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

fix: batching with zod .optional() input #669

Merged
merged 19 commits into from Jul 19, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 21 additions & 3 deletions packages/server/src/procedure.ts
Expand Up @@ -57,19 +57,37 @@ export abstract class Procedure<
this.inputParser = opts.inputParser;
}

private execParser(fn: (v: unknown) => TInput, rawInput: unknown): TInput {
if (rawInput !== null) {
return fn(rawInput);
}
// do potentially second pass to see if we can parse it as `undefined` if rawInput was `null`
// this is because JSON.stringify() will convert e.g. [undefined] to [null]
// https://github.com/trpc/trpc/pull/669
try {
return fn(rawInput);
} catch (err) {
try {
return fn(undefined);
} catch {
throw err;
}
}
}

private parseInput(rawInput: unknown): TInput {
try {
const parser: any = this.inputParser;

if (typeof parser === 'function') {
return parser(rawInput);
return this.execParser(parser, rawInput);
}
if (typeof parser.parse === 'function') {
return parser.parse(rawInput);
return this.execParser(parser.parse, rawInput);
}

if (typeof parser.validateSync === 'function') {
return parser.validateSync(rawInput);
return this.execParser(parser.validateSync, rawInput);
}

throw new Error('Could not find a validator fn');
Expand Down
31 changes: 31 additions & 0 deletions packages/server/test/index.test.tsx
Expand Up @@ -595,3 +595,34 @@ describe('TRPCAbortError', () => {
close();
});
});

test('regression: JSON.stringify([undefined]) gives [null] causes wrong type to procedure input', async () => {
const { client, close } = routerToServerAndClient(
trpc.router().query('q', {
input: z.string().optional(),
async resolve({ input }) {
return { input };
},
}),
{
client({ httpUrl }) {
return {
links: [httpBatchLink({ url: httpUrl })],
};
},
server: {
batching: {
enabled: true,
},
},
},
);

expect(await client.query('q', 'foo')).toMatchInlineSnapshot(`
Object {
"input": "foo",
}
`);
expect(await client.query('q')).toMatchInlineSnapshot(`Object {}`);
close();
});