Skip to content
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

Feat: Support x-www-form-urlencoded request bodies #222

Merged
merged 2 commits into from
Jan 2, 2023
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
23 changes: 12 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ Please note:

## HTTP Requests

Procedures with a `GET`/`DELETE` method will accept inputs via URL `query parameters`. Procedures with a `POST`/`PATCH`/`PUT` method will accept inputs via the `request body` with a `application/json` content type.
Procedures with a `GET`/`DELETE` method will accept inputs via URL `query parameters`. Procedures with a `POST`/`PATCH`/`PUT` method will accept inputs via the `request body` with a `application/json` or `application/x-www-form-urlencoded` content type.

### Path parameters

Expand Down Expand Up @@ -302,16 +302,17 @@ Please see [full typings here](src/generator/index.ts).

Please see [full typings here](src/types.ts).

| Property | Type | Description | Required | Default |
| ------------- | ------------------- | ------------------------------------------------------------------------------------------------------------ | -------- | ----------- |
| `enabled` | `boolean` | Exposes this procedure to `trpc-openapi` adapters and on the OpenAPI document. | `false` | `true` |
| `method` | `HttpMethod` | HTTP method this endpoint is exposed on. Value can be `GET`, `POST`, `PATCH`, `PUT` or `DELETE`. | `true` | `undefined` |
| `path` | `string` | Pathname this endpoint is exposed on. Value must start with `/`, specify path parameters using `{}`. | `true` | `undefined` |
| `protect` | `boolean` | Requires this endpoint to use an `Authorization` header credential with `Bearer` scheme on OpenAPI document. | `false` | `false` |
| `summary` | `string` | A short summary of the endpoint included in the OpenAPI document. | `false` | `undefined` |
| `description` | `string` | A verbose description of the endpoint included in the OpenAPI document. | `false` | `undefined` |
| `tags` | `string[]` | A list of tags used for logical grouping of endpoints in the OpenAPI document. | `false` | `undefined` |
| `headers` | `ParameterObject[]` | An array of custom headers to add for this endpoint in the OpenAPI document. | `false` | `undefined` |
| Property | Type | Description | Required | Default |
| -------------- | ------------------- | ------------------------------------------------------------------------------------------------------------ | -------- | ---------------------- |
| `enabled` | `boolean` | Exposes this procedure to `trpc-openapi` adapters and on the OpenAPI document. | `false` | `true` |
| `method` | `HttpMethod` | HTTP method this endpoint is exposed on. Value can be `GET`, `POST`, `PATCH`, `PUT` or `DELETE`. | `true` | `undefined` |
| `path` | `string` | Pathname this endpoint is exposed on. Value must start with `/`, specify path parameters using `{}`. | `true` | `undefined` |
| `protect` | `boolean` | Requires this endpoint to use an `Authorization` header credential with `Bearer` scheme on OpenAPI document. | `false` | `false` |
| `summary` | `string` | A short summary of the endpoint included in the OpenAPI document. | `false` | `undefined` |
| `description` | `string` | A verbose description of the endpoint included in the OpenAPI document. | `false` | `undefined` |
| `tags` | `string[]` | A list of tags used for logical grouping of endpoints in the OpenAPI document. | `false` | `undefined` |
| `headers` | `ParameterObject[]` | An array of custom headers to add for this endpoint in the OpenAPI document. | `false` | `undefined` |
| `contentTypes` | `ContentType[]` | A set of content types specified as accepted in the OpenAPI document. | `false` | `['application/json']` |

#### CreateOpenApiNodeHttpHandlerOptions

Expand Down
4 changes: 2 additions & 2 deletions src/adapters/node-http/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ export const getBody = async (req: NodeHTTPRequest, maxBodySize = BODY_100_KB):

req.body = undefined;

if (req.headers['content-type'] === 'application/json') {
if (req.headers['content-type']) {
try {
const { raw, parsed } = await parse.json(req, {
const { raw, parsed } = await parse(req, {
limit: maxBodySize,
strict: false,
returnRawBody: true,
Expand Down
12 changes: 11 additions & 1 deletion src/generator/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,30 @@ export const getOpenApiPathsObject = (
const path = normalizePath(openapi.path);
const pathParameters = getPathParameters(path);
const headerParameters = headers?.map((header) => ({ ...header, in: 'header' })) || [];

const httpMethod = OpenAPIV3.HttpMethods[method];
if (!httpMethod) {
throw new TRPCError({
message: 'Method must be GET, POST, PATCH, PUT or DELETE',
code: 'INTERNAL_SERVER_ERROR',
});
}

if (pathsObject[path]?.[httpMethod]) {
throw new TRPCError({
message: `Duplicate procedure defined for route ${method} ${path}`,
code: 'INTERNAL_SERVER_ERROR',
});
}

const contentTypes = openapi.contentTypes || ['application/json'];
if (contentTypes.length === 0) {
throw new TRPCError({
message: 'At least one content type must be specified',
code: 'INTERNAL_SERVER_ERROR',
});
}

const { inputParser, outputParser } = getInputOutputParsers(procedure);

pathsObject[path] = {
Expand All @@ -55,7 +65,7 @@ export const getOpenApiPathsObject = (
security: protect ? [{ Authorization: [] }] : undefined,
...(acceptsRequestBody(method)
? {
requestBody: getRequestBodyObject(inputParser, pathParameters),
requestBody: getRequestBodyObject(inputParser, pathParameters, contentTypes),
parameters: [
...headerParameters,
...(getParameterObjects(inputParser, pathParameters, 'path') || []),
Expand Down
16 changes: 11 additions & 5 deletions src/generator/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { OpenAPIV3 } from 'openapi-types';
import { z } from 'zod';
import zodToJsonSchema from 'zod-to-json-schema';

import { OpenApiContentType } from '../types';
import {
instanceofZodType,
instanceofZodTypeCoercible,
Expand Down Expand Up @@ -113,6 +114,7 @@ export const getParameterObjects = (
export const getRequestBodyObject = (
schema: unknown,
pathParameters: string[],
contentTypes: OpenApiContentType[],
): OpenAPIV3.RequestBodyObject | undefined => {
if (!instanceofZodType(schema)) {
throw new TRPCError({
Expand Down Expand Up @@ -142,13 +144,17 @@ export const getRequestBodyObject = (
});
const dedupedSchema = unwrappedSchema.omit(mask);

const openApiSchemaObject = zodSchemaToOpenApiSchemaObject(dedupedSchema);
const content: OpenAPIV3.RequestBodyObject['content'] = {};
for (const contentType of contentTypes) {
content[contentType] = {
schema: openApiSchemaObject,
};
}

return {
required: isRequired,
content: {
'application/json': {
schema: zodSchemaToOpenApiSchemaObject(dedupedSchema),
},
},
content,
};
};

Expand Down
3 changes: 3 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ export type OpenApiMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';

type TRPCMeta = Record<string, unknown>;

export type OpenApiContentType = 'application/json' | 'application/x-www-form-urlencoded';

export type OpenApiMeta<TMeta = TRPCMeta> = TMeta & {
openapi?: {
enabled?: boolean;
Expand All @@ -18,6 +20,7 @@ export type OpenApiMeta<TMeta = TRPCMeta> = TMeta & {
protect?: boolean;
tags?: string[];
headers?: (OpenAPIV3.ParameterBaseObject & { name: string; in?: 'header' })[];
contentTypes?: OpenApiContentType[];
};
};

Expand Down
35 changes: 35 additions & 0 deletions test/adapters/standalone.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1254,4 +1254,39 @@ describe('standalone adapter', () => {

close();
});

test('with x-www-form-urlencoded', async () => {
const appRouter = t.router({
echo: t.procedure
.meta({
openapi: {
method: 'POST',
path: '/echo',
contentTypes: ['application/x-www-form-urlencoded'],
},
})
.input(z.object({ payload: z.array(z.string()) }))
.output(z.object({ result: z.string() }))
.query(({ input }) => ({ result: input.payload.join(' ') })),
});

const { url, close } = createHttpServerWithRouter({
router: appRouter,
});

const res = await fetch(`${url}/echo`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'payload=Hello&payload=World',
});
const body = await res.json();

expect(res.status).toBe(200);
expect(body).toEqual({ result: 'Hello World' });
expect(createContextMock).toHaveBeenCalledTimes(1);
expect(responseMetaMock).toHaveBeenCalledTimes(1);
expect(onErrorMock).toHaveBeenCalledTimes(0);

close();
});
});
117 changes: 117 additions & 0 deletions test/generator.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { initTRPC } from '@trpc/server';
import { observable } from '@trpc/server/observable';
import openAPISchemaValidator from 'openapi-schema-validator';
import { OpenAPIV3 } from 'openapi-types';
import { z } from 'zod';

import {
Expand Down Expand Up @@ -1697,6 +1698,45 @@ describe('generator', () => {
`);
});

test('with coerce', () => {
const appRouter = t.router({
transform: t.procedure
.meta({ openapi: { method: 'GET', path: '/coerce' } })
.input(z.object({ payload: z.number() }))
.output(z.number())
.query(({ input }) => input.payload),
});

const openApiDocument = generateOpenApiDocument(appRouter, defaultDocOpts);

expect(openApiSchemaValidator.validate(openApiDocument).errors).toEqual([]);
expect(openApiDocument.paths['/coerce']!.get!.parameters).toMatchInlineSnapshot(`
Array [
Object {
"description": undefined,
"in": "query",
"name": "payload",
"required": true,
"schema": Object {
"type": "number",
},
},
]
`);
expect(openApiDocument.paths['/coerce']!.get!.responses[200]).toMatchInlineSnapshot(`
Object {
"content": Object {
"application/json": Object {
"schema": Object {
"type": "number",
},
},
},
"description": "Successful response",
}
`);
});

test('with union', () => {
{
const appRouter = t.router({
Expand Down Expand Up @@ -2459,4 +2499,81 @@ describe('generator', () => {
}
`);
});

test('with content types', () => {
{
const appRouter = t.router({
withNone: t.procedure
.meta({ openapi: { method: 'POST', path: '/with-none', contentTypes: [] } })
.input(z.object({ payload: z.string() }))
.output(z.object({ payload: z.string() }))
.mutation(({ input }) => ({ payload: input.payload })),
});

expect(() => {
generateOpenApiDocument(appRouter, defaultDocOpts);
}).toThrowError('[mutation.withNone] - At least one content type must be specified');
}
{
const appRouter = t.router({
withUrlencoded: t.procedure
.meta({
openapi: {
method: 'POST',
path: '/with-urlencoded',
contentTypes: ['application/x-www-form-urlencoded'],
},
})
.input(z.object({ payload: z.string() }))
.output(z.object({ payload: z.string() }))
.mutation(({ input }) => ({ payload: input.payload })),
withJson: t.procedure
.meta({
openapi: { method: 'POST', path: '/with-json', contentTypes: ['application/json'] },
})
.input(z.object({ payload: z.string() }))
.output(z.object({ payload: z.string() }))
.mutation(({ input }) => ({ payload: input.payload })),
withAll: t.procedure
.meta({
openapi: {
method: 'POST',
path: '/with-all',
contentTypes: ['application/json', 'application/x-www-form-urlencoded'],
},
})
.input(z.object({ payload: z.string() }))
.output(z.object({ payload: z.string() }))
.mutation(({ input }) => ({ payload: input.payload })),
withDefault: t.procedure
.meta({ openapi: { method: 'POST', path: '/with-default' } })
.input(z.object({ payload: z.string() }))
.output(z.object({ payload: z.string() }))
.mutation(({ input }) => ({ payload: input.payload })),
});

const openApiDocument = generateOpenApiDocument(appRouter, defaultDocOpts);

expect(openApiSchemaValidator.validate(openApiDocument).errors).toEqual([]);
expect(
Object.keys((openApiDocument.paths['/with-urlencoded']!.post!.requestBody as any).content),
).toEqual(['application/x-www-form-urlencoded']);
expect(
Object.keys((openApiDocument.paths['/with-json']!.post!.requestBody as any).content),
).toEqual(['application/json']);
expect(
Object.keys((openApiDocument.paths['/with-all']!.post!.requestBody as any).content),
).toEqual(['application/json', 'application/x-www-form-urlencoded']);
expect(
(openApiDocument.paths['/with-all']!.post!.requestBody as any).content['application/json'],
).toEqual(
(openApiDocument.paths['/with-all']!.post!.requestBody as any).content[
'application/x-www-form-urlencoded'
],
);
expect(
Object.keys((openApiDocument.paths['/with-default']!.post!.requestBody as any).content),
).toEqual(['application/json']);
}
});
});