Skip to content
This repository was archived by the owner on Nov 19, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions src/generator/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import zodToJsonSchema from 'zod-to-json-schema';
import {
instanceofZod,
instanceofZodTypeLikeObject,
instanceofZodTypeLikeOptional,
instanceofZodTypeLikeString,
instanceofZodTypeLikeVoid,
} from '../utils';
Expand Down Expand Up @@ -60,7 +61,9 @@ export const getParameterObjects = (
return true;
})
.map((shapeKey) => {
const shapeSchema = shape[shapeKey]!;
let shapeSchema = shape[shapeKey]!;
const isRequired = !shapeSchema.isOptional();
const isPathParameter = pathParameters.includes(shapeKey);

if (!instanceofZodTypeLikeString(shapeSchema)) {
throw new TRPCError({
Expand All @@ -69,13 +72,22 @@ export const getParameterObjects = (
});
}

const isPathParameter = pathParameters.includes(shapeKey);
if (instanceofZodTypeLikeOptional(shapeSchema)) {
if (isPathParameter) {
throw new TRPCError({
message: `Path parameter: "${shapeKey}" must not be optional`,
code: 'INTERNAL_SERVER_ERROR',
});
}
shapeSchema = shapeSchema.unwrap();
}

const { description, ...schema } = zodSchemaToOpenApiSchemaObject(shapeSchema);

return {
name: shapeKey,
in: isPathParameter ? 'path' : 'query',
required: isPathParameter || !shapeSchema.isOptional(),
required: isPathParameter || isRequired,
schema: schema,
description: description,
};
Expand Down
6 changes: 6 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,9 @@ export const instanceofZodTypeLikeString = (type: z.ZodTypeAny): boolean => {
}
return instanceofZodTypeKind(type, z.ZodFirstPartyTypeKind.ZodString);
};

export const instanceofZodTypeLikeOptional = (
type: z.ZodTypeAny,
): type is z.ZodOptional<z.ZodTypeAny> => {
return instanceofZodTypeKind(type, z.ZodFirstPartyTypeKind.ZodOptional);
};
75 changes: 74 additions & 1 deletion test/generator.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as trpc from '@trpc/server';
import { Subscription } from '@trpc/server';
import e from 'express';
import openAPISchemaValidator from 'openapi-schema-validator';
import { z } from 'zod';

Expand Down Expand Up @@ -620,6 +619,23 @@ describe('generator', () => {
}).toThrowError('[query.pathParameters] - Input parser must be a ZodObject');
});

test('with optional path parameters', () => {
const appRouter = trpc.router().query('pathParameters', {
meta: { openapi: { enabled: true, path: '/path-parameters/{name}', method: 'GET' } },
input: z.object({ name: z.string().optional() }),
output: z.object({ name: z.string() }),
resolve: () => ({ name: 'asdf' }),
});

expect(() => {
generateOpenApiDocument(appRouter, {
title: 'tRPC OpenAPI',
version: '1.0.0',
baseUrl: 'http://localhost:3000/api',
});
}).toThrowError('[query.pathParameters] - Path parameter: "name" must not be optional');
});

test('with missing path parameters', () => {
const appRouter = trpc.router().query('pathParameters', {
meta: { openapi: { enabled: true, path: '/path-parameters/{name}', method: 'GET' } },
Expand Down Expand Up @@ -1577,4 +1593,61 @@ describe('generator', () => {
}
`);
});

test('with optional query input parameter', () => {
const appRouter = trpc.router<any, OpenApiMeta>().query('optional', {
meta: { openapi: { enabled: true, path: '/optional', method: 'GET' } },
input: z.object({ payload: z.string().optional() }),
output: z.string().optional(),
resolve: ({ input }) => input.payload,
});

const openApiDocument = generateOpenApiDocument(appRouter, {
title: 'tRPC OpenAPI',
version: '1.0.0',
baseUrl: 'http://localhost:3000/api',
});

expect(openApiSchemaValidator.validate(openApiDocument).errors).toEqual([]);
expect(openApiDocument.paths['/optional']!.get!.parameters).toMatchInlineSnapshot(`
Array [
Object {
"description": undefined,
"in": "query",
"name": "payload",
"required": false,
"schema": Object {
"type": "string",
},
},
]
`);
expect(openApiDocument.paths['/optional']!.get!.responses[200]).toMatchInlineSnapshot(`
Object {
"content": Object {
"application/json": Object {
"schema": Object {
"additionalProperties": false,
"properties": Object {
"data": Object {
"type": "string",
},
"ok": Object {
"enum": Array [
true,
],
"type": "boolean",
},
},
"required": Array [
"ok",
],
"type": "object",
},
},
},
"description": "Successful response",
}
`);
});
});