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

V9 refactoring and cleanup #732

Merged
merged 23 commits into from
Aug 20, 2021
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
3 changes: 3 additions & 0 deletions examples/next-prisma-todomvc/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
17 changes: 9 additions & 8 deletions packages/client/src/internals/httpRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,21 @@ export function httpRequest<TResponseShape = TRPCResponse>(
mutation: 'POST',
subscription: 'PATCH',
};
const input = 'input' in props ? props.input : arrayToDict(props.inputs);
const input =
'input' in props
? rt.transformer.serialize(props.input)
: arrayToDict(
props.inputs.map((_input) => rt.transformer.serialize(_input)),
);

function getUrl() {
let url = props.url + '/' + path;
const queryParts: string[] = [];
if ('inputs' in props) {
queryParts.push('batch=1');
}
if (type === 'query' && input !== undefined) {
queryParts.push(
`input=${encodeURIComponent(
JSON.stringify(rt.transformer.serialize(input)),
)}`,
);
queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
}
if (queryParts.length) {
url += '?' + queryParts.join('&');
Expand All @@ -50,8 +52,7 @@ export function httpRequest<TResponseShape = TRPCResponse>(
if (type === 'query') {
return undefined;
}
const rawInput = rt.transformer.serialize(input);
return rawInput !== undefined ? JSON.stringify(rawInput) : undefined;
return input !== undefined ? JSON.stringify(input) : undefined;
}

const promise = new Promise<TResponseShape>((resolve, reject) => {
Expand Down
28 changes: 0 additions & 28 deletions packages/server/src/http/errors.ts

This file was deleted.

1 change: 0 additions & 1 deletion packages/server/src/http/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { assertNotBrowser } from '../assertNotBrowser';
export * from './errors';
export * from './requestHandler';
assertNotBrowser();
3 changes: 1 addition & 2 deletions packages/server/src/http/internals/getHTTPStatusCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ const JSONRPC2_TO_HTTP_CODE: Record<
> = {
PARSE_ERROR: 400,
BAD_REQUEST: 400,
METHOD_NOT_FOUND: 405,
PATH_NOT_FOUND: 404,
NOT_FOUND: 404,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why no 405 METHOD_NOT_ALLOWED?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's removed now anyway :)

INTERNAL_SERVER_ERROR: 500,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
Expand Down
42 changes: 17 additions & 25 deletions packages/server/src/http/requestHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,6 @@ async function getRequestParams({
}

const body = await getPostBody({ req, maxBodySize });
/**
* @deprecated TODO delete me for next major
* */
if (
body &&
typeof body === 'object' &&
'input' in body &&
Object.keys(body).length === 1
) {
// legacy format
return { input: body.input };
}

return { input: body };
}
Expand Down Expand Up @@ -95,7 +83,7 @@ export async function requestHandler<
}
const type =
HTTP_METHOD_PROCEDURE_TYPE_MAP[req.method!] ?? ('unknown' as const);
let input: unknown = undefined;
const input: unknown = undefined;
let ctx: inferRouterContext<TRouter> | undefined = undefined;

const reqQueryParams = req.query
Expand Down Expand Up @@ -124,29 +112,33 @@ export async function requestHandler<
type,
});

input =
rawInput !== undefined
? router._def.transformer.input.deserialize(rawInput)
: undefined;
ctx = await createContext?.({ req, res });

const getInputs = (): unknown[] | Record<number, unknown> => {
const getInputs = (): Record<number, unknown> => {
if (!isBatchCall) {
return [input];
return {
0: router._def.transformer.input.deserialize(rawInput),
};
}

// TODO - next major, delete `Array.isArray()`
if (
!Array.isArray(input) &&
(typeof input !== 'object' || input == null)
rawInput == null ||
typeof rawInput !== 'object' ||
Array.isArray(rawInput)
) {
throw new TRPCError({
code: 'BAD_REQUEST',
message:
'"input" needs to be an array or object when doing a batch call',
message: '"input" needs to be an object when doing a batch call',
});
}
return input as any;
const input: Record<number, unknown> = {};
for (const key in rawInput) {
const k = key as any as number;
input[k] = router._def.transformer.input.deserialize(
(rawInput as any)[k],
);
}
return input;
};
const inputs = getInputs();
const paths = isBatchCall ? opts.path.split(',') : [opts.path];
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ export class Router<

if (!procedure) {
throw new TRPCError({
code: 'PATH_NOT_FOUND',
code: 'NOT_FOUND',
message: `No "${type}"-procedure on path "${path}"`,
});
}
Expand Down
8 changes: 2 additions & 6 deletions packages/server/src/rpc/codes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,15 @@ export const TRPC_ERROR_CODES_BY_KEY = {
/**
* The JSON sent is not a valid Request object.
*/
BAD_REQUEST: -32600,
/**
* The method does not exist / is not available.
*/
METHOD_NOT_FOUND: -32601,
BAD_REQUEST: -32600, // 400
/**
* Internal JSON-RPC error.
*/
INTERNAL_SERVER_ERROR: -32603,
// Implementation specific errors
UNAUTHORIZED: -32001, // 401
FORBIDDEN: -32003, // 403
PATH_NOT_FOUND: -32004, // 404
NOT_FOUND: -32004, // 404
METHOD_NOT_SUPPORTED: -32005, // 405
TIMEOUT: -32008, // 408
PAYLOAD_TOO_LARGE: -32013, // 413
Expand Down
4 changes: 2 additions & 2 deletions packages/server/test/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ test('input error', async () => {
close();
});

test('httpError.unauthorized()', async () => {
test('unauthorized()', async () => {
const onError = jest.fn();
const { client, close } = routerToServerAndClient(
trpc.router().query('err', {
Expand Down Expand Up @@ -249,7 +249,7 @@ test('make sure object is ignoring prototype', async () => {
expect(clientError.shape.code).toMatchInlineSnapshot(`-32004`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0][0].error;
expect(serverError.code).toMatchInlineSnapshot(`"PATH_NOT_FOUND"`);
expect(serverError.code).toMatchInlineSnapshot(`"NOT_FOUND"`);

close();
});
Expand Down
4 changes: 2 additions & 2 deletions packages/server/test/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { createWSClient, wsLink } from '../../client/src/links/wsLink';
import { z } from 'zod';
import { TRPCClientError } from '../../client/src';
import * as trpc from '../src';
import { CreateHttpContextOptions, Maybe } from '../src';
import { CreateHttpContextOptions, Maybe, TRPCError } from '../src';
import { routerToServerAndClient } from './_testHelpers';
import WebSocket from 'ws';
import { waitFor } from '@testing-library/react';
Expand Down Expand Up @@ -270,7 +270,7 @@ describe('integration tests', () => {
trpc.router<Context>().query('whoami', {
async resolve({ ctx }) {
if (!ctx.user) {
throw trpc.httpError.unauthorized();
throw new TRPCError({ code: 'UNAUTHORIZED' });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likimng this syntax 👍🏻

}
return ctx.user;
},
Expand Down
10 changes: 5 additions & 5 deletions packages/server/test/middleware.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { routerToServerAndClient } from './_testHelpers';
import * as trpc from '../src';
import { httpError } from '../src';
import { TRPCError } from '../src';
import { routerToServerAndClient } from './_testHelpers';

test('is called if def first', async () => {
const middleware = jest.fn();
Expand Down Expand Up @@ -76,7 +76,7 @@ test('allows you to throw an error (e.g. auth)', async () => {
.router<Context>()
.middleware(({ ctx }) => {
if (!ctx.user?.isAdmin) {
throw httpError.unauthorized();
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
})
.query('secretPlace', {
Expand Down Expand Up @@ -197,7 +197,7 @@ test('equiv', () => {
.router<Context>()
.middleware(({ ctx }) => {
if (!ctx.user?.isAdmin) {
throw httpError.unauthorized();
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
})
.query('secretPlace', {
Expand All @@ -219,7 +219,7 @@ test('equiv', () => {
.router<Context>()
.middleware(({ ctx }) => {
if (!ctx.user?.isAdmin) {
throw httpError.unauthorized();
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
})
.query('admin.secretPlace', {
Expand Down
69 changes: 0 additions & 69 deletions packages/server/test/rawFetch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,78 +30,9 @@ const factory = () =>
}),
);

/**
* @deprecated TODO delete in next major
**/
test('call mutation with `input`-prop', async () => {
const { close, httpUrl } = factory();

const res = await fetch(`${httpUrl}/myMutation`, {
method: 'POST',
body: JSON.stringify({
input: {
name: 'alexdotjs',
},
}),
});
const json = await res.json();

expect(json).toHaveProperty('result');
expect(json.result).toMatchInlineSnapshot(`
Object {
"data": Object {
"input": Object {
"name": "alexdotjs",
},
},
"type": "data",
}
`);

close();
});

test('batching with raw batch', async () => {
const { close, httpUrl } = factory();

{
/**
* @deprecated TODO delete in next major
**/
const res = await fetch(
`${httpUrl}/myQuery?batch=1&input=${JSON.stringify([])}`,
);
const json = await res.json();

expect(json[0]).toHaveProperty('result');
expect(json[0].result).toMatchInlineSnapshot(`
Object {
"data": "default",
"type": "data",
}
`);
}

{
/**
* @deprecated TODO - remove in next major
**/
const res = await fetch(
`${httpUrl}/myQuery?batch=1&input=${JSON.stringify([
{ name: 'alexdotjs' },
])}`,
);
const json = await res.json();

expect(json[0]).toHaveProperty('result');
expect(json[0].result).toMatchInlineSnapshot(`
Object {
"data": "alexdotjs",
"type": "data",
}
`);
}

{
const res = await fetch(
`${httpUrl}/myQuery?batch=1&input=${JSON.stringify({
Expand Down
3 changes: 2 additions & 1 deletion packages/server/test/react.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
TRPCWebSocketClient,
} from '../../client/src/links/wsLink';
import { splitLink } from '../../client/src/links/splitLink';
import { TRPCError } from '../src/TRPCError';

setLogger({
log() {},
Expand Down Expand Up @@ -92,7 +93,7 @@ function createAppRouter() {
postById(input);
const post = db.posts.find((p) => p.id === input);
if (!post) {
throw trpcServer.httpError.notFound();
throw new TRPCError({ code: 'NOT_FOUND' });
}
return post;
},
Expand Down
2 changes: 1 addition & 1 deletion packages/server/test/websockets.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ test('not found error', async () => {
);

expect(error.name).toBe('TRPCClientError');
expect(error.shape?.data.code).toMatchInlineSnapshot(`"PATH_NOT_FOUND"`);
expect(error.shape?.data.code).toMatchInlineSnapshot(`"NOT_FOUND"`);

close();
});
Expand Down
3 changes: 2 additions & 1 deletion www/docs/server/authorization.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export const appRouter = createRouter()

```ts
import * as trpc from '@trpc/server';
import { TRPCError } from '@trpc/server';
import { createRouter } from './[trpc]';

export const appRouter = createRouter()
Expand All @@ -90,7 +91,7 @@ export const appRouter = createRouter()
// this protectes all procedures defined after in this router
.middleware(async ({ ctx }) => {
if (!ctx.user?.isAdmin) {
throw httpError.unauthorized();
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
})
.query('secret', {
Expand Down
2 changes: 1 addition & 1 deletion www/docs/server/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,6 @@ throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Optional Message'
// "FORBIDDEN"
// "BAD_REQUEST"
// "INTERNAL_SERVER_ERROR"
// "PATH_NOT_FOUND"
// "NOT_FOUND"
// "TIMEOUT"
```