-
Notifications
You must be signed in to change notification settings - Fork 1
feat: add new way of defining api contracts #902
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1563ccd
feat: add new way of defining api contracts
d6f1604
chore: exec lint fix
6a56781
chore: adjust type in README
758668c
chore: resolve tests issues
fce65b8
chore: remove unneeded type assertion
d083dd8
chore: adjust ContractNoBody type
d801ccb
chore: use CommonRouteDefinitionMetadata
2a0003b
chore: rename responses by status code
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,236 @@ | ||
| # api-contracts | ||
|
|
||
| API contracts are shared definitions that live in a shared package and are consumed by both the client and the backend. The contract describes a route — its path, HTTP method, and request/response schemas — and serves as the single source of truth for both sides. | ||
|
|
||
| The backend implements the route against the contract. The client uses the same contract to make type-safe requests without duplicating configuration. This eliminates assumptions across the boundary and keeps documentation, validation, and types in sync. | ||
|
|
||
| ## Defining contracts | ||
|
|
||
| ### REST routes | ||
|
|
||
| ```ts | ||
| import { defineApiContract, ContractNoBody } from '@lokalise/api-contracts' | ||
| import { z } from 'zod/v4' | ||
|
|
||
| // GET with path params | ||
| const getUser = defineApiContract({ | ||
| method: 'get', | ||
| requestPathParamsSchema: z.object({ userId: z.uuid() }), | ||
| pathResolver: ({ userId }) => `/users/${userId}`, | ||
| responsesByStatusCode: { | ||
| 200: z.object({ id: z.string(), name: z.string() }), | ||
| }, | ||
| }) | ||
|
|
||
| // POST | ||
| const createUser = defineApiContract({ | ||
| method: 'post', | ||
| pathResolver: () => '/users', | ||
| requestBodySchema: z.object({ name: z.string() }), | ||
| responsesByStatusCode: { | ||
| 201: z.object({ id: z.string(), name: z.string() }), | ||
| }, | ||
| }) | ||
|
|
||
| // DELETE with no response body | ||
| const deleteUser = defineApiContract({ | ||
| method: 'delete', | ||
| requestPathParamsSchema: z.object({ userId: z.uuid() }), | ||
| pathResolver: ({ userId }) => `/users/${userId}`, | ||
| responsesByStatusCode: { | ||
| 204: ContractNoBody, | ||
| }, | ||
| }) | ||
| ``` | ||
|
|
||
| ### Non-JSON responses | ||
|
|
||
| Use `textResponse` for plain-text or CSV responses, and `blobResponse` for binary responses (images, PDFs, etc.). Both carry the content type. | ||
|
|
||
| ```ts | ||
| import { defineApiContract, textResponse, blobResponse } from '@lokalise/api-contracts' | ||
|
|
||
| const exportCsv = defineApiContract({ | ||
| method: 'get', | ||
| pathResolver: () => '/export.csv', | ||
| responsesByStatusCode: { | ||
| 200: textResponse('text/csv'), | ||
| }, | ||
| }) | ||
|
|
||
| const downloadPhoto = defineApiContract({ | ||
| method: 'get', | ||
| pathResolver: () => '/photo.png', | ||
| responsesByStatusCode: { | ||
| 200: blobResponse('image/png'), | ||
| }, | ||
| }) | ||
| ``` | ||
|
|
||
| ### SSE and dual-mode routes | ||
|
|
||
| Use `sseResponse()` inside `responsesByStatusCode` to define SSE event schemas. For endpoints that can respond with either JSON or an SSE stream depending on the `Accept` header, use `anyOfResponses()` to declare both options on the same status code. | ||
|
|
||
| ```ts | ||
| import { defineApiContract, sseResponse, anyOfResponses } from '@lokalise/api-contracts' | ||
| import { z } from 'zod/v4' | ||
|
|
||
| // SSE-only | ||
| const notifications = defineApiContract({ | ||
| method: 'get', | ||
| pathResolver: () => '/notifications/stream', | ||
| responsesByStatusCode: { | ||
| 200: sseResponse({ | ||
| notification: z.object({ id: z.string(), message: z.string() }), | ||
| }), | ||
| }, | ||
| }) | ||
|
|
||
| // Dual-mode: JSON response or SSE stream depending on Accept header | ||
| const chatCompletion = defineApiContract({ | ||
| method: 'post', | ||
| pathResolver: () => '/chat/completions', | ||
| requestBodySchema: z.object({ message: z.string() }), | ||
| responsesByStatusCode: { | ||
| 200: anyOfResponses([ | ||
| sseResponse({ | ||
| chunk: z.object({ delta: z.string() }), | ||
| done: z.object({ finish_reason: z.string() }), | ||
| }), | ||
| z.object({ text: z.string() }), | ||
| ]), | ||
| }, | ||
| }) | ||
| ``` | ||
|
|
||
| `getSseSchemaByEventName(contract)` extracts SSE event schemas from a contract: | ||
|
|
||
| ```ts | ||
| import { getSseSchemaByEventName } from '@lokalise/api-contracts' | ||
|
|
||
| getSseSchemaByEventName(notifications) | ||
| // { notification: ZodObject<...> } | ||
|
|
||
| getSseSchemaByEventName(chatCompletion) | ||
| // { chunk: ZodObject<...>, done: ZodObject<...> } | ||
| ``` | ||
|
|
||
| ### All fields | ||
|
|
||
| ```ts | ||
| defineApiContract({ | ||
| // Required | ||
| method: 'get' | 'post' | 'put' | 'patch' | 'delete', | ||
| pathResolver: (pathParams) => string, | ||
| responsesByStatusCode: { | ||
| [statusCode]: z.ZodType | ContractNoBody | TypedTextResponse | TypedBlobResponse | TypedSseResponse | AnyOfResponses | ||
| }, | ||
|
|
||
| // Path params — links pathResolver parameter type to the schema | ||
| requestPathParamsSchema: z.ZodObject, | ||
|
|
||
| // Request | ||
| requestBodySchema: z.ZodType | ContractNoBody, // POST / PUT / PATCH only | ||
| requestQuerySchema: z.ZodType, | ||
| requestHeaderSchema: z.ZodType, | ||
|
|
||
| // Response | ||
| responseHeaderSchema: z.ZodType, | ||
|
|
||
| // Documentation | ||
| summary: string, | ||
| description: string, | ||
| tags: readonly string[], | ||
| metadata: Record<string, unknown>, | ||
| }) | ||
| ``` | ||
|
|
||
| ### Header schemas | ||
|
|
||
| ```ts | ||
| const contract = defineApiContract({ | ||
| method: 'get', | ||
| pathResolver: () => '/api/data', | ||
| requestHeaderSchema: z.object({ | ||
| authorization: z.string(), | ||
| 'x-api-key': z.string(), | ||
| }), | ||
| responseHeaderSchema: z.object({ | ||
| 'x-ratelimit-remaining': z.string(), | ||
| 'cache-control': z.string(), | ||
| }), | ||
| responsesByStatusCode: { | ||
| 200: dataSchema, | ||
| }, | ||
| }) | ||
| ``` | ||
|
|
||
| ### Type utilities | ||
|
|
||
| **`InferNonSseSuccessResponses<T>`** — TypeScript output type of all non-SSE 2xx responses. JSON schemas → `z.output<T>`, `textResponse` → `string`, `blobResponse` → `Blob`, `ContractNoBody` → `undefined`, `sseResponse` → `never` (excluded). `anyOfResponses` entries are unpacked before mapping. | ||
|
|
||
| ```ts | ||
| import type { InferNonSseSuccessResponses } from '@lokalise/api-contracts' | ||
|
|
||
| type UserResponse = InferNonSseSuccessResponses<typeof getUser['responsesByStatusCode']> | ||
| // { id: string; name: string } | ||
|
|
||
| type CsvResponse = InferNonSseSuccessResponses<typeof exportCsv['responsesByStatusCode']> | ||
| // string | ||
| ``` | ||
|
|
||
| **`InferJsonSuccessResponses<T>`** — union of Zod schema types for all JSON 2xx entries. Text, Blob, SSE, and `ContractNoBody` entries are excluded. | ||
|
|
||
| **`InferSseSuccessResponses<T>`** — extracts the SSE event schema map type from a `responsesByStatusCode` map. Returns `never` when no SSE schemas are present. | ||
|
|
||
| **`HasAnySseSuccessResponse<T>`** — `true` if any 2xx entry is a `TypedSseResponse` or an `AnyOfResponses` containing one. | ||
|
|
||
| **`HasAnyJsonSuccessResponse<T>`** — `true` if any 2xx entry is a JSON Zod schema or an `AnyOfResponses` containing one. | ||
|
|
||
| **`IsNoBodySuccessResponse<T>`** — `true` when all 2xx entries are `ContractNoBody` or no 2xx status codes are defined. | ||
|
|
||
| ### Utility functions | ||
|
|
||
| **`mapApiContractToPath`** — Express/Fastify-style path pattern. | ||
|
|
||
| ```ts | ||
| import { mapApiContractToPath } from '@lokalise/api-contracts' | ||
|
|
||
| mapApiContractToPath(getUser) // "/users/:userId" | ||
| ``` | ||
|
|
||
| **`describeApiContract`** — human-readable `"METHOD /path"` string. | ||
|
|
||
| ```ts | ||
| import { describeApiContract } from '@lokalise/api-contracts' | ||
|
|
||
| describeApiContract(getUser) // "GET /users/:userId" | ||
| ``` | ||
|
|
||
| **`getSuccessResponseSchema`** — merged Zod schema from all 2xx JSON entries. `ContractNoBody` and non-JSON entries are excluded. Returns `null` when no schema is present. | ||
|
|
||
| ```ts | ||
| import { getSuccessResponseSchema } from '@lokalise/api-contracts' | ||
|
|
||
| getSuccessResponseSchema(getUser) // ZodObject | ||
| getSuccessResponseSchema(deleteUser) // null | ||
| ``` | ||
|
|
||
| **`getIsEmptyResponseExpected`** — `true` when no Zod schema exists among 2xx entries. | ||
|
|
||
| ```ts | ||
| import { getIsEmptyResponseExpected } from '@lokalise/api-contracts' | ||
|
|
||
| getIsEmptyResponseExpected(deleteUser) // true | ||
| getIsEmptyResponseExpected(getUser) // false | ||
| ``` | ||
|
|
||
| **`getSseSchemaByEventName`** — extracts SSE event schemas from a contract. Returns `null` when no SSE schemas are present. | ||
|
|
||
| ```ts | ||
| import { getSseSchemaByEventName } from '@lokalise/api-contracts' | ||
|
|
||
| getSseSchemaByEventName(notifications) // { notification: ZodObject<...> } | ||
| getSseSchemaByEventName(getUser) // null | ||
| ``` | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export const ContractNoBody = Symbol.for('ContractNoBody') |
105 changes: 105 additions & 0 deletions
105
packages/app/api-contracts/src/new/contractResponse.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import { describe, expect, it } from 'vitest' | ||
| import { z } from 'zod/v4' | ||
| import { ContractNoBody } from './constants.ts' | ||
| import { | ||
| anyOfResponses, | ||
| blobResponse, | ||
| resolveContractResponse, | ||
| sseResponse, | ||
| textResponse, | ||
| } from './contractResponse.ts' | ||
|
|
||
| describe('resolveContractResponse', () => { | ||
| describe('ContractNoBody', () => { | ||
| it('returns noContent regardless of content-type', () => { | ||
| expect(resolveContractResponse(ContractNoBody, 'application/json')).toEqual({ | ||
| kind: 'noContent', | ||
| }) | ||
| expect(resolveContractResponse(ContractNoBody, undefined)).toEqual({ kind: 'noContent' }) | ||
| }) | ||
| }) | ||
|
|
||
| describe('missing content-type', () => { | ||
| it('returns null for typed responses when content-type is absent', () => { | ||
| expect(resolveContractResponse(z.object({ id: z.string() }), undefined)).toBeNull() | ||
| expect(resolveContractResponse(textResponse('text/csv'), undefined)).toBeNull() | ||
| expect(resolveContractResponse(blobResponse('image/png'), undefined)).toBeNull() | ||
| }) | ||
| }) | ||
|
|
||
| describe('JSON (ZodType)', () => { | ||
| it('resolves to json for application/json content-type', () => { | ||
| const schema = z.object({ id: z.string() }) | ||
| const result = resolveContractResponse(schema, 'application/json') | ||
| expect(result).toEqual({ kind: 'json', schema }) | ||
| }) | ||
|
|
||
| it('returns null for non-json content-type', () => { | ||
| const schema = z.object({ id: z.string() }) | ||
| expect(resolveContractResponse(schema, 'text/plain')).toBeNull() | ||
| }) | ||
| }) | ||
|
|
||
| describe('textResponse', () => { | ||
| it('resolves to text when content-type matches', () => { | ||
| expect(resolveContractResponse(textResponse('text/csv'), 'text/csv; charset=utf-8')).toEqual({ | ||
| kind: 'text', | ||
| }) | ||
| }) | ||
|
|
||
| it('returns null when content-type does not match', () => { | ||
| expect(resolveContractResponse(textResponse('text/csv'), 'application/json')).toBeNull() | ||
| }) | ||
| }) | ||
|
|
||
| describe('blobResponse', () => { | ||
| it('resolves to blob when content-type matches', () => { | ||
| expect(resolveContractResponse(blobResponse('image/png'), 'image/png')).toEqual({ | ||
| kind: 'blob', | ||
| }) | ||
| }) | ||
|
|
||
| it('returns null when content-type does not match', () => { | ||
| expect(resolveContractResponse(blobResponse('image/png'), 'application/json')).toBeNull() | ||
| }) | ||
| }) | ||
|
|
||
| describe('sseResponse', () => { | ||
| it('resolves to sse for text/event-stream content-type', () => { | ||
| const schema = { update: z.object({ id: z.string() }) } | ||
| const result = resolveContractResponse(sseResponse(schema), 'text/event-stream') | ||
| expect(result).toEqual({ kind: 'sse', schemaByEventName: schema }) | ||
| }) | ||
|
|
||
| it('returns null for non-sse content-type', () => { | ||
| expect( | ||
| resolveContractResponse(sseResponse({ update: z.string() }), 'application/json'), | ||
| ).toBeNull() | ||
| }) | ||
| }) | ||
|
|
||
| describe('anyOfResponses', () => { | ||
| it('resolves to the first matching entry by content-type', () => { | ||
| const schema = z.object({ id: z.string() }) | ||
| const entry = anyOfResponses([textResponse('text/csv'), schema]) | ||
|
|
||
| expect(resolveContractResponse(entry, 'text/csv')).toEqual({ kind: 'text' }) | ||
| expect(resolveContractResponse(entry, 'application/json')).toEqual({ kind: 'json', schema }) | ||
| }) | ||
|
|
||
| it('resolves SSE entry inside anyOfResponses', () => { | ||
| const sseSchema = { tick: z.object({ count: z.number() }) } | ||
| const entry = anyOfResponses([sseResponse(sseSchema), z.object({ total: z.number() })]) | ||
|
|
||
| expect(resolveContractResponse(entry, 'text/event-stream')).toEqual({ | ||
| kind: 'sse', | ||
| schemaByEventName: sseSchema, | ||
| }) | ||
| }) | ||
|
|
||
| it('returns null when no entry matches content-type', () => { | ||
| const entry = anyOfResponses([textResponse('text/csv'), blobResponse('image/png')]) | ||
| expect(resolveContractResponse(entry, 'application/json')).toBeNull() | ||
| }) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.