From e6bd66c560eb9e61481b2a758e1fa625b07706ba Mon Sep 17 00:00:00 2001 From: TakuyaYagam1 Date: Thu, 8 Oct 2026 08:28:39 +0300 Subject: [PATCH] feat: add safe match response adapter --- frontend/src/entities/match/api/search.ts | 14 + frontend/src/entities/match/index.ts | 15 + .../src/entities/match/model/adapter.test.ts | 239 +++++++++++++ frontend/src/entities/match/model/adapter.ts | 320 ++++++++++++++++++ 4 files changed, 588 insertions(+) create mode 100644 frontend/src/entities/match/api/search.ts create mode 100644 frontend/src/entities/match/index.ts create mode 100644 frontend/src/entities/match/model/adapter.test.ts create mode 100644 frontend/src/entities/match/model/adapter.ts diff --git a/frontend/src/entities/match/api/search.ts b/frontend/src/entities/match/api/search.ts new file mode 100644 index 0000000..7af20c3 --- /dev/null +++ b/frontend/src/entities/match/api/search.ts @@ -0,0 +1,14 @@ +import { searchOrganizationMatches } from "../../../shared/api/endpoints/organization/organization"; +import type { MatchSearchRequest } from "../../../shared/api/schemas"; +import { matchSearchFromTransport, type MatchSearchModel } from "../model/adapter"; + +type SearchRequestOptions = Parameters[2]; + +export async function searchMatches( + organizationId: string, + request: MatchSearchRequest, + options?: SearchRequestOptions, +): Promise { + const response = await searchOrganizationMatches(organizationId, request, options); + return matchSearchFromTransport(response); +} diff --git a/frontend/src/entities/match/index.ts b/frontend/src/entities/match/index.ts new file mode 100644 index 0000000..57dd583 --- /dev/null +++ b/frontend/src/entities/match/index.ts @@ -0,0 +1,15 @@ +export { searchMatches } from "./api/search"; +export { + matchSearchFromTransport, + matchSearchToTransport, + parseMatchSearchResponse, +} from "./model/adapter"; +export type { + MatchCardModel, + MatchConfirmedCardModel, + MatchConfirmedComponentsModel, + MatchGroup, + MatchSearchModel, + MatchSearchSourceModel, + MatchUnconfirmedCardModel, +} from "./model/adapter"; diff --git a/frontend/src/entities/match/model/adapter.test.ts b/frontend/src/entities/match/model/adapter.test.ts new file mode 100644 index 0000000..ce599e6 --- /dev/null +++ b/frontend/src/entities/match/model/adapter.test.ts @@ -0,0 +1,239 @@ +import { describe, expect, it } from "vitest"; +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import { + MatchSearchResponse as matchSearchResponseSchema, + type MatchSearchResponseOutput, +} from "../../../shared/api/schemas"; +import { + matchSearchFromTransport, + matchSearchToTransport, + type MatchConfirmedCardModel, +} from "./adapter"; + +const backendHandle = "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; +const nearHandle = "cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; + +function matchResponseFixture(): MatchSearchResponseOutput { + return matchSearchResponseSchema.parse({ + source: { + kind: "bank", + filters: { + specialization: null, + confirmed_grade: null, + confirmed_category: null, + confirmation_status: null, + declared_grade: null, + stack: null, + conditions: null, + }, + }, + groups: { + main: [ + { + candidate_handle: backendHandle, + specialization: "backend", + confirmation_status: "confirmed", + declared_grade: "middle", + category: { specialization: "backend", grade: "middle" }, + strength: "strong", + public_context: { + stack: ["go"], + experience_band: "3_6", + work_formats: ["remote"], + salary_compatibility: "compatible", + }, + evidence_summary: [ + { code: "confirmed_category", state: "supports" }, + { code: "required_skill_evidence", state: "supports" }, + ], + components: { + fit: 0.82, + coverage: 0.76, + domain: 0.8, + semantics: 0.5, + percentile: 0.71, + competition: 0, + freshness: 0.6, + responsiveness: 0.5, + rank_score: 0.68, + }, + unknown_flags: [], + }, + ], + near: [ + { + candidate_handle: nearHandle, + specialization: "frontend", + confirmation_status: "confirmed", + declared_grade: "junior", + category: { specialization: "frontend", grade: "junior" }, + strength: "standard", + public_context: { + stack: null, + experience_band: null, + work_formats: null, + salary_compatibility: null, + }, + evidence_summary: [{ code: "required_skill_evidence", state: "partial" }], + components: { + fit: 0.48, + coverage: 0.18, + domain: 0.5, + semantics: 0.5, + percentile: null, + competition: 0, + freshness: 0.5, + responsiveness: 0.5, + rank_score: 0.43, + }, + unknown_flags: [{ component: "percentile", reason: "cohort_below_30" }], + }, + ], + unconfirmed: [ + { + candidate_handle: backendHandle, + specialization: "network_engineer", + confirmation_status: "unconfirmed", + declared_grade: "junior", + category: null, + strength: null, + public_context: { + stack: ["postgresql"], + experience_band: "1_3", + work_formats: ["remote"], + salary_compatibility: "compatible", + }, + evidence_summary: [{ code: "declared_grade", state: "declared_only" }], + components: { fit: 0.51, coverage: 0.38 }, + unknown_flags: [ + { component: "assessment", reason: "no_confirmation_for_specialization" }, + ], + }, + ], + }, + }); +} + +function responseWithCardField(field: string, value: unknown): unknown { + const response = matchResponseFixture(); + return { + ...response, + groups: { + ...response.groups, + main: [{ ...response.groups.main[0], [field]: value }], + }, + }; +} + +function responseWithContextField(field: string, value: unknown): unknown { + const response = matchResponseFixture(); + const [candidate] = response.groups.main; + if (!candidate) throw new Error("Fixture main card is missing."); + + return { + ...response, + groups: { + ...response.groups, + main: [ + { + ...candidate, + public_context: { ...candidate.public_context, [field]: value }, + }, + ], + }, + }; +} + +function expectInvalidResponse(value: unknown): void { + try { + matchSearchFromTransport(value); + } catch (error: unknown) { + expect(error).toBeInstanceOf(ApiRequestError); + expect(error).toMatchObject({ status: 200, code: invalidResponseCode }); + return; + } + throw new Error("Expected a non-contract response to be rejected."); +} + +describe("match response adapter", () => { + it("round-trips group, specialization, confirmation, and unknown values", () => { + const response = matchResponseFixture(); + const model = matchSearchFromTransport(response); + + expect( + model.cards.map(({ group, specialization, confirmationStatus }) => [ + group, + specialization, + confirmationStatus, + ]), + ).toEqual([ + ["main", "backend", "confirmed"], + ["near", "frontend", "confirmed"], + ["unconfirmed", "network_engineer", "unconfirmed"], + ]); + + const backend = model.cards.find( + (card) => card.group === "main" && card.specialization === "backend", + ); + const near = model.cards.find((card): card is MatchConfirmedCardModel => card.group === "near"); + const network = model.cards.find((card) => card.group === "unconfirmed"); + expect(backend).toBeDefined(); + expect(near).toBeDefined(); + expect(network).toBeDefined(); + if (!backend || !near || !network) throw new Error("Fixture match cards are missing."); + + expect(backend.candidateHandle).toBe(network.candidateHandle); + expect(backend.category).toEqual({ specialization: "backend", grade: "middle" }); + expect(network.category).toBeNull(); + expect(network.strength).toBeNull(); + expect(network.components).toEqual({ fit: 0.51, coverage: 0.38 }); + expect(near.components.percentile).toBeNull(); + expect(near.unknownFlags).toEqual([{ component: "percentile", reason: "cohort_below_30" }]); + + const roundTrip = matchSearchToTransport(model); + expect(roundTrip).toEqual(response); + expect(matchSearchFromTransport(roundTrip)).toEqual(model); + }); + + it("round-trips a need source using its requirements version", () => { + const response = matchResponseFixture(); + const needResponse = { + ...response, + source: { + kind: "need" as const, + need_id: "4d3a4a1b-4f60-44c1-9dc2-6c8e6c9d4c11", + requirements_version: 3, + }, + }; + const model = matchSearchFromTransport(needResponse); + + expect(model.source).toEqual({ + kind: "need", + needId: "4d3a4a1b-4f60-44c1-9dc2-6c8e6c9d4c11", + requirementsVersion: 3, + }); + expect(matchSearchToTransport(model)).toEqual(needResponse); + }); + + it.each([ + ["candidate", () => responseWithCardField("email", "private@example.test")], + ["candidate", () => responseWithCardField("candidate_id", "account-123")], + ["public context", () => responseWithContextField("salary_minimum", 1000)], + [ + "groups", + () => ({ + ...matchResponseFixture(), + groups: { ...matchResponseFixture().groups, debug: true }, + }), + ], + [ + "source", + () => ({ + ...matchResponseFixture(), + source: { ...matchResponseFixture().source, candidate_id: "account-123" }, + }), + ], + ])("rejects extra fields under the %s object", (_location, invalidResponse) => { + expectInvalidResponse(invalidResponse()); + }); +}); diff --git a/frontend/src/entities/match/model/adapter.ts b/frontend/src/entities/match/model/adapter.ts new file mode 100644 index 0000000..10f210e --- /dev/null +++ b/frontend/src/entities/match/model/adapter.ts @@ -0,0 +1,320 @@ +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import { + MatchSearchResponse as matchSearchResponseSchema, + type MatchSearchResponseOutput, +} from "../../../shared/api/schemas"; + +type MatchSearchSource = MatchSearchResponseOutput["source"]; +type NeedSource = Extract; +type BankSource = Extract; +type BankConditions = NonNullable; +type ConfirmedCandidate = MatchSearchResponseOutput["groups"]["main"][number]; +type UnconfirmedCandidate = MatchSearchResponseOutput["groups"]["unconfirmed"][number]; + +export type MatchGroup = "main" | "near" | "unconfirmed"; + +export type MatchSearchSourceModel = + | { + readonly kind: "need"; + readonly needId: NeedSource["need_id"]; + readonly requirementsVersion: NeedSource["requirements_version"]; + } + | { + readonly kind: "bank"; + readonly filters: { + readonly specialization: BankSource["filters"]["specialization"]; + readonly confirmedGrade: BankSource["filters"]["confirmed_grade"]; + readonly confirmedCategory: BankSource["filters"]["confirmed_category"]; + readonly confirmationStatus: BankSource["filters"]["confirmation_status"]; + readonly declaredGrade: BankSource["filters"]["declared_grade"]; + readonly stack: BankSource["filters"]["stack"]; + readonly conditions: { + readonly workFormats: BankConditions["work_formats"]; + readonly salaryCompatibility: BankConditions["salary_compatibility"]; + } | null; + }; + }; + +type MatchPublicContext = { + readonly stack: ConfirmedCandidate["public_context"]["stack"]; + readonly experienceBand: ConfirmedCandidate["public_context"]["experience_band"]; + readonly workFormats: ConfirmedCandidate["public_context"]["work_formats"]; + readonly salaryCompatibility: ConfirmedCandidate["public_context"]["salary_compatibility"]; +}; + +type MatchEvidence = ConfirmedCandidate["evidence_summary"][number]; +type MatchUnknownFlag = ConfirmedCandidate["unknown_flags"][number]; +type ConfirmedComponents = ConfirmedCandidate["components"]; +type UnconfirmedComponents = UnconfirmedCandidate["components"]; + +export type MatchConfirmedComponentsModel = Omit & { + readonly rankScore: ConfirmedComponents["rank_score"]; +}; + +export type MatchConfirmedCardModel = { + readonly group: "main" | "near"; + readonly candidateHandle: ConfirmedCandidate["candidate_handle"]; + readonly specialization: ConfirmedCandidate["specialization"]; + readonly confirmationStatus: "confirmed"; + readonly declaredGrade: ConfirmedCandidate["declared_grade"]; + readonly category: ConfirmedCandidate["category"]; + readonly strength: ConfirmedCandidate["strength"]; + readonly publicContext: MatchPublicContext; + readonly evidenceSummary: readonly MatchEvidence[]; + readonly components: MatchConfirmedComponentsModel; + readonly unknownFlags: readonly MatchUnknownFlag[]; +}; + +export type MatchUnconfirmedCardModel = { + readonly group: "unconfirmed"; + readonly candidateHandle: UnconfirmedCandidate["candidate_handle"]; + readonly specialization: UnconfirmedCandidate["specialization"]; + readonly confirmationStatus: "unconfirmed"; + readonly declaredGrade: UnconfirmedCandidate["declared_grade"]; + readonly category: null; + readonly strength: null; + readonly publicContext: MatchPublicContext; + readonly evidenceSummary: readonly MatchEvidence[]; + readonly components: UnconfirmedComponents; + readonly unknownFlags: readonly MatchUnknownFlag[]; +}; + +export type MatchCardModel = MatchConfirmedCardModel | MatchUnconfirmedCardModel; + +export type MatchSearchModel = { + readonly source: MatchSearchSourceModel; + readonly cards: readonly MatchCardModel[]; +}; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function containsOnlyContractProperties(input: unknown, parsed: unknown): boolean { + if (Array.isArray(input) || Array.isArray(parsed)) { + return ( + Array.isArray(input) && + Array.isArray(parsed) && + input.length === parsed.length && + input.every((item, index) => containsOnlyContractProperties(item, parsed[index])) + ); + } + + if (isRecord(input) || isRecord(parsed)) { + if (!isRecord(input) || !isRecord(parsed)) return false; + const parsedKeys = new Set(Object.keys(parsed)); + if (Object.keys(input).some((key) => !parsedKeys.has(key))) return false; + + return Object.entries(parsed).every( + ([key, value]) => + !Object.prototype.hasOwnProperty.call(input, key) || + containsOnlyContractProperties(input[key], value), + ); + } + + return true; +} + +function invalidMatchResponse(status: number): ApiRequestError { + return new ApiRequestError({ + status, + code: invalidResponseCode, + title: "The response does not match the API contract.", + }); +} + +export function parseMatchSearchResponse(value: unknown, status = 200): MatchSearchResponseOutput { + const parsed = matchSearchResponseSchema.safeParse(value); + if (!parsed.success || !containsOnlyContractProperties(value, parsed.data)) { + throw invalidMatchResponse(status); + } + return parsed.data; +} + +function sourceFromTransport(source: MatchSearchSource): MatchSearchSourceModel { + if (source.kind === "need") { + return { + kind: "need", + needId: source.need_id, + requirementsVersion: source.requirements_version, + }; + } + + const conditions = source.filters.conditions; + return { + kind: "bank", + filters: { + specialization: source.filters.specialization, + confirmedGrade: source.filters.confirmed_grade, + confirmedCategory: source.filters.confirmed_category, + confirmationStatus: source.filters.confirmation_status, + declaredGrade: source.filters.declared_grade, + stack: source.filters.stack, + conditions: + conditions === null + ? null + : { + workFormats: conditions.work_formats, + salaryCompatibility: conditions.salary_compatibility, + }, + }, + }; +} + +function sourceToTransport(source: MatchSearchSourceModel): MatchSearchSource { + if (source.kind === "need") { + return { + kind: "need", + need_id: source.needId, + requirements_version: source.requirementsVersion, + }; + } + + const conditions = source.filters.conditions; + return { + kind: "bank", + filters: { + specialization: source.filters.specialization, + confirmed_grade: source.filters.confirmedGrade, + confirmed_category: source.filters.confirmedCategory, + confirmation_status: source.filters.confirmationStatus, + declared_grade: source.filters.declaredGrade, + stack: source.filters.stack === null ? null : [...source.filters.stack], + conditions: + conditions === null + ? null + : { + work_formats: conditions.workFormats === null ? null : [...conditions.workFormats], + salary_compatibility: conditions.salaryCompatibility, + }, + }, + }; +} + +function publicContextFromTransport( + context: ConfirmedCandidate["public_context"], +): MatchPublicContext { + return { + stack: context.stack === null ? null : [...context.stack], + experienceBand: context.experience_band, + workFormats: context.work_formats === null ? null : [...context.work_formats], + salaryCompatibility: context.salary_compatibility, + }; +} + +function publicContextToTransport( + context: MatchPublicContext, +): ConfirmedCandidate["public_context"] { + return { + stack: context.stack === null ? null : [...context.stack], + experience_band: context.experienceBand, + work_formats: context.workFormats === null ? null : [...context.workFormats], + salary_compatibility: context.salaryCompatibility, + }; +} + +function confirmedFromTransport( + group: "main" | "near", + candidate: ConfirmedCandidate, +): MatchConfirmedCardModel { + const { rank_score: rankScore, ...components } = candidate.components; + return { + group, + candidateHandle: candidate.candidate_handle, + specialization: candidate.specialization, + confirmationStatus: candidate.confirmation_status, + declaredGrade: candidate.declared_grade, + category: candidate.category, + strength: candidate.strength, + publicContext: publicContextFromTransport(candidate.public_context), + evidenceSummary: candidate.evidence_summary.map(({ code, state }) => ({ code, state })), + components: { ...components, rankScore }, + unknownFlags: candidate.unknown_flags.map(({ component, reason }) => ({ component, reason })), + }; +} + +function unconfirmedFromTransport(candidate: UnconfirmedCandidate): MatchUnconfirmedCardModel { + return { + group: "unconfirmed", + candidateHandle: candidate.candidate_handle, + specialization: candidate.specialization, + confirmationStatus: candidate.confirmation_status, + declaredGrade: candidate.declared_grade, + category: null, + strength: null, + publicContext: publicContextFromTransport(candidate.public_context), + evidenceSummary: candidate.evidence_summary.map(({ code, state }) => ({ code, state })), + components: { fit: candidate.components.fit, coverage: candidate.components.coverage }, + unknownFlags: candidate.unknown_flags.map(({ component, reason }) => ({ component, reason })), + }; +} + +export function matchSearchFromTransport(value: unknown, status = 200): MatchSearchModel { + const response = parseMatchSearchResponse(value, status); + return { + source: sourceFromTransport(response.source), + cards: [ + ...response.groups.main.map((candidate) => confirmedFromTransport("main", candidate)), + ...response.groups.near.map((candidate) => confirmedFromTransport("near", candidate)), + ...response.groups.unconfirmed.map(unconfirmedFromTransport), + ], + }; +} + +function confirmedToTransport(candidate: MatchConfirmedCardModel): ConfirmedCandidate { + const { rankScore, ...components } = candidate.components; + return { + candidate_handle: candidate.candidateHandle, + specialization: candidate.specialization, + confirmation_status: "confirmed", + declared_grade: candidate.declaredGrade, + category: candidate.category, + strength: candidate.strength, + public_context: publicContextToTransport(candidate.publicContext), + evidence_summary: candidate.evidenceSummary.map(({ code, state }) => ({ code, state })), + components: { ...components, rank_score: rankScore }, + unknown_flags: candidate.unknownFlags.map(({ component, reason }) => ({ component, reason })), + }; +} + +function unconfirmedToTransport(candidate: MatchUnconfirmedCardModel): UnconfirmedCandidate { + return { + candidate_handle: candidate.candidateHandle, + specialization: candidate.specialization, + confirmation_status: "unconfirmed", + declared_grade: candidate.declaredGrade, + category: null, + strength: null, + public_context: publicContextToTransport(candidate.publicContext), + evidence_summary: candidate.evidenceSummary.map(({ code, state }) => ({ code, state })), + components: { fit: candidate.components.fit, coverage: candidate.components.coverage }, + unknown_flags: candidate.unknownFlags.map(({ component, reason }) => ({ component, reason })), + }; +} + +export function matchSearchToTransport(model: MatchSearchModel): MatchSearchResponseOutput { + const groups: MatchSearchResponseOutput["groups"] = { + main: [], + near: [], + unconfirmed: [], + }; + + for (const candidate of model.cards) { + switch (candidate.group) { + case "main": + groups.main.push(confirmedToTransport(candidate)); + break; + case "near": + groups.near.push(confirmedToTransport(candidate)); + break; + case "unconfirmed": + groups.unconfirmed.push(unconfirmedToTransport(candidate)); + break; + } + } + + return matchSearchResponseSchema.parse({ + source: sourceToTransport(model.source), + groups, + }); +}