level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
5,201 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/clientInternals.test.ts | import { getFetch } from '@trpc/client/src';
import { getAbortController } from '@trpc/client/src/internals/getAbortController';
describe('getAbortController() from..', () => {
test('passed', () => {
const sym: any = Symbol('test');
expect(getAbortController(sym)).toBe(sym);
});
test('window', () => {
const sym: any = Symbol('test');
(global as any).AbortController = undefined;
(global as any).window = {
AbortController: sym,
};
expect(getAbortController(null)).toBe(sym);
});
test('global', () => {
const sym: any = Symbol('test');
(global as any).AbortController = sym;
(global as any).window = undefined;
expect(getAbortController(null)).toBe(sym);
});
test('window w. undefined AbortController -> global', () => {
const sym: any = Symbol('test');
(global as any).AbortController = sym;
(global as any).window = {};
expect(getAbortController(null)).toBe(sym);
});
test('neither', () => {
(global as any).AbortController = undefined;
(global as any).window = undefined;
expect(getAbortController(null)).toBe(null);
});
});
describe('getFetch() from...', () => {
test('passed', () => {
const customImpl: any = () => true;
expect(getFetch(customImpl)).toBe(customImpl);
});
test('window', () => {
(global as any).fetch = undefined;
(global as any).window = {
fetch: () => 42,
};
expect(getFetch()('')).toBe(42);
});
test('global', () => {
(global as any).fetch = () => 1337;
(global as any).window = undefined;
delete (global as any).window;
expect(getFetch()('')).toBe(1337);
});
test('window w. undefined fetch -> global', () => {
(global as any).fetch = () => 808;
(global as any).window = {};
expect(getFetch()('')).toBe(808);
});
test('neither -> throws', () => {
(global as any).fetch = undefined;
(global as any).window = undefined;
expect(() => getFetch()).toThrowError();
});
});
|
5,202 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/dataloader.test.ts | /* eslint-disable @typescript-eslint/no-empty-function */
import { waitError, waitMs } from '../___testHelpers';
import { dataLoader } from '@trpc/client/src/internals/dataLoader';
describe('basic', () => {
const fetchFn = vi.fn();
const validateFn = vi.fn();
const loader = dataLoader<number, number>({
validate: () => {
validateFn();
return true;
},
fetch: (keys) => {
fetchFn(keys);
const promise = new Promise<number[]>((resolve) => {
resolve(keys.map((v) => v + 1));
});
return { promise, cancel: () => {} };
},
});
beforeEach(() => {
fetchFn.mockClear();
validateFn.mockClear();
});
test('no time between calls', async () => {
const $result = await Promise.all([
loader.load(1).promise,
loader.load(2).promise,
]);
expect($result).toEqual([2, 3]);
expect(validateFn.mock.calls.length).toMatchInlineSnapshot(`2`);
expect(fetchFn).toHaveBeenCalledTimes(1);
expect(fetchFn).toHaveBeenNthCalledWith(1, [1, 2]);
});
test('time between calls', async () => {
const res1 = loader.load(3);
await waitMs(1);
const res2 = loader.load(4);
const $result = await Promise.all([res1.promise, res2.promise]);
expect($result).toEqual([4, 5]);
expect(validateFn.mock.calls.length).toMatchInlineSnapshot(`2`);
expect(fetchFn).toHaveBeenCalledTimes(2);
expect(fetchFn).toHaveBeenNthCalledWith(1, [3]);
expect(fetchFn).toHaveBeenNthCalledWith(2, [4]);
});
});
describe('cancellation', () => {
const fetchFn = vi.fn();
const validateFn = vi.fn();
const cancelFn = vi.fn();
const loader = dataLoader<number, number>({
validate: () => {
return true;
},
fetch: (keys) => {
fetchFn();
const promise = new Promise<number[]>((resolve) => {
setTimeout(() => {
resolve(keys.map((v) => v + 1));
}, 10);
});
return { promise, cancel: cancelFn };
},
});
beforeEach(() => {
fetchFn.mockClear();
validateFn.mockClear();
cancelFn.mockClear();
});
test('cancel immediately before it is executed', async () => {
const res1 = loader.load(1);
const res2 = loader.load(2);
res1.cancel();
res2.cancel();
expect(fetchFn).toHaveBeenCalledTimes(0);
expect(validateFn).toHaveBeenCalledTimes(0);
expect(cancelFn).toHaveBeenCalledTimes(0);
expect(await Promise.allSettled([res1.promise, res2.promise]))
.toMatchInlineSnapshot(`
Array [
Object {
"reason": [Error: Aborted],
"status": "rejected",
},
Object {
"reason": [Error: Aborted],
"status": "rejected",
},
]
`);
});
test('cancel after some time', async () => {
const res1 = loader.load(2);
const res2 = loader.load(3);
await waitMs(1);
res1.cancel();
res2.cancel();
expect(await Promise.allSettled([res1.promise, res2.promise]))
.toMatchInlineSnapshot(`
Array [
Object {
"status": "fulfilled",
"value": 3,
},
Object {
"status": "fulfilled",
"value": 4,
},
]
`);
});
test('cancel only a single request', async () => {
const res1 = loader.load(2);
const res2 = loader.load(3);
res2.cancel();
expect(cancelFn).toHaveBeenCalledTimes(0);
expect(await Promise.allSettled([res1.promise, res2.promise]))
.toMatchInlineSnapshot(`
Array [
Object {
"status": "fulfilled",
"value": 3,
},
Object {
"reason": [Error: Aborted],
"status": "rejected",
},
]
`);
});
});
test('errors', async () => {
const loader = dataLoader<number, number>({
validate: () => true,
fetch: () => {
const promise = new Promise<number[]>((_resolve, reject) => {
reject(new Error('Some error'));
});
return { promise, cancel: () => {} };
},
});
const result1 = loader.load(1);
const result2 = loader.load(2);
await expect(result1.promise).rejects.toMatchInlineSnapshot(
`[Error: Some error]`,
);
await expect(result2.promise).rejects.toMatchInlineSnapshot(
`[Error: Some error]`,
);
});
describe('validation', () => {
const validateFn = vi.fn();
const fetchFn = vi.fn();
const loader = dataLoader<number, number>({
validate: (keys) => {
validateFn(keys);
const sum = keys.reduce((acc, key) => acc + key, 0);
return sum < 10;
},
fetch: (keys) => {
fetchFn(keys);
const promise = new Promise<number[]>((resolve) => {
resolve(keys.map((v) => v + 1));
});
return { promise, cancel: () => {} };
},
});
beforeEach(() => {
fetchFn.mockClear();
validateFn.mockClear();
});
test('1', async () => {
const $result = await Promise.all([
loader.load(1).promise,
loader.load(9).promise,
loader.load(0).promise,
]);
expect($result).toEqual([2, 10, 1]);
expect(validateFn.mock.calls.length).toMatchInlineSnapshot(`4`);
});
test('2', async () => {
const $result = await Promise.all([
loader.load(2).promise,
loader.load(9).promise,
loader.load(3).promise,
loader.load(4).promise,
loader.load(5).promise,
loader.load(1).promise,
]);
expect($result).toMatchInlineSnapshot(`
Array [
3,
10,
4,
5,
6,
2,
]
`);
expect(validateFn.mock.calls.length).toMatchInlineSnapshot(`9`);
expect(fetchFn.mock.calls.length).toMatchInlineSnapshot(`4`);
});
test('too large', async () => {
const $result = await waitError(loader.load(13).promise);
expect($result).toMatchInlineSnapshot(
`[Error: Input is too big for a single dispatch]`,
);
});
});
|
5,203 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/errors.test.ts | /* eslint-disable @typescript-eslint/no-empty-function */
import { waitError } from '../___testHelpers';
import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import { TRPCClientError } from '@trpc/client/src';
import * as trpc from '@trpc/server/src';
import { CreateHTTPContextOptions } from '@trpc/server/src/adapters/standalone';
import { TRPCError } from '@trpc/server/src/error/TRPCError';
import { getMessageFromUnknownError } from '@trpc/server/src/error/utils';
import { OnErrorFunction } from '@trpc/server/src/internals/types';
import fetch from 'node-fetch';
import { z, ZodError } from 'zod';
test('basic', async () => {
class MyError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, MyError.prototype);
}
}
const onError = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('err', {
resolve() {
throw new MyError('woop');
},
}),
{
server: {
onError,
},
},
);
const clientError = await waitError(client.query('err'), TRPCClientError);
expect(clientError.shape.message).toMatchInlineSnapshot(`"woop"`);
expect(clientError.shape.code).toMatchInlineSnapshot(`-32603`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError).toBeInstanceOf(TRPCError);
if (!(serverError instanceof TRPCError)) {
throw new Error('Wrong error');
}
expect(serverError.cause).toBeInstanceOf(MyError);
await close();
});
test('input error', async () => {
const onError = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc.router().mutation('err', {
input: z.string(),
resolve() {
return null;
},
}),
{
server: {
onError,
},
},
);
const clientError = await waitError(
client.mutation('err', 1 as any),
TRPCClientError,
);
expect(clientError.shape.message).toMatchInlineSnapshot(`
"[
{
\\"code\\": \\"invalid_type\\",
\\"expected\\": \\"string\\",
\\"received\\": \\"number\\",
\\"path\\": [],
\\"message\\": \\"Expected string, received number\\"
}
]"
`);
expect(clientError.shape.code).toMatchInlineSnapshot(`-32600`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
// if (!(serverError instanceof TRPCError)) {
// console.log('err', serverError);
// throw new Error('Wrong error');
// }
expect(serverError.cause).toBeInstanceOf(ZodError);
await close();
});
test('unauthorized()', async () => {
const onError = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('err', {
resolve() {
throw new TRPCError({ code: 'UNAUTHORIZED' });
},
}),
{
server: {
onError,
},
},
);
const clientError = await waitError(client.query('err'), TRPCClientError);
expect(clientError).toMatchInlineSnapshot(`[TRPCClientError: UNAUTHORIZED]`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError).toBeInstanceOf(TRPCError);
await close();
});
test('getMessageFromUnknownError()', () => {
expect(getMessageFromUnknownError('test', 'nope')).toBe('test');
expect(getMessageFromUnknownError(1, 'test')).toBe('test');
expect(getMessageFromUnknownError({}, 'test')).toBe('test');
});
describe('formatError()', () => {
test('simple', async () => {
const onError = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.formatError(({ error, shape }) => {
if (error.cause instanceof ZodError) {
return {
...shape,
data: {
...shape.data,
type: 'zod' as const,
errors: error.cause.errors,
},
};
}
return shape;
})
.mutation('err', {
input: z.string(),
resolve() {
return null;
},
}),
{
server: {
onError,
},
},
);
const clientError = await waitError(
client.mutation('err', 1 as any),
TRPCClientError,
);
delete clientError.data.stack;
expect(clientError.data).toMatchInlineSnapshot(`
Object {
"code": "BAD_REQUEST",
"errors": Array [
Object {
"code": "invalid_type",
"expected": "string",
"message": "Expected string, received number",
"path": Array [],
"received": "number",
},
],
"httpStatus": 400,
"path": "err",
"type": "zod",
}
`);
expect(clientError.shape).toMatchInlineSnapshot(`
Object {
"code": -32600,
"data": Object {
"code": "BAD_REQUEST",
"errors": Array [
Object {
"code": "invalid_type",
"expected": "string",
"message": "Expected string, received number",
"path": Array [],
"received": "number",
},
],
"httpStatus": 400,
"path": "err",
"type": "zod",
},
"message": "[
{
\\"code\\": \\"invalid_type\\",
\\"expected\\": \\"string\\",
\\"received\\": \\"number\\",
\\"path\\": [],
\\"message\\": \\"Expected string, received number\\"
}
]",
}
`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError.cause).toBeInstanceOf(ZodError);
await close();
});
test('double errors', async () => {
expect(() => {
trpc
.router()
.formatError(({ shape }) => {
return shape;
})
.formatError(({ shape }) => {
return shape;
});
}).toThrowErrorMatchingInlineSnapshot(
`"You seem to have double \`formatError()\`-calls in your router tree"`,
);
});
test('setting custom http response code', async () => {
const TEAPOT_ERROR_CODE = 418;
const onError = vi.fn();
const { close, httpUrl } = legacyRouterToServerAndClient(
trpc
.router()
.formatError(({ error, shape }) => {
if (!(error.cause instanceof ZodError)) {
return shape;
}
return {
...shape,
data: {
...shape.data,
httpStatus: TEAPOT_ERROR_CODE,
},
};
})
.query('q', {
input: z.string(),
resolve() {
return null;
},
}),
{
server: {
onError,
},
},
);
const res = await fetch(`${httpUrl}/q`);
expect(res.ok).toBeFalsy();
expect(res.status).toBe(TEAPOT_ERROR_CODE);
await close();
});
test('do not override response status set by middleware or resolver', async () => {
const TEAPOT_ERROR_CODE = 418;
const onError = vi.fn();
const { close, httpUrl } = legacyRouterToServerAndClient(
trpc
.router<CreateHTTPContextOptions>()
.middleware(({ ctx }) => {
ctx.res.statusCode = TEAPOT_ERROR_CODE;
throw new Error('Some error');
})
.query('q', {
resolve() {
return null;
},
}),
{
server: {
onError,
},
},
);
const res = await fetch(`${httpUrl}/q`);
expect(res.ok).toBeFalsy();
expect(res.status).toBe(TEAPOT_ERROR_CODE);
await close();
});
});
test('make sure object is ignoring prototype', async () => {
const onError = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('hello', {
resolve() {
return 'there';
},
}),
{
server: {
onError,
},
},
);
const clientError = await waitError(
client.query('toString' as any),
TRPCClientError,
);
expect(clientError.shape.message).toMatchInlineSnapshot(
`"No \\"query\\"-procedure on path \\"toString\\""`,
);
expect(clientError.shape.code).toMatchInlineSnapshot(`-32004`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError.code).toMatchInlineSnapshot(`"NOT_FOUND"`);
await close();
});
test('allow using built-in Object-properties', async () => {
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.query('toString', {
resolve() {
return 'toStringValue';
},
})
.query('hasOwnProperty', {
resolve() {
return 'hasOwnPropertyValue';
},
}),
);
expect(await client.query('toString')).toBe('toStringValue');
expect(await client.query('hasOwnProperty')).toBe('hasOwnPropertyValue');
await close();
});
test('retain stack trace', async () => {
class CustomError extends Error {
constructor() {
super('CustomError.msg');
this.name = 'CustomError';
Object.setPrototypeOf(this, new.target.prototype);
}
}
const onErrorFn: OnErrorFunction<any, any> = () => {};
const onError = vi.fn(onErrorFn);
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('hello', {
resolve() {
if (true) {
throw new CustomError();
}
return 'toStringValue';
},
}),
{
server: {
onError,
},
},
);
const clientError = await waitError(() => client.query('hello'));
expect(clientError.name).toBe('TRPCClientError');
expect(onError).toHaveBeenCalledTimes(1);
const serverOnErrorOpts = onError.mock.calls[0]![0]!;
const serverError = serverOnErrorOpts.error;
expect(serverError).toBeInstanceOf(TRPCError);
expect(serverError.cause).toBeInstanceOf(CustomError);
expect(serverError.stack).not.toContain('getErrorFromUnknown');
const stackParts = serverError.stack!.split('\n');
// first line of stack trace
expect(stackParts[1]).toContain(__filename);
await close();
});
|
5,204 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/headers.test.tsx | import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import { createTRPCClient, httpBatchLink } from '@trpc/client/src';
import * as trpc from '@trpc/server/src';
import { Dict } from '@trpc/server/src';
describe('pass headers', () => {
type Context = {
headers: Dict<string[] | string>;
};
const { close, httpUrl } = legacyRouterToServerAndClient(
trpc.router<Context>().query('hello', {
resolve({ ctx }) {
return {
'x-special': ctx.headers['x-special'],
};
},
}),
{
server: {
createContext({ req }) {
return { headers: req.headers };
},
},
},
);
afterAll(async () => {
await close();
});
test('no headers', async () => {
const client = createTRPCClient({
links: [httpBatchLink({ url: httpUrl })],
});
expect(await client.query('hello')).toMatchInlineSnapshot(`Object {}`);
});
test('custom headers', async () => {
const client = createTRPCClient({
links: [
httpBatchLink({
url: httpUrl,
headers() {
return {
'X-Special': 'special header',
};
},
}),
],
});
expect(await client.query('hello')).toMatchInlineSnapshot(`
Object {
"x-special": "special header",
}
`);
});
test('async headers', async () => {
const client = createTRPCClient({
links: [
httpBatchLink({
url: httpUrl,
async headers() {
return {
'X-Special': 'async special header',
};
},
}),
],
});
expect(await client.query('hello')).toMatchInlineSnapshot(`
Object {
"x-special": "async special header",
}
`);
});
});
|
5,205 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/index.test.tsx | /* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-empty-function */
import { waitError } from '../___testHelpers';
import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import { waitFor } from '@testing-library/react';
import { httpBatchLink, HTTPHeaders, TRPCClientError } from '@trpc/client/src';
import * as trpc from '@trpc/server/src';
import { Maybe, TRPCError } from '@trpc/server/src';
import { CreateHTTPContextOptions } from '@trpc/server/src/adapters/standalone';
import { observable } from '@trpc/server/src/observable';
import { z } from 'zod';
test('smoke test', async () => {
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('hello', {
resolve() {
return 'world';
},
}),
);
expect(await client.query('hello')).toBe('world');
await close();
});
test('mix query and mutation', async () => {
type Context = {};
const r = trpc
.router<Context>()
.query('q1', {
// input: null,
resolve() {
return 'q1res';
},
})
.query('q2', {
input: z.object({ q2: z.string() }),
resolve() {
return 'q2res';
},
})
.mutation('m1', {
resolve() {
return 'm1res';
},
});
const caller = r.createCaller({});
expect(await caller.query('q1')).toMatchInlineSnapshot(`"q1res"`);
expect(await caller.query('q2', { q2: 'hey' })).toMatchInlineSnapshot(
`"q2res"`,
);
expect(await caller.mutation('m1')).toMatchInlineSnapshot(`"m1res"`);
});
test('merge', async () => {
type Context = {};
const root = trpc.router<Context>().query('helloo', {
// input: null,
resolve() {
return 'world';
},
});
const posts = trpc
.router<Context>()
.query('list', {
resolve: () => [{ text: 'initial' }],
})
.mutation('create', {
input: z.string(),
resolve({ input }) {
return { text: input };
},
});
const r = root.merge('post.', posts);
const caller = r.createCaller({});
expect(await caller.query('post.list')).toMatchInlineSnapshot(`
Array [
Object {
"text": "initial",
},
]
`);
});
describe('integration tests', () => {
test('not found procedure', async () => {
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('hello', {
input: z
.object({
who: z.string(),
})
.nullish(),
resolve({ input }) {
return {
text: `hello ${input?.who ?? 'world'}`,
};
},
}),
);
const err = await waitError(
client.query('notFound' as any),
TRPCClientError,
);
expect(err.message).toMatchInlineSnapshot(
`"No \\"query\\"-procedure on path \\"notFound\\""`,
);
expect(err.shape?.message).toMatchInlineSnapshot(
`"No \\"query\\"-procedure on path \\"notFound\\""`,
);
await close();
});
test('invalid input', async () => {
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('hello', {
input: z
.object({
who: z.string(),
})
.nullish(),
resolve({ input }) {
expectTypeOf(input).toMatchTypeOf<Maybe<{ who: string }>>();
return {
text: `hello ${input?.who ?? 'world'}`,
};
},
}),
);
const err = await waitError(
client.query('hello', { who: 123 as any }),
TRPCClientError,
);
expect(err.shape?.code).toMatchInlineSnapshot(`-32600`);
expect(err.shape?.message).toMatchInlineSnapshot(`
"[
{
\\"code\\": \\"invalid_type\\",
\\"expected\\": \\"string\\",
\\"received\\": \\"number\\",
\\"path\\": [
\\"who\\"
],
\\"message\\": \\"Expected string, received number\\"
}
]"
`);
await close();
});
test('passing input to input w/o input', async () => {
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.query('q', {
resolve() {
return {
text: `hello `,
};
},
})
.mutation('m', {
resolve() {
return {
text: `hello `,
};
},
}),
);
await client.query('q');
await client.query('q', undefined);
await client.query('q', null as any); // treat null as undefined
await expect(
client.query('q', 'not-nullish' as any),
).rejects.toMatchInlineSnapshot(`[TRPCClientError: No input expected]`);
await client.mutation('m');
await client.mutation('m', undefined);
await client.mutation('m', null as any); // treat null as undefined
await expect(
client.mutation('m', 'not-nullish' as any),
).rejects.toMatchInlineSnapshot(`[TRPCClientError: No input expected]`);
await close();
});
describe('type testing', () => {
test('basic', async () => {
type Input = { who: string };
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('hello', {
input: z.object({
who: z.string(),
}),
resolve({ input }) {
expectTypeOf(input).not.toBeAny();
expectTypeOf(input).toMatchTypeOf<{ who: string }>();
return {
text: `hello ${input?.who ?? 'world'}`,
input,
};
},
}),
);
const res = await client.query('hello', { who: 'katt' });
expectTypeOf(res.input).toMatchTypeOf<Input>();
expectTypeOf(res.input).not.toBeAny();
expectTypeOf(res).toMatchTypeOf<{ input: Input; text: string }>();
expect(res.text).toEqual('hello katt');
await close();
});
test('mixed response', async () => {
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('postById', {
input: z.number(),
async resolve({ input }) {
if (input === 1) {
return {
id: 1,
title: 'helloo',
};
}
if (input === 2) {
return {
id: 2,
title: 'test',
};
}
return null;
},
}),
);
const res = await client.query('postById', 1);
expectTypeOf(res).toMatchTypeOf<{ id: number; title: string } | null>();
expect(res).toEqual({
id: 1,
title: 'helloo',
});
await close();
});
test('propagate ctx', async () => {
type Context = {
user?: {
id: number;
name: string;
};
};
const headers: HTTPHeaders = {};
function createContext({ req }: CreateHTTPContextOptions): Context {
if (req.headers.authorization !== 'kattsecret') {
return {};
}
return {
user: {
id: 1,
name: 'KATT',
},
};
}
const { client, close } = legacyRouterToServerAndClient(
trpc.router<Context>().query('whoami', {
async resolve({ ctx }) {
if (!ctx.user) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return ctx.user;
},
}),
{
server: {
createContext,
},
client({ httpUrl }) {
return {
links: [
httpBatchLink({
headers,
url: httpUrl,
}),
],
};
},
},
);
// no auth, should fail
{
const err = await waitError(client.query('whoami'), TRPCClientError);
expect(err.shape.message).toMatchInlineSnapshot(`"UNAUTHORIZED"`);
}
// auth, should work
{
headers.authorization = 'kattsecret';
const res = await client.query('whoami');
expectTypeOf(res).toMatchTypeOf<{ id: number; name: string }>();
expect(res).toEqual({
id: 1,
name: 'KATT',
});
}
await close();
});
test('optional input', async () => {
type Input = Maybe<{ who: string }>;
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('hello', {
input: z
.object({
who: z.string(),
})
.nullish(),
resolve({ input }) {
expectTypeOf(input).not.toBeAny();
expectTypeOf(input).toMatchTypeOf<Input>();
return {
text: `hello ${input?.who ?? 'world'}`,
input,
};
},
}),
);
{
const res = await client.query('hello', { who: 'katt' });
expectTypeOf(res.input).toMatchTypeOf<Input>();
expectTypeOf(res.input).not.toBeAny();
}
{
const res = await client.query('hello');
expectTypeOf(res.input).toMatchTypeOf<Input>();
expectTypeOf(res.input).not.toBeAny();
}
await close();
});
test('mutation', async () => {
type Input = Maybe<{ who: string }>;
const { client, close } = legacyRouterToServerAndClient(
trpc.router().mutation('hello', {
input: z
.object({
who: z.string(),
})
.nullish(),
resolve({ input }) {
expectTypeOf(input).not.toBeAny();
expectTypeOf(input).toMatchTypeOf<Input>();
return {
text: `hello ${input?.who ?? 'world'}`,
input,
};
},
}),
);
const res = await client.mutation('hello', { who: 'katt' });
expectTypeOf(res.input).toMatchTypeOf<Input>();
expectTypeOf(res.input).not.toBeAny();
expect(res.text).toBe('hello katt');
await close();
});
});
});
describe('createCaller()', () => {
type Context = {};
const router = trpc
.router<Context>()
.query('q', {
input: z.number(),
async resolve({ input }) {
return { input };
},
})
.mutation('m', {
input: z.number(),
async resolve({ input }) {
return { input };
},
})
.subscription('sub', {
input: z.number(),
async resolve({ input }) {
return observable<{ input: typeof input }>((emit) => {
emit.next({ input });
return () => {
// noop
};
});
},
});
test('query()', async () => {
const data = await router.createCaller({}).query('q', 1);
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
expect(data).toEqual({ input: 1 });
});
test('mutation()', async () => {
const data = await router.createCaller({}).mutation('m', 2);
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
expect(data).toEqual({ input: 2 });
});
test('subscription()', async () => {
const subObservable = await router.createCaller({}).subscription('sub', 3);
await new Promise<void>((resolve) => {
subObservable.subscribe({
next(data: { input: number }) {
expect(data).toEqual({ input: 3 });
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
resolve();
},
});
});
});
});
describe('createCaller()', () => {
type Context = {};
const router = trpc
.router<Context>()
.query('q', {
input: z.number(),
async resolve({ input }) {
return { input };
},
})
.mutation('m', {
input: z.number(),
async resolve({ input }) {
return { input };
},
})
.subscription('sub', {
input: z.number(),
async resolve({ input }) {
return observable<{ input: typeof input }>((emit) => {
emit.next({ input });
return () => {
// noop
};
});
},
});
test('query()', async () => {
const data = await router.createCaller({}).query('q', 1);
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
expect(data).toEqual({ input: 1 });
});
test('mutation()', async () => {
const data = await router.createCaller({}).mutation('m', 2);
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
expect(data).toEqual({ input: 2 });
});
test('subscription()', async () => {
const subObservable = await router.createCaller({}).subscription('sub', 3);
await new Promise<void>((resolve) => {
subObservable.subscribe({
next(data: { input: number }) {
expect(data).toEqual({ input: 3 });
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
resolve();
},
});
});
});
});
// regression https://github.com/trpc/trpc/issues/527
test('void mutation response', async () => {
const {
client,
close,
// wssPort,
// router
} = legacyRouterToServerAndClient(
trpc
.router()
.mutation('undefined', {
async resolve() {},
})
.mutation('null', {
async resolve() {
return null;
},
}),
);
expect(await client.mutation('undefined')).toMatchInlineSnapshot(`undefined`);
expect(await client.mutation('null')).toMatchInlineSnapshot(`null`);
// const ws = createWSClient({
// url: `ws://localhost:${wssPort}`,
// WebSocket: WebSocket as any,
// });
// const wsClient = createTRPCClient<typeof router>({
// links: [wsLink({ client: ws })],
// });
// expect(await wsClient.mutation('undefined')).toMatchInlineSnapshot(
// `undefined`,
// );
// expect(await wsClient.mutation('null')).toMatchInlineSnapshot(`null`);
// ws.await close();
await close();
});
// https://github.com/trpc/trpc/issues/559
describe('ObservableAbortError', () => {
test('cancelling request should throw ObservableAbortError', async () => {
const { client, close } = legacyRouterToServerAndClient(
trpc.router().query('slow', {
async resolve() {
await new Promise((resolve) => setTimeout(resolve, 500));
return null;
},
}),
);
const onReject = vi.fn();
const ac = new AbortController();
const req = client.query('slow', undefined, {
signal: ac.signal,
});
req.catch(onReject);
// cancel after 10ms
await new Promise((resolve) => setTimeout(resolve, 5));
ac.abort();
await waitFor(() => {
expect(onReject).toHaveBeenCalledTimes(1);
});
const err = onReject.mock.calls[0]![0]! as TRPCClientError<any>;
expect(err.name).toBe('TRPCClientError');
expect(err.cause?.name).toBe('ObservableAbortError');
await close();
});
test('cancelling batch request should throw AbortError', async () => {
// aborting _one_ batch request doesn't necessarily mean we cancel the reqs part of that batch
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.query('slow1', {
async resolve() {
await new Promise((resolve) => setTimeout(resolve, 500));
return 'slow1';
},
})
.query('slow2', {
async resolve() {
await new Promise((resolve) => setTimeout(resolve, 500));
return 'slow2';
},
}),
{
server: {
batching: {
enabled: true,
},
},
client({ httpUrl }) {
return {
links: [httpBatchLink({ url: httpUrl })],
};
},
},
);
const ac = new AbortController();
const req1 = client.query('slow1', undefined, { signal: ac.signal });
const req2 = client.query('slow2');
const onReject1 = vi.fn();
req1.catch(onReject1);
await new Promise((resolve) => setTimeout(resolve, 5));
ac.abort();
await waitFor(() => {
expect(onReject1).toHaveBeenCalledTimes(1);
});
const err = onReject1.mock.calls[0]![0]! as TRPCClientError<any>;
expect(err).toBeInstanceOf(TRPCClientError);
expect(err.cause?.name).toBe('ObservableAbortError');
expect(await req2).toBe('slow2');
await close();
});
});
test('regression: JSON.stringify([undefined]) gives [null] causes wrong type to procedure input', async () => {
const { client, close } = legacyRouterToServerAndClient(
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 {}`);
await close();
});
|
5,206 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/inference.test.ts | import * as trpc from '@trpc/server/src';
import { inferProcedureInput, inferProcedureOutput } from '@trpc/server/src';
import { Observable, observable } from '@trpc/server/src/observable';
import { z } from 'zod';
describe('infer query input & output', () => {
const router = trpc
.router()
.query('noInput', {
async resolve({ input }) {
return { input };
},
})
.query('withInput', {
input: z.string(),
output: z.object({
input: z.string(),
}),
async resolve({ input }) {
return { input };
},
})
.query('withOutput', {
output: z.object({
input: z.string(),
}),
// @ts-expect-error - ensure type inferred from "output" is expected as "resolve" fn return type
async resolve({ input }) {
return { input };
},
})
.query('withOutputEmptyObject', {
output: z.object({
input: z.string(),
}),
// @ts-expect-error - ensure type inferred from "output" is higher priority than "resolve" fn return type
resolve() {
return {};
},
})
.query('withInputOutput', {
input: z.string(),
output: z.object({
input: z.string(),
}),
async resolve({ input }) {
return { input };
},
})
.interop();
type TQueries = (typeof router)['_def']['queries'];
test('no input', () => {
const input: inferProcedureInput<TQueries['noInput']> = null as any;
const output: inferProcedureOutput<TQueries['noInput']> = null as any;
expectTypeOf(input).toMatchTypeOf<null | undefined | void>();
expectTypeOf(output).toMatchTypeOf<{ input: undefined }>();
});
test('with input', () => {
const input: inferProcedureInput<TQueries['withInput']> = null as any;
const output: inferProcedureOutput<TQueries['withInput']> = null as any;
expectTypeOf(input).toMatchTypeOf<string>();
expectTypeOf(output).toMatchTypeOf<{ input: string }>();
});
test('with output', () => {
const input: inferProcedureInput<TQueries['withOutput']> = null as any;
const output: inferProcedureOutput<TQueries['withOutput']> = null as any;
expectTypeOf(input).toMatchTypeOf<null | undefined | void>();
expectTypeOf(output).toMatchTypeOf<{ input: string }>();
});
test('with output empty object', () => {
const input: inferProcedureInput<TQueries['withOutputEmptyObject']> =
null as any;
const output: inferProcedureOutput<TQueries['withOutputEmptyObject']> =
null as any;
expectTypeOf(input).toMatchTypeOf<null | undefined | void>();
expectTypeOf(output).toMatchTypeOf<{ input: string }>();
});
test('with input and output', () => {
const input: inferProcedureInput<TQueries['withInputOutput']> = null as any;
const output: inferProcedureOutput<TQueries['withInputOutput']> =
null as any;
expectTypeOf(input).toMatchTypeOf<string>();
expectTypeOf(output).toMatchTypeOf<{ input: string }>();
});
});
describe('infer mutation input & output', () => {
const router = trpc
.router()
.mutation('noInput', {
async resolve({ input }) {
return { input };
},
})
.mutation('withInput', {
input: z.string(),
output: z.object({
input: z.string(),
}),
async resolve({ input }) {
return { input };
},
})
.mutation('withOutput', {
output: z.object({
input: z.string(),
}),
// @ts-expect-error - ensure type inferred from "output" is expected as "resolve" fn return type
async resolve({ input }) {
return { input };
},
})
.mutation('withOutputEmptyObject', {
output: z.object({
input: z.string(),
}),
// @ts-expect-error - ensure type inferred from "output" is higher priority than "resolve" fn return type
resolve() {
return {};
},
})
.mutation('withInputOutput', {
input: z.string(),
output: z.object({
input: z.string(),
}),
async resolve({ input }) {
return { input };
},
})
.interop();
type TMutations = (typeof router)['_def']['mutations'];
test('no input', () => {
const input: inferProcedureInput<TMutations['noInput']> = null as any;
const output: inferProcedureOutput<TMutations['noInput']> = null as any;
expectTypeOf(input).toMatchTypeOf<null | undefined | void>();
expectTypeOf(output).toMatchTypeOf<{ input: undefined }>();
});
test('with input', () => {
const input: inferProcedureInput<TMutations['withInput']> = null as any;
const output: inferProcedureOutput<TMutations['withInput']> = null as any;
expectTypeOf(input).toMatchTypeOf<string>();
expectTypeOf(output).toMatchTypeOf<{ input: string }>();
});
test('with output', () => {
const input: inferProcedureInput<TMutations['withOutput']> = null as any;
const output: inferProcedureOutput<TMutations['withOutput']> = null as any;
expectTypeOf(input).toMatchTypeOf<null | undefined | void>();
expectTypeOf(output).toMatchTypeOf<{ input: string }>();
});
test('with output empty object', () => {
const input: inferProcedureInput<TMutations['withOutputEmptyObject']> =
null as any;
const output: inferProcedureOutput<TMutations['withOutputEmptyObject']> =
null as any;
expectTypeOf(input).toMatchTypeOf<null | undefined | void>();
expectTypeOf(output).toMatchTypeOf<{ input: string }>();
});
test('with input and output', () => {
const input: inferProcedureInput<TMutations['withInputOutput']> =
null as any;
const output: inferProcedureOutput<TMutations['withInputOutput']> =
null as any;
expectTypeOf(input).toMatchTypeOf<string>();
expectTypeOf(output).toMatchTypeOf<{ input: string }>();
});
});
describe('infer subscription input & output', () => {
// @ts-expect-error - ensure "output" is omitted in subscription procedure
const router = trpc
.router()
.subscription('noSubscription', {
// @ts-expect-error - ensure Observable is expected as "resolve" fn return type
async resolve({ input }) {
return { input };
},
})
.subscription('noInput', {
async resolve() {
return observable(() => () => null);
},
})
.subscription('withInput', {
input: z.string(),
async resolve({ input }) {
return observable<typeof input>((emit) => {
emit.next(input);
return () => null;
});
},
})
.subscription('withOutput', {
input: z.string(),
output: z.null(),
async resolve({ input }) {
return observable<typeof input>((emit) => {
emit.next(input);
return () => null;
});
},
})
.interop();
type TSubscriptions = (typeof router)['_def']['subscriptions'];
test('no input', () => {
const input: inferProcedureInput<TSubscriptions['noInput']> = null as any;
const output: inferProcedureOutput<TSubscriptions['noInput']> = null as any;
expectTypeOf(input).toMatchTypeOf<null | undefined | void>();
expectTypeOf(output).toMatchTypeOf<Observable<unknown, unknown>>();
});
test('with input', () => {
const input: inferProcedureInput<TSubscriptions['withInput']> = null as any;
const output: inferProcedureOutput<TSubscriptions['withInput']> =
null as any;
expectTypeOf(input).toMatchTypeOf<string>();
expectTypeOf(output).toMatchTypeOf<Observable<string, unknown>>();
});
});
|
5,207 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/links.test.ts | import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import {
createTRPCClient,
httpBatchLink,
httpLink,
loggerLink,
OperationLink,
TRPCClientError,
TRPCClientRuntime,
} from '@trpc/client/src';
import { createChain } from '@trpc/client/src/links/internals/createChain';
import { retryLink } from '@trpc/client/src/links/internals/retryLink';
import * as trpc from '@trpc/server/src';
import { AnyRouter } from '@trpc/server/src';
import { observable, observableToPromise } from '@trpc/server/src/observable';
import { z } from 'zod';
const mockRuntime: TRPCClientRuntime = {
transformer: {
serialize: (v) => v,
deserialize: (v) => v,
},
combinedTransformer: {
input: {
serialize: (v) => v,
deserialize: (v) => v,
},
output: {
serialize: (v) => v,
deserialize: (v) => v,
},
},
};
test('chainer', async () => {
let attempt = 0;
const serverCall = vi.fn();
const { httpPort, close } = legacyRouterToServerAndClient(
trpc.router().query('hello', {
resolve() {
attempt++;
serverCall();
if (attempt < 3) {
throw new Error('Err ' + attempt);
}
return 'world';
},
}),
);
const chain = createChain({
links: [
retryLink({ attempts: 3 })(mockRuntime),
httpLink({
url: `http://localhost:${httpPort}`,
})(mockRuntime),
],
op: {
id: 1,
type: 'query',
path: 'hello',
input: null,
context: {},
},
});
const result = await observableToPromise(chain).promise;
expect(result?.context?.response).toBeTruthy();
result.context!.response = '[redacted]' as any;
expect(result).toMatchInlineSnapshot(`
Object {
"context": Object {
"response": "[redacted]",
"responseJSON": Object {
"result": Object {
"data": "world",
},
},
},
"result": Object {
"data": "world",
"type": "data",
},
}
`);
expect(serverCall).toHaveBeenCalledTimes(3);
await close();
});
test('cancel request', async () => {
const onDestroyCall = vi.fn();
const chain = createChain({
links: [
() =>
observable(() => {
return () => {
onDestroyCall();
};
}),
],
op: {
id: 1,
type: 'query',
path: 'hello',
input: null,
context: {},
},
});
chain.subscribe({}).unsubscribe();
expect(onDestroyCall).toHaveBeenCalled();
});
describe('batching', () => {
test('query batching', async () => {
const metaCall = vi.fn();
const { httpPort, close } = legacyRouterToServerAndClient(
trpc.router().query('hello', {
input: z.string().nullish(),
resolve({ input }) {
return `hello ${input ?? 'world'}`;
},
}),
{
server: {
createContext() {
metaCall();
return {};
},
batching: {
enabled: true,
},
},
},
);
const links = [
httpBatchLink({
url: `http://localhost:${httpPort}`,
})(mockRuntime),
];
const chain1 = createChain({
links,
op: {
id: 1,
type: 'query',
path: 'hello',
input: null,
context: {},
},
});
const chain2 = createChain({
links,
op: {
id: 2,
type: 'query',
path: 'hello',
input: 'alexdotjs',
context: {},
},
});
const results = await Promise.all([
observableToPromise(chain1).promise,
observableToPromise(chain2).promise,
]);
for (const res of results) {
expect(res?.context?.response).toBeTruthy();
res.context!.response = '[redacted]';
}
expect(results).toMatchInlineSnapshot(`
Array [
Object {
"context": Object {
"response": "[redacted]",
"responseJSON": Array [
Object {
"result": Object {
"data": "hello world",
},
},
Object {
"result": Object {
"data": "hello alexdotjs",
},
},
],
},
"result": Object {
"data": "hello world",
"type": "data",
},
},
Object {
"context": Object {
"response": "[redacted]",
"responseJSON": Array [
Object {
"result": Object {
"data": "hello world",
},
},
Object {
"result": Object {
"data": "hello alexdotjs",
},
},
],
},
"result": Object {
"data": "hello alexdotjs",
"type": "data",
},
},
]
`);
expect(metaCall).toHaveBeenCalledTimes(1);
await close();
});
test('batching on maxURLLength', async () => {
const createContextFn = vi.fn();
const { client, httpUrl, close, router } = legacyRouterToServerAndClient(
trpc.router().query('big-input', {
input: z.string(),
resolve({ input }) {
return input.length;
},
}),
{
server: {
createContext() {
createContextFn();
return {};
},
batching: {
enabled: true,
},
},
client: (opts) => ({
links: [
httpBatchLink({
url: opts.httpUrl,
maxURLLength: 2083,
}),
],
}),
},
);
{
// queries should be batched into a single request
// url length: 118 < 2083
const res = await Promise.all([
client.query('big-input', '*'.repeat(10)),
client.query('big-input', '*'.repeat(10)),
]);
expect(res).toEqual([10, 10]);
expect(createContextFn).toBeCalledTimes(1);
createContextFn.mockClear();
}
{
// queries should be sent and individual requests
// url length: 2146 > 2083
const res = await Promise.all([
client.query('big-input', '*'.repeat(1024)),
client.query('big-input', '*'.repeat(1024)),
]);
expect(res).toEqual([1024, 1024]);
expect(createContextFn).toBeCalledTimes(2);
createContextFn.mockClear();
}
{
// queries should be batched into a single request
// url length: 2146 < 9999
const clientWithBigMaxURLLength = createTRPCClient<typeof router>({
links: [httpBatchLink({ url: httpUrl, maxURLLength: 9999 })],
});
const res = await Promise.all([
clientWithBigMaxURLLength.query('big-input', '*'.repeat(1024)),
clientWithBigMaxURLLength.query('big-input', '*'.repeat(1024)),
]);
expect(res).toEqual([1024, 1024]);
expect(createContextFn).toBeCalledTimes(1);
}
await close();
});
test('server not configured for batching', async () => {
const serverCall = vi.fn();
const { close, router, httpPort, trpcClientOptions } =
legacyRouterToServerAndClient(
trpc.router().query('hello', {
resolve() {
serverCall();
return 'world';
},
}),
{
server: {
batching: {
enabled: false,
},
},
},
);
const client = createTRPCClient<typeof router>({
...trpcClientOptions,
links: [
httpBatchLink({
url: `http://localhost:${httpPort}`,
headers: {},
}),
],
});
await expect(client.query('hello')).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Batching is not enabled on the server]`,
);
await close();
});
});
test('create client with links', async () => {
let attempt = 0;
const serverCall = vi.fn();
const { close, router, httpPort, trpcClientOptions } =
legacyRouterToServerAndClient(
trpc.router().query('hello', {
resolve() {
attempt++;
serverCall();
if (attempt < 3) {
throw new Error('Err ' + attempt);
}
return 'world';
},
}),
);
const client = createTRPCClient<typeof router>({
...trpcClientOptions,
links: [
retryLink({ attempts: 3 }),
httpLink({
url: `http://localhost:${httpPort}`,
headers: {},
}),
],
});
const result = await client.query('hello');
expect(result).toBe('world');
await close();
});
describe('loggerLink', () => {
const logger = {
error: vi.fn(),
log: vi.fn(),
};
const logLink = loggerLink({
console: logger,
})(mockRuntime);
const okLink: OperationLink<AnyRouter> = () =>
observable((o) => {
o.next({
result: {
type: 'data',
data: undefined,
},
});
});
const errorLink: OperationLink<AnyRouter> = () =>
observable((o) => {
o.error(new TRPCClientError('..'));
});
beforeEach(() => {
logger.error.mockReset();
logger.log.mockReset();
});
test('query', () => {
createChain({
links: [logLink, okLink],
op: {
id: 1,
type: 'query',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
expect(logger.log.mock.calls).toHaveLength(2);
expect(logger.log.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c >> query #1 %cn/a%c %O"`,
);
expect(logger.log.mock.calls[0]![1]!).toMatchInlineSnapshot(`
"
background-color: #72e3ff;
color: black;
padding: 2px;
"
`);
});
test('subscription', () => {
createChain({
links: [logLink, okLink],
op: {
id: 1,
type: 'subscription',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
expect(logger.log.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c >> subscription #1 %cn/a%c %O"`,
);
expect(logger.log.mock.calls[1]![0]!).toMatchInlineSnapshot(
`"%c << subscription #1 %cn/a%c %O"`,
);
});
test('mutation', () => {
createChain({
links: [logLink, okLink],
op: {
id: 1,
type: 'mutation',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
expect(logger.log.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c >> mutation #1 %cn/a%c %O"`,
);
expect(logger.log.mock.calls[1]![0]!).toMatchInlineSnapshot(
`"%c << mutation #1 %cn/a%c %O"`,
);
});
test('query 2', () => {
createChain({
links: [logLink, errorLink],
op: {
id: 1,
type: 'query',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
expect(logger.log.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c >> query #1 %cn/a%c %O"`,
);
expect(logger.error.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c << query #1 %cn/a%c %O"`,
);
});
test('custom logger', () => {
const logFn = vi.fn();
createChain({
links: [loggerLink({ logger: logFn })(mockRuntime), errorLink],
op: {
id: 1,
type: 'query',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
const [firstCall, secondCall] = logFn.mock.calls.map((args) => args[0]);
expect(firstCall).toMatchInlineSnapshot(`
Object {
"context": Object {},
"direction": "up",
"id": 1,
"input": null,
"path": "n/a",
"type": "query",
}
`);
// omit elapsedMs
const { elapsedMs, ...other } = secondCall;
expect(typeof elapsedMs).toBe('number');
expect(other).toMatchInlineSnapshot(`
Object {
"context": Object {},
"direction": "down",
"id": 1,
"input": null,
"path": "n/a",
"result": [TRPCClientError: ..],
"type": "query",
}
`);
});
});
test('chain makes unsub', async () => {
const firstLinkUnsubscribeSpy = vi.fn();
const firstLinkCompleteSpy = vi.fn();
const secondLinkUnsubscribeSpy = vi.fn();
const router = trpc.router().query('hello', {
resolve() {
return 'world';
},
});
const { client, close } = legacyRouterToServerAndClient(router, {
client() {
return {
links: [
() =>
({ next, op }) =>
observable((observer) => {
next(op).subscribe({
error(err) {
observer.error(err);
},
next(v) {
observer.next(v);
},
complete() {
firstLinkCompleteSpy();
observer.complete();
},
});
return () => {
firstLinkUnsubscribeSpy();
observer.complete();
};
}),
() => () =>
observable((observer) => {
observer.next({
result: {
type: 'data',
data: 'world',
},
});
observer.complete();
return () => {
secondLinkUnsubscribeSpy();
};
}),
],
};
},
});
expect(await client.query('hello')).toBe('world');
expect(firstLinkCompleteSpy).toHaveBeenCalledTimes(1);
expect(firstLinkUnsubscribeSpy).toHaveBeenCalledTimes(1);
expect(secondLinkUnsubscribeSpy).toHaveBeenCalledTimes(1);
await close();
});
|
5,208 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/middleware.test.ts | import { AsyncLocalStorage } from 'async_hooks';
import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import { httpBatchLink, HTTPHeaders } from '@trpc/client/src';
import { inferProcedureOutput, TRPCError } from '@trpc/server/src';
import * as trpc from '@trpc/server/src';
import { MiddlewareResult } from '@trpc/server/src/deprecated/internals/middlewares';
import { z } from 'zod';
test('is called if def first', async () => {
const middleware = vi.fn((opts) => {
return opts.next();
});
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.middleware(middleware)
.query('foo1', {
resolve() {
return 'bar1';
},
})
.mutation('foo2', {
resolve() {
return 'bar2';
},
}),
);
const calls = middleware.mock.calls;
expect(await client.query('foo1')).toBe('bar1');
expect(calls[0]![0]!).toHaveProperty('type');
expect(calls[0]![0]!).toHaveProperty('ctx');
expect(calls[0]![0]!.type).toBe('query');
expect(middleware).toHaveBeenCalledTimes(1);
expect(await client.mutation('foo2')).toBe('bar2');
expect(calls[1]![0]!.type).toBe('mutation');
expect(middleware).toHaveBeenCalledTimes(2);
await close();
});
test('is not called if def last', async () => {
const middleware = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.query('foo', {
resolve() {
return 'bar';
},
})
.middleware(middleware),
);
expect(await client.query('foo')).toBe('bar');
expect(middleware).toHaveBeenCalledTimes(0);
await close();
});
test('receives rawInput as param', async () => {
const inputSchema = z.object({ userId: z.string() });
const middleware = vi.fn((opts) => {
const result = inputSchema.safeParse(opts.rawInput);
if (!result.success) throw new TRPCError({ code: 'BAD_REQUEST' });
const { userId } = result.data;
// Check user id auth
return opts.next({ ctx: { userId } });
});
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.middleware(middleware)
.query('userId', {
input: inputSchema,
resolve({ ctx }) {
return (ctx as any).userId;
},
}),
);
const calls = middleware.mock.calls;
expect(await client.query('userId', { userId: 'ABCD' })).toBe('ABCD');
expect(calls[0]![0]!).toHaveProperty('type');
expect(calls[0]![0]!).toHaveProperty('ctx');
expect(calls[0]![0]!.type).toBe('query');
expect(calls[0]![0]!.rawInput).toStrictEqual({ userId: 'ABCD' });
await expect(client.query('userId', { userId: 123 as any })).rejects.toThrow(
'BAD_REQUEST',
);
expect(middleware).toHaveBeenCalledTimes(2);
await close();
});
test('allows you to throw an error (e.g. auth)', async () => {
type Context = {
user?: {
id: number;
name: string;
isAdmin: boolean;
};
};
const resolverMock = vi.fn();
const headers: HTTPHeaders = {};
const { client, close } = legacyRouterToServerAndClient(
trpc
.router<Context>()
.query('foo', {
resolve() {
return 'bar';
},
})
.merge(
'admin.',
trpc
.router<Context>()
.middleware(({ ctx, next }) => {
if (!ctx.user?.isAdmin) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next();
})
.query('secretPlace', {
resolve() {
resolverMock();
return 'a key';
},
}),
),
{
server: {
createContext({ req }) {
if (req.headers.authorization === 'meow') {
return {
user: {
id: 1,
name: 'KATT',
isAdmin: true,
},
};
}
return {};
},
},
client({ httpUrl }) {
return {
links: [httpBatchLink({ url: httpUrl, headers })],
};
},
},
);
expect(await client.query('foo')).toBe('bar');
await expect(client.query('admin.secretPlace')).rejects.toMatchInlineSnapshot(
`[TRPCClientError: UNAUTHORIZED]`,
);
expect(resolverMock).toHaveBeenCalledTimes(0);
headers.authorization = 'meow';
expect(await client.query('admin.secretPlace')).toBe('a key');
expect(resolverMock).toHaveBeenCalledTimes(1);
await close();
});
test('child routers + hook call order', async () => {
const middlewareInParent = vi.fn((opts) => {
return opts.next();
});
const middlewareInChild = vi.fn((opts) => {
return opts.next();
});
const middlewareInGrandChild = vi.fn((opts) => {
return opts.next();
});
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.middleware(middlewareInParent)
.query('name', {
resolve() {
return 'Child';
},
})
.merge(
'child.',
trpc
.router()
.middleware(middlewareInChild)
.query('name', {
resolve() {
return 'Child';
},
})
.merge(
'child.',
trpc
.router()
.middleware(middlewareInGrandChild)
.query('name', {
resolve() {
return 'GrandChild';
},
}),
),
),
);
expect(await client.query('child.child.name')).toBe('GrandChild');
expect(middlewareInParent).toHaveBeenCalledTimes(1);
expect(middlewareInChild).toHaveBeenCalledTimes(1);
expect(middlewareInGrandChild).toHaveBeenCalledTimes(1);
// check call order
expect(middlewareInParent.mock.invocationCallOrder[0]).toBeLessThan(
middlewareInChild.mock.invocationCallOrder[0]!,
);
expect(middlewareInChild.mock.invocationCallOrder[0]!).toBeLessThan(
middlewareInGrandChild.mock.invocationCallOrder[0]!,
);
expect(await client.query('name')).toBe('Child');
expect(await client.query('child.name')).toBe('Child');
expect(await client.query('child.child.name')).toBe('GrandChild');
await close();
});
test('not returning next result is an error at compile-time', async () => {
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
// @ts-expect-error Compiler makes sure we actually return the `next()` result.
.middleware(async ({ next }) => {
await next();
})
.query('helloQuery', {
async resolve() {
return 'hello';
},
}),
);
await expect(client.query('helloQuery')).rejects.toMatchInlineSnapshot(
`[TRPCClientError: No result from middlewares - did you forget to \`return next()\`?]`,
);
await close();
});
test('async hooks', async () => {
const storage = new AsyncLocalStorage<{ requestId: number }>();
let requestCount = 0;
const log = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.middleware((opts) => {
return new Promise<MiddlewareResult<any>>((resolve, reject) => {
storage.run({ requestId: ++requestCount }, async () => {
opts.next().then(resolve, reject);
});
});
})
.query('foo', {
input: String,
resolve({ input }) {
// We can now call `.getStore()` arbitrarily deep in the call stack, without having to explicitly pass context
const ambientRequestInfo = storage.getStore();
log({ input, requestId: ambientRequestInfo?.requestId });
return 'bar ' + input;
},
}),
);
expect(await client.query('foo', 'one')).toBe('bar one');
expect(await client.query('foo', 'two')).toBe('bar two');
expect(log).toHaveBeenCalledTimes(2);
expect(log).toHaveBeenCalledWith({ input: 'one', requestId: 1 });
expect(log).toHaveBeenCalledWith({ input: 'two', requestId: 2 });
await close();
});
test('equiv', () => {
type Context = {
user?: {
id: number;
name: string;
isAdmin: boolean;
};
};
trpc
.router<Context>()
.query('foo', {
resolve() {
return 'bar';
},
})
.merge(
'admin.',
trpc
.router<Context>()
.middleware(({ ctx, next }) => {
if (!ctx.user?.isAdmin) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next();
})
.query('secretPlace', {
resolve() {
return 'a key';
},
}),
);
trpc
.router<Context>()
.query('foo', {
resolve() {
return 'bar';
},
})
.merge(
trpc
.router<Context>()
.middleware(({ ctx, next }) => {
if (!ctx.user?.isAdmin) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next();
})
.query('admin.secretPlace', {
resolve() {
return 'a key';
},
}),
);
});
test('measure time middleware', async () => {
let durationMs = -1;
const logMock = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.middleware(async ({ next, path, type }) => {
const start = Date.now();
const result = await next();
durationMs = Date.now() - start;
result.ok
? logMock('OK request timing:', { path, type, durationMs })
: logMock('Non-OK request timing', { path, type, durationMs });
return result;
})
.query('greeting', {
async resolve() {
return 'hello';
},
}),
);
expect(await client.query('greeting')).toBe('hello');
expect(durationMs > -1).toBeTruthy();
const calls = logMock.mock.calls.map((args) => {
// omit durationMs as it's variable
const [str, { durationMs, ...opts }] = args;
return [str, opts];
});
expect(calls).toMatchInlineSnapshot(`
Array [
Array [
"OK request timing:",
Object {
"path": "greeting",
"type": "query",
},
],
]
`);
await close();
});
test('middleware throwing should return a union', async () => {
class CustomError extends Error {
constructor(msg: string) {
super(msg);
Object.setPrototypeOf(this, CustomError.prototype);
}
}
const fn = vi.fn((res: MiddlewareResult<unknown>) => {
return res;
});
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.middleware(async function firstMiddleware({ next }) {
const result = await next();
fn(result);
return result;
})
.middleware(async function middlewareThatThrows() {
throw new CustomError('error');
})
.query('test', {
resolve() {
return 'test';
},
}),
);
try {
await client.query('test');
} catch {}
expect(fn).toHaveBeenCalledTimes(1);
const res = fn.mock.calls[0]![0]!;
if (res.ok) {
throw new Error('wrong state');
}
delete res.error.stack;
expect(res.error).toMatchInlineSnapshot(`[TRPCError: error]`);
const cause = res.error.cause as CustomError;
expect(cause).toBeInstanceOf(CustomError);
await close();
});
test('omitting ctx in next() does not affect the actual ctx', async () => {
type User = {
id: string;
};
type OriginalContext = {
maybeUser?: User;
};
const { client, close } = legacyRouterToServerAndClient(
trpc
.router<OriginalContext>()
.middleware(async function firstMiddleware({ next }) {
return next();
})
.query('test', {
resolve({ ctx }) {
expectTypeOf(ctx).toEqualTypeOf<OriginalContext>();
return ctx.maybeUser?.id;
},
}),
{
server: {
createContext() {
return {
maybeUser: {
id: 'alexdotjs',
},
};
},
},
},
);
expect(await client.query('test')).toMatchInlineSnapshot(`"alexdotjs"`);
await close();
});
test('omitting ctx in next() does not affect a previous middleware', async () => {
type User = {
id: string;
};
type OriginalContext = {
maybeUser?: User;
};
const { client, close } = legacyRouterToServerAndClient(
trpc
.router<OriginalContext>()
.middleware(({ ctx, next }) => {
if (!ctx.maybeUser) {
throw new Error('No user');
}
return next({
ctx: {
...ctx,
user: ctx.maybeUser,
},
});
})
.middleware(async function firstMiddleware({ next }) {
return next();
})
.query('test', {
resolve({ ctx }) {
expectTypeOf(ctx).toEqualTypeOf<
OriginalContext & {
user: User;
}
>();
return ctx.user.id;
},
}),
{
server: {
createContext() {
return {
maybeUser: {
id: 'alexdotjs',
},
};
},
},
},
);
expect(await client.query('test')).toMatchInlineSnapshot(`"alexdotjs"`);
await close();
});
test('mutate context in middleware', async () => {
type User = {
id: string;
};
type OriginalContext = {
maybeUser?: User;
};
const { client, close } = legacyRouterToServerAndClient(
trpc
.router<OriginalContext>()
.middleware(async function firstMiddleware({ next }) {
return next();
})
.query('isAuthorized', {
resolve({ ctx }) {
return Boolean(ctx.maybeUser);
},
})
.middleware(async function secondMiddleware({ next, ctx }) {
if (!ctx.maybeUser) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
const newContext = {
user: ctx.maybeUser,
};
const result = await next({ ctx: newContext });
return result;
})
.middleware(async function thirdMiddleware({ next, ctx }) {
return next({
ctx: {
...ctx,
email: ctx.user.id.includes('@'),
},
});
})
.query('test', {
resolve({ ctx }) {
// should have asserted that `ctx.user` is not nullable
expectTypeOf(ctx).toEqualTypeOf<{ user: User; email: boolean }>();
return `id: ${ctx.user.id}, email: ${ctx.email}`;
},
}),
{
server: {
createContext() {
return {
maybeUser: {
id: 'alexdotjs',
},
};
},
},
},
);
expect(await client.query('isAuthorized')).toBe(true);
expect(await client.query('test')).toMatchInlineSnapshot(
`"id: alexdotjs, email: false"`,
);
await close();
});
test('mutate context and combine with other routes', async () => {
type User = {
id: number;
};
type Context = {
maybeUser?: User;
};
function createRouter() {
return trpc.router<Context>();
}
const authorizedRouter = createRouter()
.middleware(({ ctx, next }) => {
if (!ctx.maybeUser) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next({
ctx: {
user: ctx.maybeUser,
},
});
})
.query('me', {
resolve({ ctx }) {
return ctx.user;
},
});
const appRouter = createRouter()
.merge('authed.', authorizedRouter)
.query('someQuery', {
resolve({ ctx }) {
expectTypeOf(ctx).toMatchTypeOf<Context>();
},
})
.interop();
type AppRouter = typeof appRouter;
type MeResponse = inferProcedureOutput<
AppRouter['_def']['queries']['authed.me']
>;
expectTypeOf<MeResponse>().toMatchTypeOf<User>();
});
|
5,209 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/outputParser.test.ts | import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import * as trpc from '@trpc/server/src';
import myzod from 'myzod';
import * as t from 'superstruct';
import * as yup from 'yup';
import { z } from 'zod';
test('zod', async () => {
const router = trpc.router().query('q', {
input: z.string().or(z.number()),
output: z.object({
input: z.string(),
}),
resolve({ input }) {
return { input: input as string };
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const output = await client.query('q', 'foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(client.query('q', 1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('zod async', async () => {
const router = trpc.router().query('q', {
input: z.string().or(z.number()),
output: z
.object({
input: z.string(),
})
.refine(async (value) => !!value),
resolve({ input }) {
return { input: input as string };
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const output = await client.query('q', 'foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(client.query('q', 1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('zod transform', async () => {
const router = trpc.router().query('q', {
input: z.string().or(z.number()),
output: z.object({
input: z.string().transform((s) => s.length),
}),
resolve({ input }) {
return { input: input as string };
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const output = await client.query('q', 'foobar');
expectTypeOf(output.input).toBeNumber();
expect(output).toMatchInlineSnapshot(`
Object {
"input": 6,
}
`);
await expect(client.query('q', 1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('superstruct', async () => {
const router = trpc.router().query('q', {
input: t.union([t.string(), t.number()]),
output: t.object({
input: t.string(),
}),
resolve({ input }) {
return { input: input as string };
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const output = await client.query('q', 'foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(client.query('q', 1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('yup', async () => {
const yupStringOrNumber = (value: unknown) => {
switch (typeof value) {
case 'number':
return yup.number().required();
case 'string':
return yup.string().required();
default:
throw new Error('Fail');
}
};
const router = trpc.router().query('q', {
input: yup.lazy(yupStringOrNumber),
output: yup.object({
input: yup.string().strict().required(),
}),
resolve({ input }) {
return { input: input as string };
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const output = await client.query('q', 'foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(client.query('q', 1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('myzod', async () => {
const router = trpc.router().query('q', {
input: myzod.string().or(myzod.number()),
output: myzod.object({
input: myzod.string(),
}),
resolve({ input }) {
return { input: input as string };
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const output = await client.query('q', 'foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(client.query('q', 1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('validator fn', async () => {
const router = trpc.router().query('q', {
input: (value: unknown) => value as number | string,
output: (value: unknown) => {
if (typeof (value as any).input === 'string') {
return value as { input: string };
}
throw new Error('Fail');
},
resolve({ input }) {
return { input: input as string };
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const output = await client.query('q', 'foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(client.query('q', 1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('async validator fn', async () => {
const router = trpc.router().query('q', {
input: (value: unknown) => value as number | string,
output: async (value: any): Promise<{ input: string }> => {
if (value && typeof value.input === 'string') {
return { input: value.input };
}
throw new Error('Fail');
},
resolve({ input }) {
return { input: input as string };
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const output = await client.query('q', 'foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(client.query('q', 1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
|
5,210 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/rawFetch.test.tsx | import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import * as trpc from '@trpc/server/src';
import { z } from 'zod';
const factory = () =>
legacyRouterToServerAndClient(
trpc
.router()
.query('myQuery', {
input: z
.object({
name: z.string(),
})
.optional(),
resolve({ input }) {
return input?.name ?? 'default';
},
})
.mutation('myMutation', {
input: z.object({
name: z.string(),
}),
async resolve({ input }) {
return { input };
},
}),
);
test('batching with raw batch', async () => {
const { close, httpUrl } = factory();
{
const res = await fetch(
`${httpUrl}/myQuery?batch=1&input=${JSON.stringify({
'0': { name: 'alexdotjs' },
})}`,
);
const json: any = await res.json();
expect(json[0]).toHaveProperty('result');
expect(json[0].result).toMatchInlineSnapshot(`
Object {
"data": "alexdotjs",
}
`);
}
await close();
});
|
5,211 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/responseMeta.test.ts | import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import * as trpc from '@trpc/server/src';
import { CreateHTTPContextOptions } from '@trpc/server/src/adapters/standalone';
import fetch from 'node-fetch';
test('set custom headers in beforeEnd', async () => {
const onError = vi.fn();
const { close, httpUrl } = legacyRouterToServerAndClient(
trpc
.router<CreateHTTPContextOptions>()
.query('public.q', {
resolve() {
return 'public endpoint';
},
})
.query('nonCachedEndpoint', {
resolve() {
return 'not cached endpoint';
},
}),
{
server: {
onError,
responseMeta({ ctx, paths, type, errors }) {
// assuming you have all your public routes with the keyword `public` in them
const allPublic = paths?.every((path) => path.includes('public'));
// checking that no procedures errored
const allOk = errors.length === 0;
// checking we're doing a query request
const isQuery = type === 'query';
if (ctx?.res && allPublic && allOk && isQuery) {
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
}
return {};
},
},
},
);
{
const res = await fetch(`${httpUrl}/public.q`);
expect(await res.json()).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "public endpoint",
},
}
`);
expect(res.headers.get('cache-control')).toMatchInlineSnapshot(
`"s-maxage=1, stale-while-revalidate=86400"`,
);
}
{
const res = await fetch(`${httpUrl}/nonCachedEndpoint`);
expect(await res.json()).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "not cached endpoint",
},
}
`);
expect(res.headers.get('cache-control')).toBeNull();
}
await close();
});
|
5,212 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/router.test.ts | import { router } from '@trpc/server/src/deprecated/router';
test('double errors', async () => {
expect(() => {
router()
.query('dupe', {
resolve() {
return null;
},
})
.query('dupe', {
resolve() {
return null;
},
});
}).toThrowErrorMatchingInlineSnapshot(`"Duplicate endpoint(s): dupe"`);
});
|
5,213 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/routerMeta.test.ts | import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import * as trpc from '@trpc/server/src';
import { inferRouterMeta } from '@trpc/server/src';
import { observable } from '@trpc/server/src/observable';
test('route meta types', async () => {
const testMeta = { data: 'foo' };
const router = trpc
.router<any, typeof testMeta>()
.middleware(({ next }) => {
return next();
})
.query('query', {
meta: testMeta,
async resolve({ input }) {
return { input };
},
})
.subscription('subscription', {
meta: testMeta,
async resolve() {
return observable(() => () => '');
},
})
.mutation('mutation', {
meta: testMeta,
async resolve({ input }) {
return { input };
},
})
.interop();
type TMeta = inferRouterMeta<typeof router>;
expectTypeOf<TMeta>().toMatchTypeOf(testMeta);
expect(router._def.queries).not.toEqual({});
expect(router._def.queries).toMatchInlineSnapshot(`
Object {
"query": [Function],
}
`);
const queryMeta = router._def.queries.query.meta;
expectTypeOf(queryMeta).toMatchTypeOf<TMeta | undefined>();
expect(queryMeta).toEqual(testMeta);
const mutationMeta = router._def.mutations.mutation.meta;
expectTypeOf(mutationMeta).toMatchTypeOf<TMeta | undefined>();
expect(mutationMeta).toEqual(testMeta);
const subscriptionMeta = router._def.subscriptions.subscription.meta;
expectTypeOf(subscriptionMeta).toMatchTypeOf<TMeta | undefined>();
expect(subscriptionMeta).toEqual(testMeta);
});
test('route meta in middleware', async () => {
const middleware = vi.fn((opts) => {
return opts.next();
});
const { client, close } = legacyRouterToServerAndClient(
trpc
.router<any, { data: string }>()
.middleware(middleware)
.query('foo1', {
meta: {
data: 'foo1',
},
resolve() {
return 'bar1';
},
})
.mutation('foo2', {
meta: {
data: 'foo2',
},
resolve() {
return 'bar2';
},
}),
);
const calls = middleware.mock.calls;
expect(await client.query('foo1')).toBe('bar1');
expect(calls[0]![0]!).toHaveProperty('meta');
expect(calls[0]![0]!.meta).toEqual({
data: 'foo1',
});
expect(await client.mutation('foo2')).toBe('bar2');
expect(calls[1]![0]!).toHaveProperty('meta');
expect(calls[1]![0]!.meta).toEqual({
data: 'foo2',
});
expect(middleware).toHaveBeenCalledTimes(2);
await close();
});
|
5,214 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/transformer.test.ts | import { routerToServerAndClientNew, waitError } from '../___testHelpers';
import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import {
createWSClient,
httpBatchLink,
httpLink,
TRPCClientError,
wsLink,
} from '@trpc/client/src';
import * as trpc from '@trpc/server/src';
import { TRPCError } from '@trpc/server/src/error/TRPCError';
import { observable } from '@trpc/server/src/observable';
import { uneval } from 'devalue';
import fetch from 'node-fetch';
import superjson from 'superjson';
import { z } from 'zod';
test('superjson up and down', async () => {
const transformer = superjson;
const date = new Date();
const fn = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('hello', {
input: z.date(),
resolve({ input }) {
fn(input);
return input;
},
}),
{
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
},
);
const res = await client.query('hello', date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('empty superjson up and down', async () => {
const transformer = superjson;
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('empty-up', {
resolve() {
return 'hello world';
},
})
.query('empty-down', {
input: z.string(),
resolve() {
return 'hello world';
},
}),
{
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
},
);
const res1 = await client.query('empty-up');
expect(res1).toBe('hello world');
const res2 = await client.query('empty-down', '');
expect(res2).toBe('hello world');
await close();
});
test('wsLink: empty superjson up and down', async () => {
const transformer = superjson;
let ws: any = null;
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('empty-up', {
resolve() {
return 'hello world';
},
})
.query('empty-down', {
input: z.string(),
resolve() {
return 'hello world';
},
}),
{
client({ wssUrl }) {
ws = createWSClient({ url: wssUrl });
return {
transformer,
links: [wsLink({ client: ws })],
};
},
},
);
const res1 = await client.query('empty-up');
expect(res1).toBe('hello world');
const res2 = await client.query('empty-down', '');
expect(res2).toBe('hello world');
await close();
ws.close();
});
test('devalue up and down', async () => {
const transformer: trpc.DataTransformer = {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
};
const date = new Date();
const fn = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('hello', {
input: z.date(),
resolve({ input }) {
fn(input);
return input;
},
}),
{
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
},
);
const res = await client.query('hello', date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('not batching: superjson up and devalue down', async () => {
const transformer: trpc.CombinedDataTransformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
},
};
const date = new Date();
const fn = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('hello', {
input: z.date(),
resolve({ input }) {
fn(input);
return input;
},
}),
{
client({ httpUrl }) {
return {
transformer,
links: [httpLink({ url: httpUrl })],
};
},
},
);
const res = await client.query('hello', date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('batching: superjson up and uneval down', async () => {
const transformer: trpc.CombinedDataTransformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
},
};
const date = new Date();
const fn = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('hello', {
input: z.date(),
resolve({ input }) {
fn(input);
return input;
},
}),
{
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
},
);
const res = await client.query('hello', date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('batching: superjson up and f down', async () => {
const transformer: trpc.CombinedDataTransformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
},
};
const date = new Date();
const fn = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('hello', {
input: z.date(),
resolve({ input }) {
fn(input);
return input;
},
}),
{
client: ({ httpUrl }) => ({
transformer,
links: [httpBatchLink({ url: httpUrl })],
}),
},
);
const res = await client.query('hello', date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('all transformers running in correct order', async () => {
const world = 'foo';
const fn = vi.fn();
const transformer: trpc.CombinedDataTransformer = {
input: {
serialize: (object) => {
fn('client:serialized');
return object;
},
deserialize: (object) => {
fn('server:deserialized');
return object;
},
},
output: {
serialize: (object) => {
fn('server:serialized');
return object;
},
deserialize: (object) => {
fn('client:deserialized');
return object;
},
},
};
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('hello', {
input: z.string(),
resolve({ input }) {
fn(input);
return input;
},
}),
{
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
},
);
const res = await client.query('hello', world);
expect(res).toBe(world);
expect(fn.mock.calls[0]![0]!).toBe('client:serialized');
expect(fn.mock.calls[1]![0]!).toBe('server:deserialized');
expect(fn.mock.calls[2]![0]!).toBe(world);
expect(fn.mock.calls[3]![0]!).toBe('server:serialized');
expect(fn.mock.calls[4]![0]!).toBe('client:deserialized');
await close();
});
describe('transformer on router', () => {
test('http', async () => {
const transformer = superjson;
const date = new Date();
const fn = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('hello', {
input: z.date(),
resolve({ input }) {
fn(input);
return input;
},
}),
{
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
},
);
const res = await client.query('hello', date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('ws', async () => {
let wsClient: any;
const date = new Date();
const fn = vi.fn();
const transformer = superjson;
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('hello', {
input: z.date(),
resolve({ input }) {
fn(input);
return input;
},
}),
{
client({ wssUrl }) {
wsClient = createWSClient({
url: wssUrl,
});
return {
transformer,
links: [wsLink({ client: wsClient })],
};
},
},
);
const res = await client.query('hello', date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
wsClient.close();
await close();
});
test('subscription', async () => {
let wsClient: any;
const date = new Date();
const fn = vi.fn();
const transformer = superjson;
const { client, close } = routerToServerAndClientNew(
trpc
.router()
.transformer(transformer)
.subscription('hello', {
input: z.date(),
resolve({ input }) {
return observable<Date>((emit) => {
fn(input);
emit.next(input);
return () => {
// noop
};
});
},
})
.interop(),
{
client({ wssUrl }) {
wsClient = createWSClient({
url: wssUrl,
});
return {
transformer,
links: [wsLink({ client: wsClient })],
};
},
},
);
const data = await new Promise<Date>((resolve) => {
const subscription = client.subscription('hello', date, {
onData: (data) => {
subscription.unsubscribe();
resolve(data);
},
});
});
expect(data.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
wsClient.close();
await close();
});
test('duplicate transformers', () => {
expect(() =>
trpc.router().transformer(superjson).transformer(superjson),
).toThrowErrorMatchingInlineSnapshot(
`"You seem to have double \`transformer()\`-calls in your router tree"`,
);
});
test('superjson up and uneval down: transform errors correctly', async () => {
const transformer: trpc.CombinedDataTransformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
},
};
class MyError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, MyError.prototype);
}
}
const onError = vi.fn();
const { client, close } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('err', {
resolve() {
throw new MyError('woop');
},
}),
{
server: {
onError,
},
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
},
);
const clientError = await waitError(client.query('err'), TRPCClientError);
expect(clientError.shape.message).toMatchInlineSnapshot(`"woop"`);
expect(clientError.shape.code).toMatchInlineSnapshot(`-32603`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError).toBeInstanceOf(TRPCError);
if (!(serverError instanceof TRPCError)) {
throw new Error('Wrong error');
}
expect(serverError.cause).toBeInstanceOf(MyError);
await close();
});
});
test('superjson - no input', async () => {
const transformer = superjson;
const fn = vi.fn();
const { close, httpUrl } = legacyRouterToServerAndClient(
trpc
.router()
.transformer(transformer)
.query('hello', {
async resolve({ input }) {
fn(input);
return 'world';
},
}),
{
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
},
);
const json = await (await fetch(`${httpUrl}/hello`)).json();
expect(json).not.toHaveProperty('error');
expect(json).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"json": "world",
},
},
}
`);
await close();
});
|
5,215 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/validators.test.ts | import { legacyRouterToServerAndClient } from './__legacyRouterToServerAndClient';
import * as trpc from '@trpc/server/src';
import myzod from 'myzod';
import * as t from 'superstruct';
import * as yup from 'yup';
import { z } from 'zod';
test('no validator', async () => {
const router = trpc.router().query('hello', {
resolve({ input }) {
expectTypeOf(input).toBeUndefined();
return 'test';
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const res = await client.query('hello');
expect(res).toBe('test');
await close();
});
test('zod', async () => {
const router = trpc.router().query('num', {
input: z.number(),
resolve({ input }) {
expectTypeOf(input).toBeNumber();
return {
input,
};
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const res = await client.query('num', 123);
await expect(client.query('num', '123' as any)).rejects
.toMatchInlineSnapshot(`
[TRPCClientError: [
{
"code": "invalid_type",
"expected": "number",
"received": "string",
"path": [],
"message": "Expected number, received string"
}
]]
`);
expect(res.input).toBe(123);
await close();
});
test('zod async', async () => {
const input = z.string().refine(async (value) => value === 'foo');
const router = trpc.router().query('q', {
input,
resolve({ input }) {
expectTypeOf(input).toBeString();
return {
input,
};
},
});
const { client, close } = legacyRouterToServerAndClient(router);
await expect(client.query('q', 'bar')).rejects.toMatchInlineSnapshot(`
[TRPCClientError: [
{
"code": "custom",
"message": "Invalid input",
"path": []
}
]]
`);
const res = await client.query('q', 'foo');
expect(res).toMatchInlineSnapshot(`
Object {
"input": "foo",
}
`);
await close();
});
test('zod transform mixed input/output', async () => {
const input = z.object({
length: z.string().transform((s) => s.length),
});
const router = trpc.router().query('num', {
input: input,
resolve({ input }) {
expectTypeOf(input.length).toBeNumber();
return {
input,
};
},
});
const { client, close } = legacyRouterToServerAndClient(router);
await expect(client.query('num', { length: '123' })).resolves
.toMatchInlineSnapshot(`
Object {
"input": Object {
"length": 3,
},
}
`);
await expect(
// @ts-expect-error this should only accept a string
client.query('num', { length: 123 }),
).rejects.toMatchInlineSnapshot(`
[TRPCClientError: [
{
"code": "invalid_type",
"expected": "string",
"received": "number",
"path": [
"length"
],
"message": "Expected string, received number"
}
]]
`);
await close();
});
test('superstruct', async () => {
const router = trpc.router().query('num', {
input: t.number(),
resolve({ input }) {
expectTypeOf(input).toBeNumber();
return {
input,
};
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const res = await client.query('num', 123);
// @ts-expect-error this only accepts a `number`
await expect(client.query('num', '123')).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Expected a number, but received: "123"]`,
);
expect(res.input).toBe(123);
await close();
});
test('yup', async () => {
const router = trpc.router().query('num', {
input: yup.number().required(),
resolve({ input }) {
expectTypeOf(input).toMatchTypeOf<number>();
return {
input,
};
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const res = await client.query('num', 123);
// @ts-expect-error this only accepts a `number`
await expect(client.query('num', 'asd')).rejects.toMatchInlineSnapshot(
`[TRPCClientError: this must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"asd"\`).]`,
);
expect(res.input).toBe(123);
await close();
});
test('myzod', async () => {
const router = trpc.router().query('num', {
input: myzod.number(),
resolve({ input }) {
expectTypeOf(input).toMatchTypeOf<number>();
return {
input,
};
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const res = await client.query('num', 123);
await expect(client.query('num', '123' as any)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: expected type to be number but got string]`,
);
expect(res.input).toBe(123);
await close();
});
test('validator fn', async () => {
function numParser(input: unknown) {
if (typeof input !== 'number') {
throw new Error('Not a number');
}
return input;
}
const router = trpc.router().query('num', {
input: numParser,
resolve({ input }) {
expectTypeOf(input).toBeNumber();
return {
input,
};
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const res = await client.query('num', 123);
await expect(client.query('num', '123' as any)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Not a number]`,
);
expect(res.input).toBe(123);
await close();
});
test('async validator fn', async () => {
async function numParser(input: unknown) {
if (typeof input !== 'number') {
throw new Error('Not a number');
}
return input;
}
const router = trpc.router().query('num', {
input: numParser,
resolve({ input }) {
expectTypeOf(input).toBeNumber();
return {
input,
};
},
});
const { client, close } = legacyRouterToServerAndClient(router);
const res = await client.query('num', 123);
await expect(client.query('num', '123' as any)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Not a number]`,
);
expect(res.input).toBe(123);
await close();
});
|
5,216 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/interop/websockets.test.ts | import { EventEmitter } from 'events';
import { routerToServerAndClientNew, waitMs } from '../___testHelpers';
import { waitFor } from '@testing-library/react';
import { createWSClient, TRPCClientError, wsLink } from '@trpc/client/src';
import * as trpc from '@trpc/server/src';
import { AnyRouter, TRPCError } from '@trpc/server/src';
import { applyWSSHandler } from '@trpc/server/src/adapters/ws';
import { observable, Observer } from '@trpc/server/src/observable';
import {
TRPCClientOutgoingMessage,
TRPCRequestMessage,
} from '@trpc/server/src/rpc';
import WebSocket, { Server } from 'ws';
import { z } from 'zod';
type Message = {
id: string;
};
function factory(config?: { createContext: () => Promise<any> }) {
const ee = new EventEmitter();
const subRef: {
current: Observer<Message, unknown>;
} = {} as any;
const onNewMessageSubscription = vi.fn();
const subscriptionEnded = vi.fn();
const onNewClient = vi.fn();
const oldRouter = trpc
.router()
.query('greeting', {
input: z.string().nullish(),
resolve({ input }) {
return `hello ${input ?? 'world'}`;
},
})
.mutation('slow', {
async resolve() {
await waitMs(50);
return 'slow query resolved';
},
})
.mutation('post.edit', {
input: z.object({
id: z.string(),
data: z.object({
title: z.string(),
text: z.string(),
}),
}),
async resolve({ input }) {
const { id, data } = input;
return {
id,
...data,
};
},
})
.subscription('onMessage', {
input: z.string().nullish(),
resolve() {
const sub = observable<Message>((emit) => {
subRef.current = emit;
const onMessage = (data: Message) => {
emit.next(data);
};
ee.on('server:msg', onMessage);
return () => {
subscriptionEnded();
ee.off('server:msg', onMessage);
};
});
ee.emit('subscription:created');
onNewMessageSubscription();
return sub;
},
})
.interop();
const onOpenMock = vi.fn();
const onCloseMock = vi.fn();
expectTypeOf(oldRouter).toMatchTypeOf<AnyRouter>();
expectTypeOf<AnyRouter>().toMatchTypeOf<typeof oldRouter>();
const opts = routerToServerAndClientNew(oldRouter, {
wsClient: {
retryDelayMs: () => 10,
onOpen: onOpenMock,
onClose: onCloseMock,
},
client({ wsClient }) {
return {
links: [wsLink({ client: wsClient })],
};
},
server: {
...(config ?? {}),
},
wssServer: {
...(config ?? {}),
},
});
opts.wss.addListener('connection', onNewClient);
return {
...opts,
ee,
subRef,
onNewMessageSubscription,
onNewClient,
onOpenMock,
onCloseMock,
};
}
test('query', async () => {
const { client, close } = factory();
expect(await client.query('greeting')).toBe('hello world');
expect(await client.query('greeting', null)).toBe('hello world');
expect(await client.query('greeting', 'alexdotjs')).toBe('hello alexdotjs');
await close();
});
test('mutation', async () => {
const { client, close } = factory();
expect(
await client.mutation('post.edit', {
id: 'id',
data: { title: 'title', text: 'text' },
}),
).toMatchInlineSnapshot(`
Object {
"id": "id",
"text": "text",
"title": "title",
}
`);
await close();
});
test('basic subscription test', async () => {
const { client, close, ee } = factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
ee.emit('server:msg', {
id: '2',
});
});
});
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const subscription = client.subscription('onMessage', undefined, {
onStarted() {
onStartedMock();
},
onData(data) {
expectTypeOf(data).not.toBeAny();
expectTypeOf(data).toMatchTypeOf<Message>();
onDataMock(data);
},
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(2);
});
ee.emit('server:msg', {
id: '2',
});
await waitFor(() => {
expect(onDataMock).toHaveBeenCalledTimes(3);
});
expect(onDataMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
Object {
"id": "1",
},
],
Array [
Object {
"id": "2",
},
],
Array [
Object {
"id": "2",
},
],
]
`);
subscription.unsubscribe();
await waitFor(() => {
expect(ee.listenerCount('server:msg')).toBe(0);
expect(ee.listenerCount('server:error')).toBe(0);
});
await close();
});
test.skip('$subscription() - server randomly stop and restart (this test might be flaky, try re-running)', async () => {
const { client, close, ee, wssPort, applyWSSHandlerOpts } = factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
ee.emit('server:msg', {
id: '2',
});
});
});
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const onCompleteMock = vi.fn();
client.subscription('onMessage', undefined, {
onStarted: onStartedMock,
onData: onDataMock,
onError: onErrorMock,
onComplete: onCompleteMock,
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(2);
});
// close websocket server
await close();
await waitFor(() => {
expect(onErrorMock).toHaveBeenCalledTimes(1);
expect(onCompleteMock).toHaveBeenCalledTimes(0);
});
expect(onErrorMock.mock.calls[0]![0]!).toMatchInlineSnapshot(
`[TRPCClientError: WebSocket closed prematurely]`,
);
expect(onErrorMock.mock.calls[0]![0]!.originalError.name).toBe(
'TRPCWebSocketClosedError',
);
// start a new wss server on same port, and trigger a message
onStartedMock.mockClear();
onDataMock.mockClear();
onCompleteMock.mockClear();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '3',
});
}, 1);
});
const wss = new Server({ port: wssPort });
applyWSSHandler({ ...applyWSSHandlerOpts, wss });
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(1);
});
expect(onDataMock.mock.calls.map((args) => args[0])).toMatchInlineSnapshot(`
Array [
Object {
"id": "3",
},
]
`);
wss.close();
});
test('server subscription ended', async () => {
const { client, close, ee, subRef } = factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
ee.emit('server:msg', {
id: '2',
});
});
});
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const onCompleteMock = vi.fn();
client.subscription('onMessage', undefined, {
onStarted: onStartedMock,
onData: onDataMock,
onError: onErrorMock,
onComplete: onCompleteMock,
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(2);
});
// destroy server subscription
subRef.current.complete();
await waitFor(() => {
expect(onCompleteMock).toHaveBeenCalledTimes(1);
});
await close();
});
test('sub emits errors', async () => {
const { client, close, wss, ee, subRef } = factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
subRef.current.error(new Error('test'));
});
});
const onNewClient = vi.fn();
wss.addListener('connection', onNewClient);
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const onCompleteMock = vi.fn();
client.subscription('onMessage', undefined, {
onStarted: onStartedMock,
onData: onDataMock,
onError: onErrorMock,
onComplete: onCompleteMock,
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(1);
expect(onErrorMock).toHaveBeenCalledTimes(1);
expect(onCompleteMock).toHaveBeenCalledTimes(0);
});
await close();
});
test(
'wait for slow queries/mutations before disconnecting',
async () => {
const { client, close, wsClient, onNewClient } = factory();
await waitFor(() => {
expect(onNewClient).toHaveBeenCalledTimes(1);
});
const promise = client.mutation('slow');
wsClient.close();
expect(await promise).toMatchInlineSnapshot(`"slow query resolved"`);
await close();
await waitFor(() => {
expect(wsClient.getConnection().readyState).toBe(WebSocket.CLOSED);
});
await close();
},
{ retry: 5 },
);
test(
'subscriptions are automatically resumed',
async () => {
const { client, close, ee, wssHandler, wss, onOpenMock, onCloseMock } =
factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
});
});
function createSub() {
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const onStoppedMock = vi.fn();
const onCompleteMock = vi.fn();
const unsub = client.subscription('onMessage', undefined, {
onStarted: onStartedMock(),
onData: onDataMock,
onError: onErrorMock,
onStopped: onStoppedMock,
onComplete: onCompleteMock,
});
return {
onStartedMock,
onDataMock,
onErrorMock,
onStoppedMock,
onCompleteMock,
unsub,
};
}
const sub1 = createSub();
await waitFor(() => {
expect(sub1.onStartedMock).toHaveBeenCalledTimes(1);
expect(sub1.onDataMock).toHaveBeenCalledTimes(1);
expect(onOpenMock).toHaveBeenCalledTimes(1);
expect(onCloseMock).toHaveBeenCalledTimes(0);
});
wssHandler.broadcastReconnectNotification();
await waitFor(() => {
expect(wss.clients.size).toBe(1);
expect(onOpenMock).toHaveBeenCalledTimes(2);
expect(onCloseMock).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(sub1.onStartedMock).toHaveBeenCalledTimes(1);
expect(sub1.onDataMock).toHaveBeenCalledTimes(1);
});
ee.emit('server:msg', {
id: '2',
});
await waitFor(() => {
expect(sub1.onDataMock).toHaveBeenCalledTimes(2);
});
expect(sub1.onDataMock.mock.calls.map((args) => args[0]))
.toMatchInlineSnapshot(`
Array [
Object {
"id": "1",
},
Object {
"id": "2",
},
]
`);
await waitFor(() => {
expect(wss.clients.size).toBe(1);
});
await close();
await waitFor(() => {
expect(onCloseMock).toHaveBeenCalledTimes(2);
});
},
{ retry: 5 },
);
test('not found error', async () => {
const { client, close, router } = factory();
const error: TRPCClientError<typeof router> = await new Promise(
(resolve, reject) =>
client
.query('notFound' as any)
.then(reject)
.catch(resolve),
);
expect(error.name).toBe('TRPCClientError');
expect(error.shape?.data.code).toMatchInlineSnapshot(`"NOT_FOUND"`);
await close();
});
test('batching', async () => {
const t = factory();
const promises = [
t.client.query('greeting'),
t.client.mutation('post.edit', { id: '', data: { text: '', title: '' } }),
] as const;
expect(await Promise.all(promises)).toMatchInlineSnapshot(`
Array [
"hello world",
Object {
"id": "",
"text": "",
"title": "",
},
]
`);
await t.close();
});
describe('regression test - slow createContext', () => {
test(
'send messages immediately on connection',
async () => {
const t = factory({
async createContext() {
await waitMs(50);
return {};
},
});
const rawClient = new WebSocket(t.wssUrl);
const msg: TRPCRequestMessage = {
id: 1,
method: 'query',
params: {
path: 'greeting',
input: null,
},
};
const msgStr = JSON.stringify(msg);
rawClient.onopen = () => {
rawClient.send(msgStr);
};
const data = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
expect(JSON.parse(data)).toMatchInlineSnapshot(`
Object {
"id": 1,
"result": Object {
"data": "hello world",
"type": "data",
},
}
`);
rawClient.close();
await t.close();
},
{ retry: 5 },
);
test(
'createContext throws',
async () => {
const createContext = vi.fn(async () => {
await waitMs(20);
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'test' });
});
const t = factory({
createContext,
});
// close built-in client immediately to prevent connection
t.wsClient.close();
const rawClient = new WebSocket(t.wssUrl);
const msg: TRPCRequestMessage = {
id: 1,
method: 'query',
params: {
path: 'greeting',
input: null,
},
};
const msgStr = JSON.stringify(msg);
rawClient.onopen = () => {
rawClient.send(msgStr);
};
const responses: any[] = [];
rawClient.addEventListener('message', (msg) => {
responses.push(JSON.parse(msg.data as any));
});
await new Promise<void>((resolve) => {
rawClient.addEventListener('close', () => {
resolve();
});
});
for (const res of responses) {
expect(res).toHaveProperty('error');
expect(typeof res.error.data.stack).toBe('string');
res.error.data.stack = '[redacted]';
}
expect(responses).toHaveLength(2);
const [first, second] = responses;
expect(first.id).toBe(null);
expect(second.id).toBe(1);
expect(responses).toMatchInlineSnapshot(`
Array [
Object {
"error": Object {
"code": -32001,
"data": Object {
"code": "UNAUTHORIZED",
"httpStatus": 401,
"stack": "[redacted]",
},
"message": "test",
},
"id": null,
},
Object {
"error": Object {
"code": -32001,
"data": Object {
"code": "UNAUTHORIZED",
"httpStatus": 401,
"path": "greeting",
"stack": "[redacted]",
},
"message": "test",
},
"id": 1,
},
]
`);
expect(createContext).toHaveBeenCalledTimes(1);
await t.close();
},
{ retry: 5 },
);
});
test('malformatted JSON', async () => {
const t = factory();
// close built-in client immediately to prevent connection
t.wsClient.close();
const rawClient = new WebSocket(t.wssUrl);
rawClient.onopen = () => {
rawClient.send('not json');
};
const res: any = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(JSON.parse(msg.data as any));
});
});
expect(res).toHaveProperty('error');
expect(typeof res.error.data.stack).toBe('string');
res.error.data.stack = '[redacted]';
expect(res.id).toBe(null);
// replace "Unexpected token "o" with aaa
res.error.message = res.error.message.replace(
/^Unexpected token.*/,
'Unexpected token [... redacted b/c it is different in node 20]',
);
expect(res).toMatchInlineSnapshot(`
Object {
"error": Object {
"code": -32700,
"data": Object {
"code": "PARSE_ERROR",
"httpStatus": 400,
"stack": "[redacted]",
},
"message": "Unexpected token [... redacted b/c it is different in node 20]",
},
"id": null,
}
`);
await t.close();
});
test('regression - badly shaped request', async () => {
const t = factory();
const rawClient = new WebSocket(t.wssUrl);
const msg: TRPCRequestMessage = {
id: null,
method: 'query',
params: {
path: 'greeting',
input: null,
},
};
const msgStr = JSON.stringify(msg);
rawClient.onopen = () => {
rawClient.send(msgStr);
};
const result = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
const data = JSON.parse(result);
data.error.data.stack = '[redacted]';
expect(data).toMatchInlineSnapshot(`
Object {
"error": Object {
"code": -32700,
"data": Object {
"code": "PARSE_ERROR",
"httpStatus": 400,
"stack": "[redacted]",
},
"message": "\`id\` is required",
},
"id": null,
}
`);
rawClient.close();
await t.close();
});
describe('include "jsonrpc" in response if sent with message', () => {
test('queries & mutations', async () => {
const t = factory();
const rawClient = new WebSocket(t.wssUrl);
const queryMessageWithJsonRPC: TRPCClientOutgoingMessage = {
id: 1,
jsonrpc: '2.0',
method: 'query',
params: {
path: 'greeting',
input: null,
},
};
rawClient.onopen = () => {
rawClient.send(JSON.stringify(queryMessageWithJsonRPC));
};
const queryResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
const queryData = JSON.parse(queryResult);
expect(queryData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"data": "hello world",
"type": "data",
},
}
`);
const mutationMessageWithJsonRPC: TRPCClientOutgoingMessage = {
id: 1,
jsonrpc: '2.0',
method: 'mutation',
params: {
path: 'slow',
input: undefined,
},
};
rawClient.send(JSON.stringify(mutationMessageWithJsonRPC));
const mutationResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
const mutationData = JSON.parse(mutationResult);
expect(mutationData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"data": "slow query resolved",
"type": "data",
},
}
`);
rawClient.close();
await t.close();
});
test('subscriptions', async () => {
const t = factory();
const rawClient = new WebSocket(t.wssUrl);
const subscriptionMessageWithJsonRPC: TRPCClientOutgoingMessage = {
id: 1,
jsonrpc: '2.0',
method: 'subscription',
params: {
path: 'onMessage',
input: null,
},
};
rawClient.onopen = () => {
rawClient.send(JSON.stringify(subscriptionMessageWithJsonRPC));
};
const startedResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
const startedData = JSON.parse(startedResult);
expect(startedData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"type": "started",
},
}
`);
const messageResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
t.ee.emit('server:msg', { id: '1' });
});
const messageData = JSON.parse(messageResult);
expect(messageData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"data": Object {
"id": "1",
},
"type": "data",
},
}
`);
const subscriptionStopNotificationWithJsonRPC: TRPCClientOutgoingMessage = {
id: 1,
jsonrpc: '2.0',
method: 'subscription.stop',
};
const stoppedResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
rawClient.send(JSON.stringify(subscriptionStopNotificationWithJsonRPC));
});
const stoppedData = JSON.parse(stoppedResult);
expect(stoppedData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"type": "stopped",
},
}
`);
rawClient.close();
await t.close();
});
});
test('wsClient stops reconnecting after .await close()', async () => {
const badWsUrl = 'ws://localhost:9999';
const retryDelayMsMock = vi.fn();
retryDelayMsMock.mockReturnValue(100);
const wsClient = createWSClient({
url: badWsUrl,
retryDelayMs: retryDelayMsMock,
});
await waitFor(() => {
expect(retryDelayMsMock).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(retryDelayMsMock).toHaveBeenCalledTimes(2);
});
wsClient.close();
await waitMs(100);
expect(retryDelayMsMock).toHaveBeenCalledTimes(2);
});
|
5,218 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/adapters/express.test.tsx | import http from 'http';
import { Context, router } from './__router';
import { createTRPCClient, httpBatchLink } from '@trpc/client/src';
import * as trpc from '@trpc/server/src';
import * as trpcExpress from '@trpc/server/src/adapters/express';
import express from 'express';
import fetch from 'node-fetch';
async function startServer() {
const createContext = (
_opts: trpcExpress.CreateExpressContextOptions,
): Context => {
const getUser = () => {
if (_opts.req.headers.authorization === 'meow') {
return {
name: 'KATT',
};
}
return null;
};
return {
user: getUser(),
};
};
// express implementation
const app = express();
app.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router,
createContext,
}),
);
const { server, port } = await new Promise<{
server: http.Server;
port: number;
}>((resolve) => {
const server = app.listen(0, () => {
resolve({
server,
port: (server.address() as any).port,
});
});
});
const client = createTRPCClient<typeof router>({
links: [
httpBatchLink({
url: `http://localhost:${port}/trpc`,
AbortController,
fetch: fetch as any,
}),
],
});
return {
close: () =>
new Promise<void>((resolve, reject) =>
server.close((err) => {
err ? reject(err) : resolve();
}),
),
port,
router,
client,
};
}
let t: trpc.inferAsyncReturnType<typeof startServer>;
beforeAll(async () => {
t = await startServer();
});
afterAll(async () => {
await t.close();
});
test('simple query', async () => {
expect(
await t.client.query('hello', {
who: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
const res = await t.client.query('hello');
expect(res).toMatchInlineSnapshot(`
Object {
"text": "hello world",
}
`);
});
|
5,219 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/adapters/fastify.test.ts | import { EventEmitter } from 'events';
import ws from '@fastify/websocket';
import { waitFor } from '@testing-library/react';
import {
createTRPCClient,
createWSClient,
HTTPHeaders,
httpLink,
splitLink,
wsLink,
} from '@trpc/client/src';
import { inferAsyncReturnType, router } from '@trpc/server/src';
import {
CreateFastifyContextOptions,
fastifyTRPCPlugin,
} from '@trpc/server/src/adapters/fastify';
import { observable } from '@trpc/server/src/observable';
import fastify from 'fastify';
import fp from 'fastify-plugin';
import fetch from 'node-fetch';
import { z } from 'zod';
const config = {
port: 2022,
logger: false,
prefix: '/trpc',
};
function createContext({ req, res }: CreateFastifyContextOptions) {
const user = { name: req.headers.username ?? 'anonymous' };
return { req, res, user };
}
type Context = inferAsyncReturnType<typeof createContext>;
interface Message {
id: string;
}
function createAppRouter() {
const ee = new EventEmitter();
const onNewMessageSubscription = vi.fn();
const onSubscriptionEnded = vi.fn();
const appRouter = router<Context>()
.query('ping', {
resolve() {
return 'pong';
},
})
.query('hello', {
input: z
.object({
username: z.string().nullish(),
})
.nullish(),
resolve({ input, ctx }) {
return {
text: `hello ${input?.username ?? ctx.user?.name ?? 'world'}`,
};
},
})
.mutation('post.edit', {
input: z.object({
id: z.string(),
data: z.object({
title: z.string(),
text: z.string(),
}),
}),
async resolve({ input, ctx }) {
if (ctx.user.name === 'anonymous') {
return { error: 'Unauthorized user' };
}
const { id, data } = input;
return { id, ...data };
},
})
.subscription('onMessage', {
resolve() {
const sub = observable<Message>((emit) => {
const onMessage = (data: Message) => {
emit.next(data);
};
ee.on('server:msg', onMessage);
return () => {
onSubscriptionEnded();
ee.off('server:msg', onMessage);
};
});
ee.emit('subscription:created');
onNewMessageSubscription();
return sub;
},
})
.interop();
return { appRouter, ee, onNewMessageSubscription, onSubscriptionEnded };
}
type CreateAppRouter = inferAsyncReturnType<typeof createAppRouter>;
type AppRouter = CreateAppRouter['appRouter'];
interface ServerOptions {
appRouter: AppRouter;
fastifyPluginWrapper?: boolean;
}
type PostPayload = { Body: { text: string; life: number } };
function createServer(opts: ServerOptions) {
const instance = fastify({ logger: config.logger });
const plugin = !!opts.fastifyPluginWrapper
? fp(fastifyTRPCPlugin)
: fastifyTRPCPlugin;
instance.register(ws);
instance.register(plugin, {
useWSS: true,
prefix: config.prefix,
trpcOptions: { router: opts.appRouter, createContext },
});
instance.get('/hello', async () => {
return { hello: 'GET' };
});
instance.post<PostPayload>('/hello', async ({ body }) => {
return { hello: 'POST', body };
});
const stop = async () => {
await instance.close();
};
const start = async () => {
try {
await instance.listen({ port: config.port });
} catch (err) {
instance.log.error(err);
}
};
return { instance, start, stop };
}
interface ClientOptions {
headers?: HTTPHeaders;
}
function createClient(opts: ClientOptions = {}) {
const host = `localhost:${config.port}${config.prefix}`;
const wsClient = createWSClient({ url: `ws://${host}` });
const client = createTRPCClient<AppRouter>({
links: [
splitLink({
condition(op) {
return op.type === 'subscription';
},
true: wsLink({ client: wsClient }),
false: httpLink({
url: `http://${host}`,
headers: opts.headers,
AbortController,
fetch: fetch as any,
}),
}),
],
});
return { client, wsClient };
}
interface AppOptions {
clientOptions?: ClientOptions;
serverOptions?: Partial<ServerOptions>;
}
function createApp(opts: AppOptions = {}) {
const { appRouter, ee } = createAppRouter();
const { instance, start, stop } = createServer({
...(opts.serverOptions ?? {}),
appRouter,
});
const { client } = createClient(opts.clientOptions);
return { server: instance, start, stop, client, ee };
}
let app: inferAsyncReturnType<typeof createApp>;
describe('anonymous user', () => {
beforeEach(async () => {
app = createApp();
await app.start();
});
afterEach(async () => {
await app.stop();
});
test('fetch POST', async () => {
const data = { text: 'life', life: 42 };
const req = await fetch(`http://localhost:${config.port}/hello`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
// body should be object
expect(await req.json()).toMatchInlineSnapshot(`
Object {
"body": Object {
"life": 42,
"text": "life",
},
"hello": "POST",
}
`);
});
test('query', async () => {
expect(await app.client.query('ping')).toMatchInlineSnapshot(`"pong"`);
expect(await app.client.query('hello')).toMatchInlineSnapshot(`
Object {
"text": "hello anonymous",
}
`);
expect(
await app.client.query('hello', {
username: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
});
test('mutation', async () => {
expect(
await app.client.mutation('post.edit', {
id: '42',
data: { title: 'new_title', text: 'new_text' },
}),
).toMatchInlineSnapshot(`
Object {
"error": "Unauthorized user",
}
`);
});
test('subscription', async () => {
app.ee.once('subscription:created', () => {
setTimeout(() => {
app.ee.emit('server:msg', {
id: '1',
});
app.ee.emit('server:msg', {
id: '2',
});
});
});
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const sub = app.client.subscription('onMessage', undefined, {
onStarted: onStartedMock,
onData(data) {
expectTypeOf(data).not.toBeAny();
expectTypeOf(data).toMatchTypeOf<Message>();
onDataMock(data);
},
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(2);
});
app.ee.emit('server:msg', {
id: '3',
});
await waitFor(() => {
expect(onDataMock).toHaveBeenCalledTimes(3);
});
expect(onDataMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
Object {
"id": "1",
},
],
Array [
Object {
"id": "2",
},
],
Array [
Object {
"id": "3",
},
],
]
`);
sub.unsubscribe();
await waitFor(() => {
expect(app.ee.listenerCount('server:msg')).toBe(0);
expect(app.ee.listenerCount('server:error')).toBe(0);
});
});
});
describe('authorized user', () => {
beforeEach(async () => {
app = createApp({ clientOptions: { headers: { username: 'nyan' } } });
await app.start();
});
afterEach(async () => {
await app.stop();
});
test('query', async () => {
expect(await app.client.query('hello')).toMatchInlineSnapshot(`
Object {
"text": "hello nyan",
}
`);
});
test('mutation', async () => {
expect(
await app.client.mutation('post.edit', {
id: '42',
data: { title: 'new_title', text: 'new_text' },
}),
).toMatchInlineSnapshot(`
Object {
"id": "42",
"text": "new_text",
"title": "new_title",
}
`);
});
});
describe('anonymous user with fastify-plugin', () => {
beforeEach(async () => {
app = createApp({ serverOptions: { fastifyPluginWrapper: true } });
await app.start();
});
afterEach(async () => {
await app.stop();
});
test('fetch GET', async () => {
const req = await fetch(`http://localhost:${config.port}/hello`);
expect(await req.json()).toEqual({ hello: 'GET' });
});
test('fetch POST', async () => {
const data = { text: 'life', life: 42 };
const req = await fetch(`http://localhost:${config.port}/hello`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
// body should be string
expect(await req.json()).toMatchInlineSnapshot(`
Object {
"body": "{\\"text\\":\\"life\\",\\"life\\":42}",
"hello": "POST",
}
`);
});
test('query', async () => {
expect(await app.client.query('ping')).toMatchInlineSnapshot(`"pong"`);
expect(await app.client.query('hello')).toMatchInlineSnapshot(`
Object {
"text": "hello anonymous",
}
`);
expect(
await app.client.query('hello', {
username: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
});
});
|
5,220 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/adapters/fetch.test.ts | /**
* @vitest-environment miniflare
*/
/// <reference types="@cloudflare/workers-types" />
import { Context, router } from './__router';
import { Response as MiniflareResponse } from '@miniflare/core';
import { createTRPCClient, httpBatchLink } from '@trpc/client/src';
import * as trpc from '@trpc/server/src';
import * as trpcFetch from '@trpc/server/src/adapters/fetch';
import { Miniflare } from 'miniflare';
// miniflare does an instanceof check
globalThis.Response = MiniflareResponse as any;
const port = 8787;
const url = `http://localhost:${port}`;
const createContext = ({
req,
}: trpcFetch.FetchCreateContextFnOptions): Context => {
const getUser = () => {
if (req.headers.get('authorization') === 'meow') {
return {
name: 'KATT',
};
}
return null;
};
return {
user: getUser(),
};
};
export async function handleRequest(request: Request): Promise<Response> {
return trpcFetch.fetchRequestHandler({
endpoint: '',
req: request,
router,
createContext,
});
}
async function startServer() {
const mf = new Miniflare({
script: '//',
port,
});
const globalScope = await mf.getGlobalScope();
globalScope.addEventListener('fetch', (event: FetchEvent) => {
event.respondWith(handleRequest(event.request));
});
const server = await mf.startServer();
const client = createTRPCClient<typeof router>({
links: [httpBatchLink({ url, fetch: fetch as any })],
});
return {
close: () =>
new Promise<void>((resolve, reject) =>
server.close((err) => {
err ? reject(err) : resolve();
}),
),
router,
client,
};
}
let t: trpc.inferAsyncReturnType<typeof startServer>;
beforeAll(async () => {
t = await startServer();
});
afterAll(async () => {
await t.close();
});
test('simple query', async () => {
expect(
await t.client.query('hello', {
who: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
expect(await t.client.query('hello')).toMatchInlineSnapshot(`
Object {
"text": "hello world",
}
`);
});
test('query with headers', async () => {
const client = createTRPCClient<typeof router>({
links: [
httpBatchLink({
url,
fetch: fetch as any,
headers: { authorization: 'meow' },
}),
],
});
expect(await client.query('hello')).toMatchInlineSnapshot(`
Object {
"text": "hello KATT",
}
`);
});
|
5,221 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/adapters/next.test.ts | import { EventEmitter } from 'events';
import * as trpc from '@trpc/server/src';
import * as trpcNext from '@trpc/server/src/adapters/next';
function mockReq({
query,
method = 'GET',
body,
}: {
query: Record<string, any>;
method?:
| 'CONNECT'
| 'DELETE'
| 'GET'
| 'HEAD'
| 'OPTIONS'
| 'POST'
| 'PUT'
| 'TRACE';
body?: unknown;
}) {
const req = new EventEmitter() as any;
req.method = method;
req.query = query;
req.headers = {};
const socket = {
destroy: vi.fn(),
};
req.socket = socket;
setTimeout(() => {
if (body) {
req.emit('data', JSON.stringify(body));
}
req.emit('end');
});
return { req, socket };
}
function mockRes() {
const res = new EventEmitter() as any;
const json = vi.fn(() => res);
const setHeader = vi.fn(() => res);
const end = vi.fn(() => res);
res.json = json;
res.setHeader = setHeader;
res.end = end;
return { res, json, setHeader, end };
}
test('bad setup', async () => {
const router = trpc
.router()
.query('hello', {
resolve: () => 'world',
})
.interop();
const handler = trpcNext.createNextApiHandler({
router,
});
const { req } = mockReq({ query: {} });
const { res, json } = mockRes();
await handler(req, res);
const responseJson: any = (json.mock.calls[0] as any)[0];
expect(responseJson.ok).toMatchInlineSnapshot(`undefined`);
expect(responseJson.error.message).toMatchInlineSnapshot(
`"Query \\"trpc\\" not found - is the file named \`[trpc]\`.ts or \`[...trpc].ts\`?"`,
);
expect(responseJson.statusCode).toMatchInlineSnapshot(`undefined`);
});
describe('ok request', () => {
const router = trpc
.router()
.query('hello', {
resolve: () => 'world',
})
.interop();
const handler = trpcNext.createNextApiHandler({
router,
});
test('[...trpc].ts', async () => {
const { req } = mockReq({
query: {
trpc: ['hello'],
},
});
const { res, end } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]);
expect(json).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "world",
},
}
`);
});
test('[trpc].ts', async () => {
const { req } = mockReq({
query: {
trpc: 'hello',
},
});
const { res, end } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]);
expect(json).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "world",
},
}
`);
});
});
test('404', async () => {
const router = trpc
.router()
.query('hello', {
resolve: () => 'world',
})
.interop();
const handler = trpcNext.createNextApiHandler({
router,
});
const { req } = mockReq({
query: {
trpc: ['not-found-path'],
},
});
const { res, end } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(404);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]);
expect(json.error.message).toMatchInlineSnapshot(
`"No \\"query\\"-procedure on path \\"not-found-path\\""`,
);
});
test('payload too large', async () => {
const router = trpc
.router()
.mutation('hello', {
resolve: () => 'world',
})
.interop();
const handler = trpcNext.createNextApiHandler({
router,
maxBodySize: 1,
});
const { req } = mockReq({
query: {
trpc: ['hello'],
},
method: 'POST',
body: '123456789',
});
const { res, end } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(413);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]);
expect(json.error.message).toMatchInlineSnapshot(`"PAYLOAD_TOO_LARGE"`);
});
test('HEAD request', async () => {
const router = trpc
.router()
.query('hello', {
resolve: () => 'world',
})
.interop();
const handler = trpcNext.createNextApiHandler({
router,
});
const { req } = mockReq({
query: {
trpc: [],
},
method: 'HEAD',
});
const { res } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(204);
});
test('PUT request (fails)', async () => {
const router = trpc
.router()
.query('hello', {
resolve: () => 'world',
})
.interop();
const handler = trpcNext.createNextApiHandler({
router,
});
const { req } = mockReq({
query: {
trpc: [],
},
method: 'PUT',
});
const { res } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(405);
});
|
5,223 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/dehydrate.test.tsx | import { createLegacyAppRouter } from './__testHelpers';
import { createSSGHelpers } from '@trpc/react-query/src/ssg';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
test('dehydrate', async () => {
const { db, appRouter } = factory;
const ssg = createSSGHelpers({ router: appRouter, ctx: {} });
await ssg.prefetchQuery('allPosts');
await ssg.fetchQuery('postById', '1');
const dehydrated = ssg.dehydrate().queries;
expect(dehydrated).toHaveLength(2);
const [cache, cache2] = dehydrated;
expect(cache!.queryHash).toMatchInlineSnapshot(
`"[[\\"allPosts\\"],{\\"type\\":\\"query\\"}]"`,
);
expect(cache!.queryKey).toMatchInlineSnapshot(`
Array [
Array [
"allPosts",
],
Object {
"type": "query",
},
]
`);
expect(cache!.state.data).toEqual(db.posts);
expect(cache2!.state.data).toMatchInlineSnapshot(`
Object {
"createdAt": 0,
"id": "1",
"title": "first post",
}
`);
});
|
5,224 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/formatError.test.tsx | import { createQueryClient } from '../../__queryClient';
import { createLegacyAppRouter } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import { DefaultErrorShape } from '@trpc/server/src/error/formatter';
import React, { useEffect, useState } from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
test('react types test', async () => {
const { trpc, client } = factory;
function MyComponent() {
const mutation = trpc.useMutation('addPost');
useEffect(() => {
mutation.mutate({ title: 123 as any });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (mutation.error?.shape) {
expectTypeOf(mutation.error.shape).toMatchTypeOf<
DefaultErrorShape & {
$test: string;
}
>();
expectTypeOf(mutation.error.shape).toMatchTypeOf<
DefaultErrorShape & {
$test: string;
}
>();
return (
<pre data-testid="err">
{JSON.stringify(mutation.error.shape.zodError, null, 2)}
</pre>
);
}
return <></>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('fieldErrors');
expect(utils.getByTestId('err').innerText).toMatchInlineSnapshot(
`undefined`,
);
});
});
|
5,225 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/infiniteQuery.test.tsx | import { createQueryClient } from '../../__queryClient';
import { createLegacyAppRouter, Post } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createSSGHelpers } from '@trpc/react-query/src/ssg';
import React, { Fragment, useState } from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('Infinite Query', () => {
test('useInfiniteQuery()', async () => {
const { trpc, client } = factory;
function MyComponent() {
const q = trpc.useInfiniteQuery(
[
'paginatedPosts',
{
limit: 1,
},
],
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
expectTypeOf(q.data?.pages[0]!.items).toMatchTypeOf<Post[] | undefined>();
return q.status === 'loading' ? (
<p>Loading...</p>
) : q.status === 'error' ? (
<p>Error: {q.error.message}</p>
) : (
<>
{q.data?.pages.map((group, i) => (
<Fragment key={i}>
{group.items.map((msg) => (
<Fragment key={msg.id}>
<div>{msg.title}</div>
</Fragment>
))}
</Fragment>
))}
<div>
<button
onClick={() => q.fetchNextPage()}
disabled={!q.hasNextPage || q.isFetchingNextPage}
data-testid="loadMore"
>
{q.isFetchingNextPage
? 'Loading more...'
: q.hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</div>
<div>
{q.isFetching && !q.isFetchingNextPage ? 'Fetching...' : null}
</div>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Load More');
});
await userEvent.click(utils.getByTestId('loadMore'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Loading more...');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Nothing more to load');
});
expect(utils.container).toMatchInlineSnapshot(`
<div>
<div>
first post
</div>
<div>
second post
</div>
<div>
<button
data-testid="loadMore"
disabled=""
>
Nothing more to load
</button>
</div>
<div />
</div>
`);
});
test('useInfiniteQuery and prefetchInfiniteQuery', async () => {
const { trpc, client } = factory;
function MyComponent() {
const trpcContext = trpc.useContext();
const q = trpc.useInfiniteQuery(
[
'paginatedPosts',
{
limit: 1,
},
],
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
expectTypeOf(q.data?.pages[0]?.items).toMatchTypeOf<Post[] | undefined>();
return q.status === 'loading' ? (
<p>Loading...</p>
) : q.status === 'error' ? (
<p>Error: {q.error.message}</p>
) : (
<>
{q.data?.pages.map((group, i) => (
<Fragment key={i}>
{group.items.map((msg) => (
<Fragment key={msg.id}>
<div>{msg.title}</div>
</Fragment>
))}
</Fragment>
))}
<div>
<button
onClick={() => q.fetchNextPage()}
disabled={!q.hasNextPage || q.isFetchingNextPage}
data-testid="loadMore"
>
{q.isFetchingNextPage
? 'Loading more...'
: q.hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</div>
<div>
<button
data-testid="prefetch"
onClick={() =>
trpcContext.prefetchInfiniteQuery([
'paginatedPosts',
{ limit: 1 },
])
}
>
Prefetch
</button>
</div>
<div>
{q.isFetching && !q.isFetchingNextPage ? 'Fetching...' : null}
</div>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Load More');
});
await userEvent.click(utils.getByTestId('loadMore'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Loading more...');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Nothing more to load');
});
expect(utils.container).toMatchInlineSnapshot(`
<div>
<div>
first post
</div>
<div>
second post
</div>
<div>
<button
data-testid="loadMore"
disabled=""
>
Nothing more to load
</button>
</div>
<div>
<button
data-testid="prefetch"
>
Prefetch
</button>
</div>
<div />
</div>
`);
await userEvent.click(utils.getByTestId('prefetch'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Fetching...');
});
await waitFor(() => {
expect(utils.container).not.toHaveTextContent('Fetching...');
});
// It should correctly fetch both pages
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
test('useInfiniteQuery and fetchInfiniteQuery', async () => {
const { trpc, client } = factory;
function MyComponent() {
const trpcContext = trpc.useContext();
const q = trpc.useInfiniteQuery(
[
'paginatedPosts',
{
limit: 1,
},
],
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
expectTypeOf(q.data?.pages[0]?.items).toMatchTypeOf<Post[] | undefined>();
return q.status === 'loading' ? (
<p>Loading...</p>
) : q.status === 'error' ? (
<p>Error: {q.error.message}</p>
) : (
<>
{q.data?.pages.map((group, i) => (
<Fragment key={i}>
{group.items.map((msg) => (
<Fragment key={msg.id}>
<div>{msg.title}</div>
</Fragment>
))}
</Fragment>
))}
<div>
<button
onClick={() => q.fetchNextPage()}
disabled={!q.hasNextPage || q.isFetchingNextPage}
data-testid="loadMore"
>
{q.isFetchingNextPage
? 'Loading more...'
: q.hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</div>
<div>
<button
data-testid="fetch"
onClick={() =>
trpcContext.fetchInfiniteQuery(['paginatedPosts', { limit: 1 }])
}
>
Fetch
</button>
</div>
<div>
{q.isFetching && !q.isFetchingNextPage ? 'Fetching...' : null}
</div>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Load More');
});
await userEvent.click(utils.getByTestId('loadMore'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Loading more...');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Nothing more to load');
});
expect(utils.container).toMatchInlineSnapshot(`
<div>
<div>
first post
</div>
<div>
second post
</div>
<div>
<button
data-testid="loadMore"
disabled=""
>
Nothing more to load
</button>
</div>
<div>
<button
data-testid="fetch"
>
Fetch
</button>
</div>
<div />
</div>
`);
await userEvent.click(utils.getByTestId('fetch'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Fetching...');
});
await waitFor(() => {
expect(utils.container).not.toHaveTextContent('Fetching...');
});
// It should correctly fetch both pages
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
test('prefetchInfiniteQuery()', async () => {
const { appRouter } = factory;
const ssg = createSSGHelpers({ router: appRouter, ctx: {} });
{
await ssg.prefetchInfiniteQuery('paginatedPosts', { limit: 1 });
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('first post');
expect(data).not.toContain('second post');
}
{
await ssg.fetchInfiniteQuery('paginatedPosts', { limit: 2 });
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('first post');
expect(data).toContain('second post');
}
});
});
|
5,226 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/invalidateQueries.test.tsx | import { createQueryClient } from '../../__queryClient';
import { createLegacyAppRouter } from './__testHelpers';
import { QueryClientProvider, useQueryClient } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React, { useState } from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('invalidateQueries()', () => {
test('queryClient.invalidateQueries()', async () => {
const { trpc, resolvers, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.useQuery(['allPosts'], {
staleTime: Infinity,
});
const postByIdQuery = trpc.useQuery(['postById', '1'], {
staleTime: Infinity,
});
const queryClient = useQueryClient();
return (
<>
<pre>
allPostsQuery:{allPostsQuery.status} allPostsQuery:
{allPostsQuery.isStale ? 'stale' : 'not-stale'}{' '}
</pre>
<pre>
postByIdQuery:{postByIdQuery.status} postByIdQuery:
{postByIdQuery.isStale ? 'stale' : 'not-stale'}
</pre>
<button
data-testid="refetch"
onClick={() => {
queryClient.invalidateQueries([['allPosts']]);
queryClient.invalidateQueries([['postById']]);
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:success');
expect(utils.container).toHaveTextContent('allPostsQuery:success');
expect(utils.container).toHaveTextContent('postByIdQuery:not-stale');
expect(utils.container).toHaveTextContent('allPostsQuery:not-stale');
});
expect(resolvers.allPosts).toHaveBeenCalledTimes(1);
expect(resolvers.postById).toHaveBeenCalledTimes(1);
await userEvent.click(utils.getByTestId('refetch'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:stale');
expect(utils.container).toHaveTextContent('allPostsQuery:stale');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:not-stale');
expect(utils.container).toHaveTextContent('allPostsQuery:not-stale');
});
expect(resolvers.allPosts).toHaveBeenCalledTimes(2);
expect(resolvers.postById).toHaveBeenCalledTimes(2);
});
test('invalidateQueries()', async () => {
const { trpc, resolvers, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.useQuery(['allPosts'], {
staleTime: Infinity,
});
const postByIdQuery = trpc.useQuery(['postById', '1'], {
staleTime: Infinity,
});
const utils = trpc.useContext();
return (
<>
<pre>
allPostsQuery:{allPostsQuery.status} allPostsQuery:
{allPostsQuery.isStale ? 'stale' : 'not-stale'}{' '}
</pre>
<pre>
postByIdQuery:{postByIdQuery.status} postByIdQuery:
{postByIdQuery.isStale ? 'stale' : 'not-stale'}
</pre>
<button
data-testid="refetch"
onClick={() => {
utils.invalidateQueries(['allPosts']);
utils.invalidateQueries(['postById', '1']);
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:success');
expect(utils.container).toHaveTextContent('allPostsQuery:success');
expect(utils.container).toHaveTextContent('postByIdQuery:not-stale');
expect(utils.container).toHaveTextContent('allPostsQuery:not-stale');
});
expect(resolvers.allPosts).toHaveBeenCalledTimes(1);
expect(resolvers.postById).toHaveBeenCalledTimes(1);
await userEvent.click(utils.getByTestId('refetch'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:stale');
expect(utils.container).toHaveTextContent('allPostsQuery:stale');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:not-stale');
expect(utils.container).toHaveTextContent('allPostsQuery:not-stale');
});
expect(resolvers.allPosts).toHaveBeenCalledTimes(2);
expect(resolvers.postById).toHaveBeenCalledTimes(2);
});
test('test invalidateQueries() with different args - flaky', async () => {
// ref https://github.com/trpc/trpc/issues/1383
const { trpc, client } = factory;
function MyComponent() {
const countQuery = trpc.useQuery(['count', 'test'], {
staleTime: Infinity,
});
const utils = trpc.useContext();
return (
<>
<pre>count:{countQuery.data}</pre>
<button
data-testid="invalidate-1-string"
onClick={() => {
utils.invalidateQueries('count');
}}
/>
<button
data-testid="invalidate-2-tuple"
onClick={() => {
utils.invalidateQueries(['count']);
}}
/>
<button
data-testid="invalidate-3-exact"
onClick={() => {
utils.invalidateQueries(['count', 'test']);
}}
/>
<button
data-testid="invalidate-4-all"
onClick={() => {
utils.invalidateQueries();
}}
/>{' '}
<button
data-testid="invalidate-5-predicate"
onClick={() => {
utils.invalidateQueries(undefined, {
predicate(opts) {
const { queryKey } = opts;
const [path, rest] = queryKey;
return (
JSON.stringify(path) === JSON.stringify(['count']) &&
(rest as any)?.input === 'test'
);
},
});
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('count:test:1');
});
let count = 1;
for (const testId of [
'invalidate-1-string',
'invalidate-2-tuple',
'invalidate-3-exact',
'invalidate-4-all',
'invalidate-5-predicate',
]) {
count++;
// click button to invalidate
await userEvent.click(utils.getByTestId(testId));
// should become stale straight after the click
await waitFor(() => {
expect(utils.container).toHaveTextContent(`count:test:${count}`);
});
}
});
});
|
5,227 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/prefetchQuery.test.tsx | import { createQueryClient } from '../../__queryClient';
import { createLegacyAppRouter } from './__testHelpers';
import {
dehydrate,
QueryClientProvider,
useQueryClient,
} from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import React, { useEffect, useState } from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('prefetchQuery()', () => {
test('with input', async () => {
const { trpc, client } = factory;
function MyComponent() {
const [state, setState] = useState<string>('nope');
const utils = trpc.useContext();
const queryClient = useQueryClient();
useEffect(() => {
async function prefetch() {
await utils.prefetchQuery(['postById', '1']);
setState(JSON.stringify(dehydrate(queryClient)));
}
prefetch();
}, [queryClient, utils]);
return <>{JSON.stringify(state)}</>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
});
|
5,228 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/setInfiniteQueryData.test.tsx | import { createQueryClient } from '../../__queryClient';
import { createLegacyAppRouter } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React, { useState } from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('setInfiniteQueryData()', () => {
test('with & without callback', async () => {
const { trpc, client } = factory;
function MyComponent() {
const utils = trpc.useContext();
const allPostsQuery = trpc.useInfiniteQuery(['paginatedPosts', {}], {
enabled: false,
getNextPageParam: (next) => next.nextCursor,
});
return (
<>
<pre>
{JSON.stringify(
allPostsQuery.data?.pages.map((p) => p.items) ?? null,
null,
4,
)}
</pre>
<button
data-testid="setInfiniteQueryData"
onClick={async () => {
// Add a new post to the first page (without callback)
utils.setInfiniteQueryData(['paginatedPosts', {}], {
pages: [
{
items: [
{
id: 'id',
title: 'infinitePosts.title1',
createdAt: Date.now(),
},
],
nextCursor: null,
},
],
pageParams: [],
});
const newPost = {
id: 'id',
title: 'infinitePosts.title2',
createdAt: Date.now(),
};
// Add a new post to the first page (with callback)
utils.setInfiniteQueryData(['paginatedPosts', {}], (data) => {
expect(data).not.toBe(undefined);
if (!data) {
return {
pages: [],
pageParams: [],
};
}
return {
...data,
pages: data.pages.map((page) => {
return {
...page,
items: [...page.items, newPost],
};
}),
};
});
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await userEvent.click(utils.getByTestId('setInfiniteQueryData'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('infinitePosts.title1');
expect(utils.container).toHaveTextContent('infinitePosts.title2');
});
});
});
|
5,229 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/setQueryData.test.tsx | import { createQueryClient } from '../../__queryClient';
import { createLegacyAppRouter } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React, { useState } from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('setQueryData()', () => {
test('without & without callback', async () => {
const { trpc, client } = factory;
function MyComponent() {
const utils = trpc.useContext();
const allPostsQuery = trpc.useQuery(['allPosts'], {
enabled: false,
});
const postByIdQuery = trpc.useQuery(['postById', '1'], {
enabled: false,
});
return (
<>
<pre>{JSON.stringify(allPostsQuery.data ?? null, null, 4)}</pre>
<pre>{JSON.stringify(postByIdQuery.data ?? null, null, 4)}</pre>
<button
data-testid="setQueryData"
onClick={async () => {
utils.setQueryData(
['allPosts'],
[
{
id: 'id',
title: 'allPost.title',
createdAt: Date.now(),
},
],
);
const newPost = {
id: 'id',
title: 'postById.tmp.title',
createdAt: Date.now(),
};
utils.setQueryData(['postById', '1'], (data) => {
expect(data).toBe(undefined);
return newPost;
});
// now it should be set
utils.setQueryData(['postById', '1'], (data) => {
expect(data).toEqual(newPost);
if (!data) {
return newPost;
}
return {
...data,
title: 'postById.title',
};
});
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await userEvent.click(utils.getByTestId('setQueryData'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('allPost.title');
expect(utils.container).toHaveTextContent('postById.title');
});
});
});
|
5,230 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/useMutation.test.tsx | /* eslint-disable @typescript-eslint/ban-ts-comment */
import { createQueryClient } from '../../__queryClient';
import { createLegacyAppRouter } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import React, { useEffect, useState } from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('useMutation()', () => {
test('call procedure with no input with null/undefined', async () => {
const { trpc, client } = factory;
const results: unknown[] = [];
function MyComponent() {
const mutation = trpc.useMutation('PING');
const [finished, setFinished] = useState(false);
useEffect(() => {
(async () => {
await new Promise((resolve) => {
mutation.mutate(undefined, {
onSettled: resolve,
});
});
await new Promise((resolve) => {
mutation.mutate(undefined, {
onSettled: resolve,
});
});
// @ts-expect-error
await mutation.mutateAsync(null);
await mutation.mutateAsync(undefined);
setFinished(true);
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
results.push(mutation.data);
}, [mutation.data]);
return (
<pre>
{JSON.stringify(mutation.data ?? {}, null, 4)}
{finished && '__IS_FINISHED__'}
</pre>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('__IS_FINISHED__');
});
// expect(results).toMatchInlineSnapshot();
});
test('nullish input called with no input', async () => {
const { trpc, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.useQuery(['allPosts']);
const deletePostsMutation = trpc.useMutation('deletePosts');
useEffect(() => {
allPostsQuery.refetch().then(async (allPosts) => {
expect(allPosts.data).toHaveLength(2);
await deletePostsMutation.mutateAsync();
const newAllPost = await allPostsQuery.refetch();
expect(newAllPost.data).toHaveLength(0);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <pre>{JSON.stringify(allPostsQuery.data ?? {}, null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('[]');
});
});
test('useMutation([path]) tuple', async () => {
const { trpc, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.useQuery(['allPosts']);
const deletePostsMutation = trpc.useMutation(['deletePosts']);
useEffect(() => {
allPostsQuery.refetch().then(async (allPosts) => {
expect(allPosts.data).toHaveLength(2);
await deletePostsMutation.mutateAsync();
const newAllPost = await allPostsQuery.refetch();
expect(newAllPost.data).toHaveLength(0);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <pre>{JSON.stringify(allPostsQuery.data ?? {}, null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('[]');
});
});
test('nullish input called with input', async () => {
const { trpc, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.useQuery(['allPosts']);
const deletePostsMutation = trpc.useMutation('deletePosts');
useEffect(() => {
allPostsQuery.refetch().then(async (allPosts) => {
expect(allPosts.data).toHaveLength(2);
await deletePostsMutation.mutateAsync(['1']);
const newAllPost = await allPostsQuery.refetch();
expect(newAllPost.data).toHaveLength(1);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <pre>{JSON.stringify(allPostsQuery.data ?? {}, null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
await waitFor(() => {
expect(utils.container).not.toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
});
test('useMutation with context', async () => {
const { trpc, App, linkSpy } = factory;
function MyComponent() {
const deletePostsMutation = trpc.useMutation(['deletePosts'], {
trpc: {
context: { test: '1' },
},
});
useEffect(() => {
deletePostsMutation.mutate();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <pre>{deletePostsMutation.isSuccess && '___FINISHED___'}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('___FINISHED___');
});
expect(linkSpy.up).toHaveBeenCalledTimes(1);
expect(linkSpy.up.mock.calls[0]![0]!.context).toMatchObject({
test: '1',
});
});
test('useMutation with mutation context', async () => {
const { trpc, client } = factory;
function MyComponent() {
trpc.useMutation(['deletePosts'], {
onMutate: () => 'foo' as const,
onSuccess: (_data, _variables, context) => {
expectTypeOf(context).toMatchTypeOf<'foo' | undefined>();
},
onError: (_error, _variables, context) => {
expectTypeOf(context).toMatchTypeOf<'foo' | undefined>();
},
// eslint-disable-next-line max-params
onSettled: (_data, _error, _variables, context) => {
expectTypeOf(context).toMatchTypeOf<'foo' | undefined>();
},
});
return null;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
render(<App />);
});
});
|
5,231 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/useQuery.test.tsx | import { createQueryClient } from '../../__queryClient';
import { createLegacyAppRouter, Post } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import React, { useState } from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('useQuery()', () => {
test('no input', async () => {
const { trpc, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.useQuery(['allPosts']);
expectTypeOf(allPostsQuery.data!).toMatchTypeOf<Post[]>();
return <pre>{JSON.stringify(allPostsQuery.data ?? 'n/a', null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
test('with operation context', async () => {
const { trpc, client, linkSpy } = factory;
function MyComponent() {
const allPostsQuery = trpc.useQuery(['allPosts'], {
trpc: {
context: { test: '1' },
},
});
expectTypeOf(allPostsQuery.data!).toMatchTypeOf<Post[]>();
return <pre>{JSON.stringify(allPostsQuery.data ?? 'n/a', null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
expect(linkSpy.up).toHaveBeenCalledTimes(1);
expect(linkSpy.up.mock.calls[0]![0]!.context).toMatchObject({
test: '1',
});
});
test('with input', async () => {
const { trpc, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.useQuery(['paginatedPosts', { limit: 1 }]);
return <pre>{JSON.stringify(allPostsQuery.data ?? 'n/a', null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
expect(utils.container).not.toHaveTextContent('second post');
});
test('select fn', async () => {
const { trpc, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.useQuery(['paginatedPosts', { limit: 1 }], {
select: () => ({
hello: 'world' as const,
}),
});
expectTypeOf(allPostsQuery.data!).toMatchTypeOf<{ hello: 'world' }>();
return <pre>{JSON.stringify(allPostsQuery.data ?? 'n/a', null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('"hello": "world"');
});
});
});
|
5,232 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/useSubscription.test.tsx | import { createQueryClient } from '../../__queryClient';
import { createLegacyAppRouter, Post } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import React, { useEffect, useState } from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('useSubscription', () => {
test('mutation on mount + subscribe for it', async () => {
const { trpc, client } = factory;
function MyComponent() {
const [posts, setPosts] = useState<Post[]>([]);
const addPosts = (newPosts?: Post[]) => {
setPosts((nowPosts) => {
const map: Record<Post['id'], Post> = {};
for (const msg of nowPosts ?? []) {
map[msg.id] = msg;
}
for (const msg of newPosts ?? []) {
map[msg.id] = msg;
}
return Object.values(map);
});
};
const input = posts.reduce(
(num, post) => Math.max(num, post.createdAt),
-1,
);
trpc.useSubscription(['newPosts', input], {
onData(post) {
addPosts([post]);
},
});
const mutation = trpc.useMutation('addPost');
const mutate = mutation.mutate;
useEffect(() => {
if (posts.length === 2) {
mutate({ title: 'third post' });
}
}, [posts.length, mutate]);
return <pre>{JSON.stringify(posts, null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('third post');
});
});
});
|
5,233 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/react/withTRPC.test.tsx | /* eslint-disable @typescript-eslint/ban-ts-comment */
import { createLegacyAppRouter } from './__testHelpers';
import { render, waitFor } from '@testing-library/react';
import { withTRPC } from '@trpc/next/src';
import { AppType } from 'next/dist/shared/lib/utils';
import React from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('withTRPC()', () => {
test('useQuery', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query = trpc.useQuery(['allPosts']);
return <>{JSON.stringify(query.data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).toHaveTextContent('first post');
});
test('useInfiniteQuery', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query = trpc.useInfiniteQuery(
[
'paginatedPosts',
{
limit: 10,
},
],
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
return <>{JSON.stringify(query.data ?? query.error)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).toHaveTextContent('first post');
});
test('browser render', async () => {
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query = trpc.useQuery(['allPosts']);
return <>{JSON.stringify(query.data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
const utils = render(<Wrapped {...props} />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
describe('`ssr: false` on query', () => {
test('useQuery()', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query = trpc.useQuery(['allPosts'], {
trpc: { ssr: false },
});
return <>{JSON.stringify(query.data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).not.toHaveTextContent('first post');
// should eventually be fetched
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
test('useInfiniteQuery', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query = trpc.useInfiniteQuery(
[
'paginatedPosts',
{
limit: 10,
},
],
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
trpc: {
ssr: false,
},
},
);
return <>{JSON.stringify(query.data ?? query.error)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).not.toHaveTextContent('first post');
// should eventually be fetched
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
});
test('useQuery - ssr batching', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions, createContext } = factory;
const App: AppType = () => {
const query1 = trpc.useQuery(['postById', '1']);
const query2 = trpc.useQuery(['postById', '2']);
return <>{JSON.stringify([query1.data, query2.data])}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
// confirm we've batched if createContext has only been called once
expect(createContext).toHaveBeenCalledTimes(1);
});
describe('`enabled: false` on query during ssr', () => {
describe('useQuery', () => {
test('queryKey does not change', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query1 = trpc.useQuery(['postById', '1']);
// query2 depends only on query1 status
const query2 = trpc.useQuery(['postById', '2'], {
enabled: query1.status === 'success',
});
return (
<>
<>{JSON.stringify(query1.data)}</>
<>{JSON.stringify(query2.data)}</>
</>
);
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
// when queryKey does not change query2 only fetched in the browser
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
});
test('queryKey changes', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query1 = trpc.useQuery(['postById', '1']);
// query2 depends on data fetched by query1
const query2 = trpc.useQuery(
[
'postById',
// workaround of TS requiring a string param
query1.data
? (parseInt(query1.data.id) + 1).toString()
: 'definitely not a post id',
],
{
enabled: !!query1.data,
},
);
return (
<>
<>{JSON.stringify(query1.data)}</>
<>{JSON.stringify(query2.data)}</>
</>
);
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
// when queryKey changes both queries are fetched on the server
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
});
});
describe('useInfiniteQuery', () => {
test('queryKey does not change', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query1 = trpc.useInfiniteQuery(
['paginatedPosts', { limit: 1 }],
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
// query2 depends only on query1 status
const query2 = trpc.useInfiniteQuery(
['paginatedPosts', { limit: 2 }],
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: query1.status === 'success',
},
);
return (
<>
<>{JSON.stringify(query1.data)}</>
<>{JSON.stringify(query2.data)}</>
</>
);
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
// when queryKey does not change query2 only fetched in the browser
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
});
test('queryKey changes', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query1 = trpc.useInfiniteQuery(
['paginatedPosts', { limit: 1 }],
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
// query2 depends on data fetched by query1
const query2 = trpc.useInfiniteQuery(
[
'paginatedPosts',
{ limit: query1.data ? query1.data.pageParams.length + 1 : 0 },
],
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: query1.status === 'success',
},
);
return (
<>
<>{JSON.stringify(query1.data)}</>
<>{JSON.stringify(query2.data)}</>
</>
);
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
// when queryKey changes both queries are fetched on the server
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
});
});
});
});
|
5,234 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop/react | petrpan-code/trpc/trpc/packages/tests/server/interop/react/regression/issue-1645-setErrorStatusSSR.test.tsx | /* eslint-disable @typescript-eslint/ban-ts-comment */
import { createLegacyAppRouter } from '../__testHelpers';
import { withTRPC } from '@trpc/next/src';
import { AppType } from 'next/dist/shared/lib/utils';
import React from 'react';
let factory: ReturnType<typeof createLegacyAppRouter>;
beforeEach(() => {
factory = createLegacyAppRouter();
});
afterEach(async () => {
await factory.close();
});
/**
* @link https://github.com/trpc/trpc/pull/1645
*/
test('regression: SSR with error sets `status`=`error`', async () => {
// @ts-ignore
const { window } = global;
let queryState: any;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
const query1 = trpc.useQuery(['bad-useQuery'] as any);
const query2 = trpc.useInfiniteQuery(['bad-useInfiniteQuery'] as any);
queryState = {
query1: {
status: query1.status,
error: query1.error,
},
query2: {
status: query2.status,
error: query2.error,
},
};
return <>{JSON.stringify(query1.data ?? null)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
// @ts-ignore
global.window = window;
expect(queryState.query1.error).toMatchInlineSnapshot(
`[TRPCClientError: No "query"-procedure on path "bad-useQuery"]`,
);
expect(queryState.query2.error).toMatchInlineSnapshot(
`[TRPCClientError: No "query"-procedure on path "bad-useInfiniteQuery"]`,
);
expect(queryState.query1.status).toBe('error');
expect(queryState.query2.status).toBe('error');
});
|
5,235 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/regression/issue-3303-transformer.test.ts | import { routerToServerAndClientNew } from '../../___testHelpers';
import { httpBatchLink } from '@trpc/react-query/src';
import * as interop from '@trpc/server/src';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import superjson from 'superjson';
type Context = {
foo: 'bar';
};
describe('transformer on legacy router', () => {
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.context<Context>().create();
const legacyRouter = interop
.router<Context>()
.transformer(superjson)
.query('oldQuery', {
resolve() {
return {
date: new Date(),
};
},
})
.mutation('oldMutation', {
resolve() {
return {
date: new Date(),
};
},
});
const newAppRouter = t.router({
newProcedure: t.procedure.query(() => {
date: new Date();
}),
});
const appRouter = t.mergeRouters(legacyRouter.interop(), newAppRouter);
const opts = routerToServerAndClientNew(appRouter, {
server: {
createContext() {
return {
foo: 'bar',
};
},
},
client({ httpUrl }) {
return {
transformer: superjson,
links: [
httpBatchLink({
url: httpUrl,
}),
],
};
},
});
return {
...opts,
appRouter,
};
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('call old', async () => {
{
const res = await ctx.client.query('oldQuery');
expectTypeOf(res.date).toEqualTypeOf<Date>();
}
{
const res = await ctx.client.mutation('oldMutation');
expectTypeOf(res.date).toEqualTypeOf<Date>();
}
});
});
|
5,236 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/regression/issue-949-inferProcedureInput.test.ts | /* eslint-disable @typescript-eslint/ban-types */
// IMPORTANT:
// needs to be imported from compiled output otherwise we get a false-positive
import * as trpc from '@trpc/server';
import { z } from 'zod';
// https://github.com/trpc/trpc/issues/949
// https://github.com/trpc/trpc/pull/955
test('inferProcedureFromInput regression', async () => {
type Context = {};
const appRouter = trpc
.router<Context>()
.merge(
'admin.',
trpc
.router<Context>()
.mutation('testMutation', {
input: z.object({
in: z.string(),
}),
resolve: async () => `out` as const,
})
.query('hello', {
input: z.object({
in: z.string(),
}),
resolve() {
return 'out' as const;
},
})
.query('noInput', {
resolve: async () => 'out' as const,
})
.middleware(async ({ next, ctx }) =>
next({
ctx: {
...ctx,
_test: '1',
},
}),
)
.query('hello-2', {
input: z.object({
in: z.string(),
}),
resolve() {
return 'out' as const;
},
}),
)
.interop();
type Mutations = typeof appRouter._def.mutations;
type Queries = typeof appRouter._def.queries;
expectTypeOf<
trpc.inferProcedureInput<Queries['admin.hello']>
>().toEqualTypeOf<{
in: string;
}>();
expectTypeOf<
trpc.inferProcedureInput<Queries['admin.noInput']>
>().toEqualTypeOf<undefined | void>();
expectTypeOf<
trpc.inferProcedureOutput<Queries['admin.noInput']>
>().toEqualTypeOf<'out'>();
expectTypeOf<
trpc.inferProcedureInput<Queries['admin.hello-2']>
>().toEqualTypeOf<{
in: string;
}>();
expectTypeOf<
trpc.inferProcedureInput<Mutations['admin.testMutation']>
>().toEqualTypeOf<{ in: string }>();
expectTypeOf<
trpc.inferProcedureInput<Mutations['admin.testMutation']>
>().not.toBeUnknown();
});
|
5,237 | 0 | petrpan-code/trpc/trpc/packages/tests/server/interop | petrpan-code/trpc/trpc/packages/tests/server/interop/regression/issue-990-initialData.test.tsx | import { legacyRouterToServerAndClient } from '../__legacyRouterToServerAndClient';
import { createQueryClient } from '../../__queryClient';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import * as trpcReact from '@trpc/react-query/src';
import * as trpcServer from '@trpc/server/src';
import React, { useState } from 'react';
test('initialData type', async () => {
const { client, router, close } = legacyRouterToServerAndClient(
trpcServer.router().query('hello', {
resolve() {
return {
text: 'world',
};
},
}),
);
const trpc = trpcReact.createReactQueryHooks<typeof router>();
function MyComponent() {
const query = trpc.useQuery(['hello'], {
initialData: {
text: 'alexdotjs',
},
enabled: false,
});
return <pre>{JSON.stringify(query.data ?? 'n/a', null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('alexdotjs');
});
await close();
});
|
5,240 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/abortOnUnmount.test.tsx | import { routerToServerAndClientNew } from '../___testHelpers';
import { createQueryClient } from '../__queryClient';
import { QueryClientProvider, useIsFetching } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { httpBatchLink } from '@trpc/client';
import { createTRPCReact } from '@trpc/react-query';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
import React, { ReactNode, useState } from 'react';
import { z } from 'zod';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
greeting: t.procedure.input(z.string()).query(async (opts) => {
await new Promise((r) => setTimeout(r, 2000));
return { text: 'Hello' + opts.input };
}),
});
function MyComponent() {
const [query, setQuery] = useState(1);
const x = useIsFetching();
return (
<div>
<button
data-testid="setQ1"
onClick={() => {
setQuery(1);
}}
/>
<button
data-testid="setQ2"
onClick={() => {
setQuery(2);
}}
/>
{query === 1 && <Query1 />}
{query === 2 && <Query2 />}
<div>isFetching: {x}</div>
</div>
);
}
function AnotherComponent() {
const [query, setQuery] = useState(1);
const x = useIsFetching();
return (
<div>
<button
data-testid="setQ1"
onClick={() => {
setQuery(1);
}}
/>
<button
data-testid="setQ2"
onClick={() => {
setQuery(2);
}}
/>
{query === 1 && <Query3 />}
{query === 2 && <Query4 />}
<div>isFetching: {x}</div>
</div>
);
}
function Query1() {
const query =
proxyWithAbortOnUnmount.greeting.useQuery('tRPC greeting 1');
return <div>{query.data?.text ?? 'Loading 1'}</div>;
}
function Query2() {
const query =
proxyWithAbortOnUnmount.greeting.useQuery('tRPC greeting 2');
return <div>{query.data?.text ?? 'Loading 2'}</div>;
}
function Query3() {
const query = proxy.greeting.useQuery('tRPC greeting 1');
return <div>{query.data?.text ?? 'Loading 1'}</div>;
}
function Query4() {
const query = proxy.greeting.useQuery('tRPC greeting 2');
return <div>{query.data?.text ?? 'Loading 2'}</div>;
}
const queryClient = createQueryClient();
const proxyWithAbortOnUnmount = createTRPCReact<typeof appRouter>({
abortOnUnmount: true,
});
const proxy = createTRPCReact<typeof appRouter>();
const opts = routerToServerAndClientNew(appRouter);
return {
...opts,
proxy,
proxyWithAbortOnUnmount,
queryClient,
AnotherComponent,
MyComponent,
};
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('abortOnUnmount', async () => {
const { proxyWithAbortOnUnmount, httpUrl, queryClient, MyComponent } = ctx;
function App(props: { children: ReactNode }) {
const [client] = useState(() =>
proxyWithAbortOnUnmount.createClient({
links: [
httpBatchLink({
url: httpUrl,
}),
],
}),
);
return (
<proxyWithAbortOnUnmount.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</proxyWithAbortOnUnmount.Provider>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByText('Loading 1')).toBeInTheDocument();
expect(utils.getByText('isFetching: 1')).toBeInTheDocument();
});
await userEvent.click(utils.getByTestId('setQ2'));
expect(utils.getByText('Loading 2')).toBeInTheDocument();
// query1 should not finish so isFetching should be 1
expect(utils.getByText('isFetching: 1')).toBeInTheDocument();
});
test('abortOnUnmount false', async () => {
const { proxy, httpUrl, queryClient, AnotherComponent } = ctx;
function App(props: { children: ReactNode }) {
const [client] = useState(() =>
proxy.createClient({
links: [
httpBatchLink({
url: httpUrl,
}),
],
}),
);
return (
<proxy.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</proxy.Provider>
);
}
const utils = render(
<App>
<AnotherComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByText('Loading 1')).toBeInTheDocument();
expect(utils.getByText('isFetching: 1')).toBeInTheDocument();
});
await userEvent.click(utils.getByTestId('setQ2'));
expect(utils.getByText('Loading 2')).toBeInTheDocument();
// query1 should finish so isFetching should be 2
expect(utils.getByText('isFetching: 2')).toBeInTheDocument();
});
|
5,241 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/bigBoi.test.tsx | import { appRouter } from '../__generated__/bigBoi/_app';
import { getServerAndReactClient } from './__reactHelpers';
import { render, waitFor } from '@testing-library/react';
import { konn } from 'konn';
import React from 'react';
const ctx = konn()
.beforeEach(() => {
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('vanilla', async () => {
const { opts } = ctx;
const { proxy } = opts;
{
const result = await proxy.r0.greeting.query({ who: 'KATT' });
expect(result).toBe('hello KATT');
expectTypeOf(result).not.toBeAny();
expectTypeOf(result).toMatchTypeOf<string>();
}
{
const result = await proxy.r10.grandchild.grandChildMutation.mutate();
expect(result).toBe('grandChildMutation');
}
{
const result = await proxy.r499.greeting.query({ who: 'KATT' });
expect(result).toBe('hello KATT');
expectTypeOf(result).not.toBeAny();
expectTypeOf(result).toMatchTypeOf<string>();
}
});
test('useQuery()', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const query1 = proxy.r499.greeting.useQuery({ who: 'KATT' });
if (!query1.data) {
return <>...</>;
}
expectTypeOf(query1.data).not.toBeAny();
expectTypeOf(query1.data).toMatchTypeOf<string>();
return <pre>{JSON.stringify(query1.data ?? 'n/a', null, 4)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`hello KATT`);
});
});
|
5,242 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/createClient.test.tsx | import { routerToServerAndClientNew } from '../___testHelpers';
import { createQueryClient } from '../__queryClient';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import { createServerSideHelpers } from '@trpc/react-query/server';
import { createTRPCReact, httpBatchLink } from '@trpc/react-query/src';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React, { ReactNode, useState } from 'react';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
hello: t.procedure.query(() => 'world'),
});
const queryClient = createQueryClient();
const hooks = createTRPCReact<typeof appRouter>();
const opts = routerToServerAndClientNew(appRouter);
function App(props: { children: ReactNode }) {
const [client] = useState(() =>
hooks.createClient({
links: [
httpBatchLink({
url: opts.httpUrl,
}),
],
}),
);
return (
<hooks.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</hooks.Provider>
);
}
return { ...opts, hooks, App };
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('createClient()', async () => {
const { App, hooks } = ctx;
function MyComponent() {
const query1 = hooks.hello.useQuery();
if (!query1.data) {
return <>...</>;
}
return <pre>{query1.data}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('world');
});
});
test('useDehydratedState() - internal', async () => {
const { App, hooks, router } = ctx;
const ssg = createServerSideHelpers({ router, ctx: {} });
const res = await ssg.hello.fetch();
expect(res).toBe('world');
const dehydratedState = ssg.dehydrate();
function MyComponent() {
const utils = hooks.useUtils();
const state = hooks.useDehydratedState(utils.client, dehydratedState);
return <h1>{JSON.stringify(state)}</h1>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('world');
});
});
test('useDehydratedState() - external', async () => {
const { App, hooks, proxy } = ctx;
const ssg = createServerSideHelpers({ client: proxy });
const res = await ssg.hello.fetch();
expect(res).toBe('world');
expectTypeOf(res).toMatchTypeOf<string>();
const dehydratedState = ssg.dehydrate();
function MyComponent() {
const utils = hooks.useUtils();
const state = hooks.useDehydratedState(utils.client, dehydratedState);
return <h1>{JSON.stringify(state)}</h1>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('world');
});
});
|
5,243 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/dehydrate.test.tsx | import { createAppRouter } from './__testHelpers';
import { createProxySSGHelpers } from '@trpc/react-query/src/ssg';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
test('dehydrate', async () => {
const { db, appRouter } = factory;
const ssg = createProxySSGHelpers({ router: appRouter, ctx: {} });
await ssg.allPosts.prefetch();
await ssg.postById.prefetch('1');
const dehydrated = ssg.dehydrate().queries;
expect(dehydrated).toHaveLength(2);
const [cache, cache2] = dehydrated;
expect(cache!.queryHash).toMatchInlineSnapshot(
`"[[\\"allPosts\\"],{\\"type\\":\\"query\\"}]"`,
);
expect(cache!.queryKey).toMatchInlineSnapshot(`
Array [
Array [
"allPosts",
],
Object {
"type": "query",
},
]
`);
expect(cache!.state.data).toEqual(db.posts);
expect(cache2!.state.data).toMatchInlineSnapshot(`
Object {
"createdAt": 0,
"id": "1",
"title": "first post",
}
`);
});
|
5,244 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/ensureQueryData.test.tsx | import { createQueryClient } from '../__queryClient';
import { createAppRouter } from './__testHelpers';
import { QueryClientProvider, useQueryClient } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import React, { useEffect, useState } from 'react';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('ensureQueryData()', () => {
test('with input', async () => {
const { trpc, client } = factory;
function MyComponent() {
const [state, setState] = useState<string>('nope');
const utils = trpc.useUtils();
const queryClient = useQueryClient();
useEffect(() => {
async function prefetch() {
const initialQuery = await utils.postById.ensureData('1');
expect(initialQuery.title).toBe('first post');
const cachedQuery = await utils.postById.ensureData('1');
expect(cachedQuery.title).toBe('first post');
// Update data to invalidate the cache
utils.postById.setData('1', () => {
return {
id: 'id',
title: 'updated post',
createdAt: Date.now(),
};
});
const updatedQuery = await utils.postById.ensureData('1');
expect(updatedQuery.title).toBe('updated post');
setState(updatedQuery.title);
}
prefetch();
}, [queryClient, utils]);
return <>{JSON.stringify(state)}</>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('updated post');
});
// Because we are using `ensureData` here, it should always be only a single call
// as the first invocation will fetch and cache the data, and any consecutive calls
// will not go through `postById.fetch`, but rather get the data directly from cache.
//
// Calling `postById.setData` updates the cache as well, so even after update
// number of direct calls should still be 1.
expect(factory.resolvers.postById.mock.calls.length).toBe(1);
expect(factory.resolvers.postById.mock.calls[0]![0]).toBe('1');
});
});
|
5,245 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/errors.test.tsx | import { getServerAndReactClient } from './__reactHelpers';
import { render, waitFor } from '@testing-library/react';
import { TRPCClientError, TRPCClientErrorLike } from '@trpc/client/src';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React from 'react';
import { z, ZodError } from 'zod';
describe('custom error formatter', () => {
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({
errorFormatter({ shape, error }) {
return {
...shape,
data: {
...shape.data,
foo: 'bar' as const,
zodError: error.cause instanceof ZodError ? error.cause : null,
},
};
},
});
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
// Minimum post id 1
id: z.number().min(1),
}),
)
.query(() => {
return '__result' as const;
}),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('query that fails', async () => {
const { proxy, App, appRouter } = ctx;
const queryErrorCallback = vi.fn();
function MyComponent() {
const query1 = proxy.post.byId.useQuery({
id: 0,
});
if (query1.error) {
expectTypeOf(query1.error.data?.foo).toMatchTypeOf<'bar' | undefined>();
expectTypeOf(query1.error).toMatchTypeOf<
TRPCClientErrorLike<typeof appRouter>
>();
expectTypeOf(query1.error).toEqualTypeOf<
TRPCClientErrorLike<typeof appRouter>
>();
queryErrorCallback(query1.error);
return (
<>
__ERROR_RESULT__:
<pre>{JSON.stringify(query1.error, null, 4)}</pre>
</>
);
}
return <>....</>;
}
render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(queryErrorCallback).toHaveBeenCalled();
});
const errorDataResult = queryErrorCallback.mock.calls[0]![0]!;
expect(errorDataResult).toBeInstanceOf(TRPCClientError);
expect(errorDataResult).toMatchInlineSnapshot(`
[TRPCClientError: [
{
"code": "too_small",
"minimum": 1,
"type": "number",
"inclusive": true,
"exact": false,
"message": "Number must be greater than or equal to 1",
"path": [
"id"
]
}
]]
`);
});
});
describe('no custom formatter', () => {
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
// Minimum post id 1
id: z.number().min(1),
}),
)
.query(() => {
return '__result' as const;
}),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('query that fails', async () => {
const { proxy, App, appRouter } = ctx;
const queryErrorCallback = vi.fn();
function MyComponent() {
const query1 = proxy.post.byId.useQuery({
id: 0,
});
if (query1.error) {
expectTypeOf(query1.error).toMatchTypeOf<
TRPCClientErrorLike<typeof appRouter>
>();
expectTypeOf(query1.error).toEqualTypeOf<
TRPCClientErrorLike<typeof appRouter>
>();
queryErrorCallback(query1.error);
return (
<>
__ERROR_RESULT__:
<pre>{JSON.stringify(query1.error, null, 4)}</pre>
</>
);
}
return <>....</>;
}
render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(queryErrorCallback).toHaveBeenCalled();
});
const errorDataResult = queryErrorCallback.mock.calls[0]![0]!;
expect(errorDataResult).toBeInstanceOf(TRPCClientError);
expect(errorDataResult).toMatchInlineSnapshot(`
[TRPCClientError: [
{
"code": "too_small",
"minimum": 1,
"type": "number",
"inclusive": true,
"exact": false,
"message": "Number must be greater than or equal to 1",
"path": [
"id"
]
}
]]
`);
});
});
test('types', async () => {
const t = initTRPC.create();
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
// Minimum post id 1
id: z.number().min(1),
}),
)
.query(() => {
return '__result' as const;
}),
}),
});
type TRouterError = TRPCClientErrorLike<typeof appRouter>;
type TProcedureError = TRPCClientErrorLike<
(typeof appRouter)['post']['byId']
>;
type TRouterError__data = TRouterError['data'];
// ^?
type TProcedureError__data = TProcedureError['data'];
// ^?
expectTypeOf<TRouterError__data>().toMatchTypeOf<TProcedureError__data>();
type TRouterError__shape = TRouterError['shape'];
// ^?
type TProcedureError__shape = TProcedureError['shape'];
// ^?
expectTypeOf<TRouterError__shape>().toMatchTypeOf<TProcedureError__shape>();
expectTypeOf<TRouterError>().toEqualTypeOf<TProcedureError>();
expectTypeOf<TRouterError>().toMatchTypeOf<TProcedureError>();
});
|
5,246 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/formData.test.tsx | import * as fs from 'fs';
import { routerToServerAndClientNew } from '../___testHelpers';
import { createQueryClient } from '../__queryClient';
import { QueryClientProvider } from '@tanstack/react-query';
import {
experimental_formDataLink,
httpBatchLink,
loggerLink,
splitLink,
} from '@trpc/client';
import { createTRPCReact } from '@trpc/react-query';
import { CreateTRPCReactBase } from '@trpc/react-query/createTRPCReact';
import { initTRPC } from '@trpc/server';
import {
experimental_createFileUploadHandler,
experimental_createMemoryUploadHandler,
experimental_isMultipartFormDataRequest,
experimental_NodeOnDiskFile,
experimental_parseMultipartFormData,
nodeHTTPFormDataContentTypeHandler,
} from '@trpc/server/adapters/node-http/content-type/form-data';
import { nodeHTTPJSONContentTypeHandler } from '@trpc/server/adapters/node-http/content-type/json';
import { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
import { konn } from 'konn';
import React, { ReactNode } from 'react';
import { z } from 'zod';
import { zfd } from 'zod-form-data';
beforeAll(async () => {
const { FormData, File, Blob } = await import('node-fetch');
globalThis.FormData = FormData;
globalThis.File = File;
globalThis.Blob = Blob;
});
function formDataOrObject<T extends z.ZodRawShape>(input: T) {
return zfd.formData(input).or(z.object(input));
}
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.context<CreateHTTPContextOptions>().create();
const appRouter = t.router({
polymorphic: t.procedure
.use(async (opts) => {
if (!experimental_isMultipartFormDataRequest(opts.ctx.req)) {
return opts.next();
}
const formData = await experimental_parseMultipartFormData(
opts.ctx.req,
experimental_createMemoryUploadHandler(),
);
return opts.next({
rawInput: formData,
});
})
.input(
formDataOrObject({
text: z.string(),
}),
)
.mutation((opts) => {
return opts.input;
}),
uploadFile: t.procedure
.use(async (opts) => {
const formData = await experimental_parseMultipartFormData(
opts.ctx.req,
experimental_createMemoryUploadHandler(),
);
return opts.next({
rawInput: formData,
});
})
.input(
zfd.formData({
file: zfd.file(),
}),
)
.mutation(async ({ input }) => {
return {
file: {
name: input.file.name,
type: input.file.type,
file: await input.file.text(),
},
};
}),
uploadFilesOnDiskAndIncludeTextPropertiesToo: t.procedure
.use(async (opts) => {
const maxBodySize = 100; // 100 bytes
const formData = await experimental_parseMultipartFormData(
opts.ctx.req,
experimental_createFileUploadHandler(),
maxBodySize,
);
return opts.next({
rawInput: formData,
});
})
.input(
zfd.formData({
files: zfd.repeatableOfType(
z.instanceof(experimental_NodeOnDiskFile),
),
text: z.string(),
json: zfd.json(z.object({ foo: z.string() })),
}),
)
.mutation(async ({ input }) => {
const files = await Promise.all(
input.files.map(async (file) => ({
name: file.name,
type: file.type,
file: await file.text(),
})),
);
return {
files,
text: input.text,
json: input.json,
};
}),
});
type TRouter = typeof appRouter;
const loggerLinkConsole = {
log: vi.fn(),
error: vi.fn(),
};
const opts = routerToServerAndClientNew(appRouter, {
server: {
experimental_contentTypeHandlers: [
nodeHTTPFormDataContentTypeHandler(),
nodeHTTPJSONContentTypeHandler(),
],
},
client: ({ httpUrl }) => ({
links: [
loggerLink({
enabled: () => true,
// console: loggerLinkConsole,
}),
splitLink({
condition: (op) => op.input instanceof FormData,
true: experimental_formDataLink({
url: httpUrl,
}),
false: httpBatchLink({
url: httpUrl,
}),
}),
],
}),
});
const queryClient = createQueryClient();
const proxy = createTRPCReact<TRouter, unknown>();
const baseProxy = proxy as CreateTRPCReactBase<TRouter, unknown>;
const client = opts.client;
function App(props: { children: ReactNode }) {
return (
<baseProxy.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</baseProxy.Provider>
);
}
return {
...opts,
close: opts.close,
queryClient,
App,
loggerLinkConsole,
};
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('upload file', async () => {
const form = new FormData();
form.append(
'file',
new File(['hi bob'], 'bob.txt', {
type: 'text/plain',
}),
);
const fileContents = await ctx.proxy.uploadFile.mutate(form);
expect(fileContents).toMatchInlineSnapshot(`
Object {
"file": Object {
"file": "hi bob",
"name": "bob.txt",
"type": "text/plain",
},
}
`);
});
test('polymorphic - accept both JSON and FormData', async () => {
const form = new FormData();
form.set('text', 'foo');
const formDataRes = await ctx.proxy.polymorphic.mutate(form);
const jsonRes = await ctx.proxy.polymorphic.mutate({
text: 'foo',
});
expect(formDataRes).toEqual(jsonRes);
});
test('upload a combination of files and non-file text fields', async () => {
const form = new FormData();
form.append(
'files',
new File(['hi bob'], 'bob.txt', {
type: 'text/plain',
}),
);
form.append(
'files',
new File(['hi alice'], 'alice.txt', {
type: 'text/plain',
}),
);
form.set('text', 'foo');
form.set('json', JSON.stringify({ foo: 'bar' }));
const fileContents =
await ctx.proxy.uploadFilesOnDiskAndIncludeTextPropertiesToo.mutate(form);
expect(fileContents).toEqual({
files: [
{
file: 'hi bob',
name: expect.stringMatching(/\.txt$/),
type: 'text/plain',
},
{
file: 'hi alice',
name: expect.stringMatching(/\.txt$/),
type: 'text/plain',
},
],
text: 'foo',
json: {
foo: 'bar',
},
});
});
test('Throws when aggregate size of uploaded files and non-file text fields exceeds maxBodySize - files too large', async () => {
const form = new FormData();
form.append(
'files',
new File(['a'.repeat(50)], 'bob.txt', {
type: 'text/plain',
}),
);
form.append(
'files',
new File(['a'.repeat(51)], 'alice.txt', {
type: 'text/plain',
}),
);
form.set('text', 'foo');
form.set('json', JSON.stringify({ foo: 'bar' }));
await expect(
ctx.proxy.uploadFilesOnDiskAndIncludeTextPropertiesToo.mutate(form),
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Body exceeded upload size of 100 bytes."`,
);
});
test('Throws when aggregate size of uploaded files and non-file text fields exceeds maxBodySize - text fields too large', async () => {
const form = new FormData();
form.append(
'files',
new File(['hi bob'], 'bob.txt', {
type: 'text/plain',
}),
);
form.set('text', 'a'.repeat(101));
form.set('json', JSON.stringify({ foo: 'bar' }));
await expect(
ctx.proxy.uploadFilesOnDiskAndIncludeTextPropertiesToo.mutate(form),
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Body exceeded upload size of 100 bytes."`,
);
});
|
5,247 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/formatError.test.tsx | import { createQueryClient } from '../__queryClient';
import { createAppRouter } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import { DefaultErrorShape } from '@trpc/server/src/error/formatter';
import React, { useEffect, useState } from 'react';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
test('react types test', async () => {
const { trpc, client } = factory;
function MyComponent() {
const mutation = trpc.addPost.useMutation();
useEffect(() => {
mutation.mutate({ title: 123 as any });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (mutation.error?.shape) {
expectTypeOf(mutation.error.shape).toMatchTypeOf<
DefaultErrorShape & {
$test: string;
}
>();
expectTypeOf(mutation.error.shape).toMatchTypeOf<
DefaultErrorShape & {
$test: string;
}
>();
return (
<pre data-testid="err">
{JSON.stringify(mutation.error.shape.zodError, null, 2)}
</pre>
);
}
return <></>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('fieldErrors');
expect(utils.getByTestId('err').innerText).toMatchInlineSnapshot(
`undefined`,
);
});
});
|
5,248 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/getQueryKey.test.tsx | import { getServerAndReactClient } from './__reactHelpers';
import { useIsFetching } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import { getQueryKey } from '@trpc/react-query';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
import React from 'react';
import { z } from 'zod';
type Post = {
id: number;
text: string;
};
const defaultPost = { id: 0, text: 'new post' };
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const posts: Post[] = [defaultPost];
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
id: z.number(),
}),
)
.query(({ input }) => posts.find((post) => post.id === input.id)),
all: t.procedure.query(() => posts),
list: t.procedure
.input(z.object({ cursor: z.number() }))
.query(({ input }) => {
return posts.slice(input.cursor);
}),
moreLists: t.procedure
.input(z.object({ anotherKey: z.number(), cursor: z.number() }))
.query(({ input }) => {
return posts.slice(input.cursor);
}),
update: t.procedure
.input(
z.object({
name: z.string(),
}),
)
.mutation(({ input }) => {
return {
user: {
name: input.name,
},
};
}),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
describe('getQueryKeys', () => {
test('no input', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy1 = getQueryKey(proxy.post.all, undefined, 'query');
const happy2 = getQueryKey(proxy.post.all);
// @ts-expect-error - post.all has no input
const sad = getQueryKey(proxy.post.all, 'foo');
return (
<>
<pre data-testid="qKey1">{JSON.stringify(happy1)}</pre>
<pre data-testid="qKey2">{JSON.stringify(happy2)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey1')).toHaveTextContent(
JSON.stringify([['post', 'all'], { type: 'query' }]),
);
expect(utils.getByTestId('qKey2')).toHaveTextContent(
JSON.stringify([['post', 'all']]),
);
});
});
test('with input', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy1 = getQueryKey(proxy.post.byId, { id: 1 }, 'query');
// input is fuzzy matched so should not be required
const happy2 = getQueryKey(proxy.post.byId, undefined, 'query');
const happy3 = getQueryKey(proxy.post.byId);
// doesn't really make sense but should still work
const happyIsh = getQueryKey(proxy.post.byId, { id: 1 });
return (
<>
<pre data-testid="qKey1">{JSON.stringify(happy1)}</pre>
<pre data-testid="qKey2">{JSON.stringify(happy2)}</pre>
<pre data-testid="qKey3">{JSON.stringify(happy3)}</pre>
<pre data-testid="qKey4">{JSON.stringify(happyIsh)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey1')).toHaveTextContent(
JSON.stringify([['post', 'byId'], { input: { id: 1 }, type: 'query' }]),
);
expect(utils.getByTestId('qKey2')).toHaveTextContent(
JSON.stringify([['post', 'byId'], { type: 'query' }]),
);
expect(utils.getByTestId('qKey3')).toHaveTextContent(
JSON.stringify([['post', 'byId']]),
);
expect(utils.getByTestId('qKey4')).toHaveTextContent(
JSON.stringify([['post', 'byId'], { input: { id: 1 } }]),
);
});
});
test('undefined input but type', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy = getQueryKey(proxy.post.list, undefined, 'infinite');
// @ts-expect-error - cursor is not a valid input
const sad = getQueryKey(proxy.post.list, { cursor: 1 }, 'infinite');
return (
<>
<pre data-testid="qKey">{JSON.stringify(happy)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey')).toHaveTextContent(
JSON.stringify([['post', 'list'], { type: 'infinite' }]),
);
});
});
test('undefined input but type', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy = getQueryKey(proxy.post.list, undefined, 'infinite');
// @ts-expect-error - cursor is not a valid input
const sad = getQueryKey(proxy.post.list, { cursor: 1 }, 'infinite');
// @ts-expect-error - input is always invalid
const sad2 = getQueryKey(proxy.post.list, { anyKey: 1 }, 'infinite');
return (
<>
<pre data-testid="qKey">{JSON.stringify(happy)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey')).toHaveTextContent(
JSON.stringify([['post', 'list'], { type: 'infinite' }]),
);
});
});
test('extra key in input but type', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy = getQueryKey(
proxy.post.moreLists,
{ anotherKey: 1 },
'infinite',
);
// these should also be valid since the input is fuzzy matched
getQueryKey(proxy.post.moreLists, undefined, 'infinite');
getQueryKey(proxy.post.moreLists, undefined);
getQueryKey(proxy.post.moreLists);
getQueryKey(proxy.post.moreLists, {}, 'infinite');
getQueryKey(proxy.post.moreLists, { anotherKey: 1 });
// @ts-expect-error - cursor is not a valid input
const sad2 = getQueryKey(proxy.post.moreLists, { cursor: 1 }, 'infinite');
// @ts-expect-error - input is always invalid
const sad3 = getQueryKey(proxy.post.moreLists, { anyKey: 1 }, 'infinite');
return (
<>
<pre data-testid="qKey">{JSON.stringify(happy)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey')).toHaveTextContent(
JSON.stringify([
['post', 'moreLists'],
{ input: { anotherKey: 1 }, type: 'infinite' },
]),
);
});
});
test('infinite', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy = getQueryKey(proxy.post.list, undefined, 'infinite');
return (
<>
<pre data-testid="qKey">{JSON.stringify(happy)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey')).toHaveTextContent(
JSON.stringify([['post', 'list'], { type: 'infinite' }]),
);
});
});
test('mutation', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy = getQueryKey(proxy.post.update);
// @ts-expect-error - mutations takes no input
const sad = getQueryKey(proxy.post.update, { name: 'trash' });
return (
<div>
<pre data-testid="qKey">{JSON.stringify(happy)}</pre>
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey')).toHaveTextContent(
JSON.stringify([['post', 'update']]),
);
});
});
test('on router', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy = getQueryKey(proxy.post);
// @ts-expect-error - router has no input
const sad = getQueryKey(proxy.post, 'foo');
return (
<div>
<pre data-testid="qKey">{JSON.stringify(happy)}</pre>
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey')).toHaveTextContent(
JSON.stringify([['post']]),
);
});
});
test('forwarded to a real method', async () => {
const { proxy, App } = ctx;
function MyComponent() {
proxy.post.all.useQuery();
const qKey = getQueryKey(proxy.post.all, undefined, 'query');
const isFetching = useIsFetching(qKey);
return <div>{isFetching}</div>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
// should be fetching initially, and then not
expect(utils.container).toHaveTextContent('1');
await waitFor(() => {
expect(utils.container).toHaveTextContent('0');
});
});
test('outside of the react context', () => {
const { proxy } = ctx;
const all = getQueryKey(proxy.post.all, undefined, 'query');
const byId = getQueryKey(proxy.post.byId, { id: 1 }, 'query');
expect(all).toEqual([['post', 'all'], { type: 'query' }]);
expect(byId).toEqual([
['post', 'byId'],
{ input: { id: 1 }, type: 'query' },
]);
});
});
describe('getQueryKeys deprecated', () => {
test('no input', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy1 = proxy.post.all.getQueryKey(undefined, 'query');
const happy2 = proxy.post.all.getQueryKey();
// @ts-expect-error - post.all has no input
const sad = proxy.post.all.getQueryKey('foo');
return (
<>
<pre data-testid="qKey1">{JSON.stringify(happy1)}</pre>
<pre data-testid="qKey2">{JSON.stringify(happy2)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey1')).toHaveTextContent(
JSON.stringify([['post', 'all'], { type: 'query' }]),
);
expect(utils.getByTestId('qKey2')).toHaveTextContent(
JSON.stringify([['post', 'all']]),
);
});
});
test('with input', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy1 = proxy.post.byId.getQueryKey({ id: 1 }, 'query');
// doesn't really make sense but should still work
const happyIsh = proxy.post.byId.getQueryKey({ id: 1 });
// @ts-expect-error - post.byId has required input
const sad = proxy.post.byId.getQueryKey(undefined, 'query');
return (
<>
<pre data-testid="qKey1">{JSON.stringify(happy1)}</pre>
<pre data-testid="qKey2">{JSON.stringify(happyIsh)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey1')).toHaveTextContent(
JSON.stringify([['post', 'byId'], { input: { id: 1 }, type: 'query' }]),
);
expect(utils.getByTestId('qKey2')).toHaveTextContent(
JSON.stringify([['post', 'byId'], { input: { id: 1 } }]),
);
});
});
test('on router', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const happy = proxy.post.getQueryKey();
// @ts-expect-error - router has no input
const sad = proxy.post.getQueryKey('foo');
return (
<div>
<pre data-testid="qKey">{JSON.stringify(happy)}</pre>
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('qKey')).toHaveTextContent(
JSON.stringify([['post']]),
);
});
});
test('forwarded to a real method', async () => {
const { proxy, App } = ctx;
function MyComponent() {
proxy.post.all.useQuery();
const qKey = proxy.post.all.getQueryKey(undefined, 'query');
const isFetching = useIsFetching(qKey);
return <div>{isFetching}</div>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
// should be fetching initially, and then not
expect(utils.container).toHaveTextContent('1');
await waitFor(() => {
expect(utils.container).toHaveTextContent('0');
});
});
test('outside of the react context', () => {
const { proxy } = ctx;
const all = proxy.post.all.getQueryKey(undefined, 'query');
const byId = proxy.post.byId.getQueryKey({ id: 1 }, 'query');
expect(all).toEqual([['post', 'all'], { type: 'query' }]);
expect(byId).toEqual([
['post', 'byId'],
{ input: { id: 1 }, type: 'query' },
]);
});
});
|
5,249 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/infiniteQuery.test.tsx | import { ignoreErrors } from '../___testHelpers';
import { createQueryClient } from '../__queryClient';
import { createAppRouter, Post } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createServerSideHelpers } from '@trpc/react-query/server';
import { inferProcedureInput } from '@trpc/server';
import React, { Fragment, useState } from 'react';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('Infinite Query', () => {
test('useInfiniteQuery()', async () => {
const { trpc, client } = factory;
function MyComponent() {
const q = trpc.paginatedPosts.useInfiniteQuery(
{
limit: 1,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
expectTypeOf(q.data?.pages[0]!.items).toMatchTypeOf<Post[] | undefined>();
return q.status === 'loading' ? (
<p>Loading...</p>
) : q.status === 'error' ? (
<p>Error: {q.error.message}</p>
) : (
<>
{q.data?.pages.map((group, i) => (
<Fragment key={i}>
{group.items.map((msg) => (
<Fragment key={msg.id}>
<div>{msg.title}</div>
</Fragment>
))}
</Fragment>
))}
<div>
<button
onClick={() => q.fetchNextPage()}
disabled={!q.hasNextPage || q.isFetchingNextPage}
data-testid="loadMore"
>
{q.isFetchingNextPage
? 'Loading more...'
: q.hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</div>
<div>
{q.isFetching && !q.isFetchingNextPage ? 'Fetching...' : null}
</div>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Load More');
});
await userEvent.click(utils.getByTestId('loadMore'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Loading more...');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Nothing more to load');
});
expect(utils.container).toMatchInlineSnapshot(`
<div>
<div>
first post
</div>
<div>
second post
</div>
<div>
<button
data-testid="loadMore"
disabled=""
>
Nothing more to load
</button>
</div>
<div />
</div>
`);
});
test('useInfiniteQuery and prefetchInfiniteQuery', async () => {
const { trpc, client } = factory;
function MyComponent() {
const trpcContext = trpc.useUtils();
const q = trpc.paginatedPosts.useInfiniteQuery(
{
limit: 1,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
expectTypeOf(q.data?.pages[0]?.items).toMatchTypeOf<Post[] | undefined>();
return q.status === 'loading' ? (
<p>Loading...</p>
) : q.status === 'error' ? (
<p>Error: {q.error.message}</p>
) : (
<>
{q.data?.pages.map((group, i) => (
<Fragment key={i}>
{group.items.map((msg) => (
<Fragment key={msg.id}>
<div>{msg.title}</div>
</Fragment>
))}
</Fragment>
))}
<div>
<button
onClick={() => q.fetchNextPage()}
disabled={!q.hasNextPage || q.isFetchingNextPage}
data-testid="loadMore"
>
{q.isFetchingNextPage
? 'Loading more...'
: q.hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</div>
<div>
<button
data-testid="prefetch"
onClick={() =>
trpcContext.paginatedPosts.prefetchInfinite({ limit: 1 })
}
>
Prefetch
</button>
</div>
<div>
{q.isFetching && !q.isFetchingNextPage ? 'Fetching...' : null}
</div>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Load More');
});
await userEvent.click(utils.getByTestId('loadMore'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Loading more...');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Nothing more to load');
});
expect(utils.container).toMatchInlineSnapshot(`
<div>
<div>
first post
</div>
<div>
second post
</div>
<div>
<button
data-testid="loadMore"
disabled=""
>
Nothing more to load
</button>
</div>
<div>
<button
data-testid="prefetch"
>
Prefetch
</button>
</div>
<div />
</div>
`);
await userEvent.click(utils.getByTestId('prefetch'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Fetching...');
});
await waitFor(() => {
expect(utils.container).not.toHaveTextContent('Fetching...');
});
// It should correctly fetch both pages
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
test('useInfiniteQuery and fetchInfiniteQuery', async () => {
const { trpc, client } = factory;
function MyComponent() {
const trpcContext = trpc.useUtils();
const q = trpc.paginatedPosts.useInfiniteQuery(
{
limit: 1,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
expectTypeOf(q.data?.pages[0]?.items).toMatchTypeOf<Post[] | undefined>();
return q.status === 'loading' ? (
<p>Loading...</p>
) : q.status === 'error' ? (
<p>Error: {q.error.message}</p>
) : (
<>
{q.data?.pages.map((group, i) => (
<Fragment key={i}>
{group.items.map((msg) => (
<Fragment key={msg.id}>
<div>{msg.title}</div>
</Fragment>
))}
</Fragment>
))}
<div>
<button
onClick={() => q.fetchNextPage()}
disabled={!q.hasNextPage || q.isFetchingNextPage}
data-testid="loadMore"
>
{q.isFetchingNextPage
? 'Loading more...'
: q.hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</div>
<div>
<button
data-testid="fetch"
onClick={() =>
trpcContext.paginatedPosts.fetchInfinite({ limit: 1 })
}
>
Fetch
</button>
</div>
<div>
{q.isFetching && !q.isFetchingNextPage ? 'Fetching...' : null}
</div>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Load More');
});
await userEvent.click(utils.getByTestId('loadMore'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Loading more...');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
expect(utils.container).toHaveTextContent('Nothing more to load');
});
expect(utils.container).toMatchInlineSnapshot(`
<div>
<div>
first post
</div>
<div>
second post
</div>
<div>
<button
data-testid="loadMore"
disabled=""
>
Nothing more to load
</button>
</div>
<div>
<button
data-testid="fetch"
>
Fetch
</button>
</div>
<div />
</div>
`);
await userEvent.click(utils.getByTestId('fetch'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('Fetching...');
});
await waitFor(() => {
expect(utils.container).not.toHaveTextContent('Fetching...');
});
// It should correctly fetch both pages
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
test('prefetchInfiniteQuery()', async () => {
const { appRouter } = factory;
const ssg = createServerSideHelpers({ router: appRouter, ctx: {} });
{
await ssg.paginatedPosts.prefetchInfinite({ limit: 1 });
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('first post');
expect(data).not.toContain('second post');
}
{
await ssg.paginatedPosts.fetchInfinite({ limit: 2 });
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('first post');
expect(data).toContain('second post');
}
});
test('useInfiniteQuery() is exposed on procedure with optional inputs', () => {
const { trpc, appRouter } = factory;
type AppRouter = typeof appRouter;
type Input = inferProcedureInput<AppRouter['paginatedPosts']>;
type Extends<T, U> = T extends U ? true : false;
// Optional procedure inputs are unioned with void | undefined.
assertType<Extends<Input, { cursor?: string }>>(false);
assertType<Extends<Input, { cursor?: string } | void>>(true);
assertType<Extends<Input, { cursor?: string } | undefined>>(true);
assertType<Extends<Input, { cursor?: string } | undefined | void>>(true);
// Assert 'useInfiniteQuery' is exposed in 'trpc.paginatedPosts'.
expectTypeOf(trpc.paginatedPosts.useInfiniteQuery).toBeFunction();
});
test('useInfiniteQuery() is **not** exposed if there is not cursor', () => {
ignoreErrors(async () => {
// @ts-expect-error 'cursor' is required
factory.trpc.postById.useInfiniteQuery;
const ssg = createServerSideHelpers({
router: factory.appRouter,
ctx: {},
});
// good
await ssg.paginatedPosts.fetchInfinite({ limit: 1 });
// @ts-expect-error 'cursor' is required
await ssg.postById.fetchInfinite({ limit: 1 });
});
});
});
|
5,250 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/interopBasic.test.tsx | import { routerToServerAndClientNew } from '../___testHelpers';
import { createQueryClient } from '../__queryClient';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import { createReactQueryHooks, httpBatchLink } from '@trpc/react-query/src';
import * as interop from '@trpc/server/src';
import { inferProcedureOutput, initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React, { useState } from 'react';
import superjson from 'superjson';
import { z } from 'zod';
type Context = {
foo: 'bar';
};
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.context<Context>().create();
const legacyRouter = interop
.router<Context>()
.transformer(superjson)
.query('oldProcedure', {
input: z.string().optional(),
resolve({ input }) {
return `oldProcedureOutput__input:${input ?? 'n/a'}`;
},
});
const legacyRouterInterop = legacyRouter.interop();
expectTypeOf(legacyRouterInterop._def.queries.oldProcedure).not.toBeNever();
const newAppRouter = t.router({
newProcedure: t.procedure.query(() => 'newProcedureOutput'),
});
const appRouter = t.mergeRouters(legacyRouterInterop, newAppRouter);
const opts = routerToServerAndClientNew(appRouter, {
server: {
createContext() {
return {
foo: 'bar',
};
},
},
client({ httpUrl }) {
return {
transformer: superjson,
links: [
httpBatchLink({
url: httpUrl,
}),
],
};
},
});
const queryClient = createQueryClient();
const react = createReactQueryHooks<(typeof opts)['router']>();
const client = opts.client;
type Return = inferProcedureOutput<
typeof opts.router._def.queries.oldProcedure
>;
expectTypeOf<Return>().toMatchTypeOf<string>();
return {
opts,
close: opts.close,
client,
queryClient,
react,
appRouter,
legacyRouterInterop,
};
})
.afterEach(async (ctx) => {
await ctx?.opts?.close?.();
})
.done();
test('interop inference', async () => {
const { opts } = ctx;
expect(await opts.client.query('oldProcedure')).toBe(
'oldProcedureOutput__input:n/a',
);
// @ts-expect-error we can't call oldProcedure with proxy
expect(await opts.proxy.oldProcedure.query()).toBe(
'oldProcedureOutput__input:n/a',
);
// @ts-expect-error we can't call new procedures without proxy
expect(await opts.client.query('newProcedure')).toBe('newProcedureOutput');
expect(await opts.proxy.newProcedure.query()).toBe('newProcedureOutput');
});
test('useQuery()', async () => {
const { react, client } = ctx;
function MyComponent() {
const query1 = react.useQuery(['oldProcedure']);
const query2 = react.useQuery(['oldProcedure', 'KATT']);
if (!query1.data || !query2.data) {
return <>...</>;
}
expectTypeOf(query1.data).not.toBeAny();
expectTypeOf(query1.data).toMatchTypeOf<string>();
return (
<pre>
{JSON.stringify(
{ query1: query1.data, query2: query2.data } ?? 'n/a',
null,
4,
)}
</pre>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<react.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</react.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`oldProcedureOutput__input:n/a`);
expect(utils.container).toHaveTextContent(`oldProcedureOutput__input:KATT`);
});
});
test("we can use new router's procedures too", async () => {
const { react, client } = ctx;
function MyComponent() {
const query1 = react.proxy.newProcedure.useQuery();
if (!query1.data) {
return <>...</>;
}
expectTypeOf(query1.data).not.toBeAny();
expectTypeOf(query1.data).toMatchTypeOf<string>();
return (
<pre>{JSON.stringify({ query1: query1.data } ?? 'n/a', null, 4)}</pre>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<react.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</react.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`newProcedureOutput`);
});
});
test("old procedures can't be used in interop", async () => {
const { react, client } = ctx;
function MyComponent() {
// @ts-expect-error we can't call oldProcedure with proxy
react.proxy.oldProcedure.useQuery();
return <>__hello</>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<react.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</react.Provider>
);
}
render(<App />);
});
test('createCaller', async () => {
{
const caller = ctx.appRouter.createCaller({
foo: 'bar',
});
expect(await caller.newProcedure()).toBe('newProcedureOutput');
expect(await caller.query('oldProcedure')).toBe(
'oldProcedureOutput__input:n/a',
);
}
{
const caller = ctx.legacyRouterInterop.createCaller({
foo: 'bar',
});
expect(await caller.query('oldProcedure')).toBe(
'oldProcedureOutput__input:n/a',
);
}
{
const asyncFnThatReturnsCaller = async () =>
ctx.legacyRouterInterop.createCaller({
foo: 'bar',
});
const caller = await asyncFnThatReturnsCaller();
expect(await caller.query('oldProcedure')).toBe(
'oldProcedureOutput__input:n/a',
);
}
});
|
5,251 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/interopBig.test.tsx | import { routerToServerAndClientNew } from '../___testHelpers';
import { appRouter as bigV10Router } from '../__generated__/bigBoi/_app';
import { bigRouter as bigV9Router } from '../__generated__/bigLegacyRouter/bigRouter';
import { createQueryClient } from '../__queryClient';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import { createReactQueryHooks } from '@trpc/react-query/src';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React, { useState } from 'react';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const legacyRouterInterop = bigV9Router.interop();
const appRouter = t.mergeRouters(legacyRouterInterop, bigV10Router);
const opts = routerToServerAndClientNew(appRouter, {});
const queryClient = createQueryClient();
const react = createReactQueryHooks<(typeof opts)['router']>();
const client = opts.client;
return {
opts,
close: opts.close,
client,
queryClient,
react,
appRouter,
};
})
.afterEach(async (ctx) => {
await ctx?.opts?.close?.();
})
.done();
test('vanilla', async () => {
const res = await ctx.client.query('oldProc100');
expectTypeOf(res).toEqualTypeOf<'100'>();
expect(res).toBe('100');
});
test('react', async () => {
const { react, client } = ctx;
function MyComponent() {
const query1 = react.proxy.r499.greeting.useQuery({ who: 'KATT' });
if (!query1.data) {
return <>...</>;
}
expectTypeOf(query1.data).not.toBeAny();
expectTypeOf(query1.data).toMatchTypeOf<string>();
return <pre>{JSON.stringify(query1.data ?? 'n/a', null, 4)}</pre>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<react.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</react.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`hello KATT`);
});
});
|
5,252 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/interopBigCompiled.test.tsx | /* eslint-disable no-console */
import { appRouter as bigV10Router } from '../__generated__/bigBoi/_app';
import { t } from '../__generated__/bigBoi/_trpc';
import { bigRouter as bigV9Router } from '../__generated__/bigLegacyRouter/bigRouter';
import {
createTRPCClient,
createTRPCProxyClient,
httpBatchLink,
} from '@trpc/client/src';
import { createReactQueryHooks } from '@trpc/react-query/src';
const legacyRouterInterop = bigV9Router.interop();
const appRouter = t.mergeRouters(legacyRouterInterop, bigV10Router);
type AppRouter = typeof appRouter;
test('raw client', async () => {
try {
const client = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: 'http://localhost:-1' })],
});
const result = await client.query('oldProc100');
// ^?
expectTypeOf(result).toEqualTypeOf<'100'>();
} catch {
// ignore
}
try {
const proxy = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:-1',
}),
],
});
const result = await proxy.r0.greeting.query({ who: 'KATT' });
expectTypeOf(result).not.toBeAny();
expectTypeOf(result).toMatchTypeOf<string>();
} catch {
// ignore
}
});
test('react', () => {
const prevConsoleError = console.error;
console.error = () => {
// whatever
};
const trpc = createReactQueryHooks<AppRouter>();
try {
const { data } = trpc.useQuery(['oldProc100']);
if (!data) {
throw new Error('Whatever');
}
expectTypeOf(data).toEqualTypeOf<'100'>();
} catch {
// whatever
}
try {
const { data } = trpc.proxy.r499.greeting.useQuery({ who: 'KATT' });
if (!data) {
throw new Error('Whatever');
}
expectTypeOf(data).not.toBeAny();
expectTypeOf(data).toMatchTypeOf<string>();
} catch {
// whatever
}
console.error = prevConsoleError;
});
|
5,253 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/invalidateQueries.test.tsx | import { createQueryClient } from '../__queryClient';
import { createAppRouter } from './__testHelpers';
import { QueryClientProvider, useQueryClient } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { QueryKey } from '@trpc/react-query/src/internals/getArrayQueryKey';
import React, { useState } from 'react';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('invalidateQueries()', () => {
test('queryClient.invalidateQueries()', async () => {
const { trpc, resolvers, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.allPosts.useQuery(undefined, {
staleTime: Infinity,
});
const postByIdQuery = trpc.postById.useQuery('1', {
staleTime: Infinity,
});
const queryClient = useQueryClient();
return (
<>
<pre>
allPostsQuery:{allPostsQuery.status} allPostsQuery:
{allPostsQuery.isStale ? 'stale' : 'not-stale'}{' '}
</pre>
<pre>
postByIdQuery:{postByIdQuery.status} postByIdQuery:
{postByIdQuery.isStale ? 'stale' : 'not-stale'}
</pre>
<button
data-testid="refetch"
onClick={() => {
queryClient.invalidateQueries([['allPosts']]);
queryClient.invalidateQueries([['postById']]);
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:success');
expect(utils.container).toHaveTextContent('allPostsQuery:success');
expect(utils.container).toHaveTextContent('postByIdQuery:not-stale');
expect(utils.container).toHaveTextContent('allPostsQuery:not-stale');
});
expect(resolvers.allPosts).toHaveBeenCalledTimes(1);
expect(resolvers.postById).toHaveBeenCalledTimes(1);
await userEvent.click(utils.getByTestId('refetch'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:stale');
expect(utils.container).toHaveTextContent('allPostsQuery:stale');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:not-stale');
expect(utils.container).toHaveTextContent('allPostsQuery:not-stale');
});
expect(resolvers.allPosts).toHaveBeenCalledTimes(2);
expect(resolvers.postById).toHaveBeenCalledTimes(2);
});
test('invalidateQueries()', async () => {
const { trpc, resolvers, client } = factory;
function MyComponent() {
const allPostsQuery = trpc.allPosts.useQuery(undefined, {
staleTime: Infinity,
});
const postByIdQuery = trpc.postById.useQuery('1', {
staleTime: Infinity,
});
const utils = trpc.useUtils();
return (
<>
<pre>
allPostsQuery:{allPostsQuery.status} allPostsQuery:
{allPostsQuery.isStale ? 'stale' : 'not-stale'}{' '}
</pre>
<pre>
postByIdQuery:{postByIdQuery.status} postByIdQuery:
{postByIdQuery.isStale ? 'stale' : 'not-stale'}
</pre>
<button
data-testid="refetch"
onClick={() => {
utils.allPosts.invalidate();
utils.postById.invalidate('1');
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:success');
expect(utils.container).toHaveTextContent('allPostsQuery:success');
expect(utils.container).toHaveTextContent('postByIdQuery:not-stale');
expect(utils.container).toHaveTextContent('allPostsQuery:not-stale');
});
expect(resolvers.allPosts).toHaveBeenCalledTimes(1);
expect(resolvers.postById).toHaveBeenCalledTimes(1);
await userEvent.click(utils.getByTestId('refetch'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:stale');
expect(utils.container).toHaveTextContent('allPostsQuery:stale');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('postByIdQuery:not-stale');
expect(utils.container).toHaveTextContent('allPostsQuery:not-stale');
});
expect(resolvers.allPosts).toHaveBeenCalledTimes(2);
expect(resolvers.postById).toHaveBeenCalledTimes(2);
});
test('test invalidateQueries() with different args', async () => {
// ref https://github.com/trpc/trpc/issues/1383
const { trpc, client } = factory;
function MyComponent() {
const countQuery = trpc.count.useQuery('test', {
staleTime: Infinity,
});
const utils = trpc.useUtils();
return (
<>
<pre>count:{countQuery.data}</pre>
<button
data-testid="invalidate-1-string"
onClick={() => {
utils.count.invalidate();
}}
/>
<button
data-testid="invalidate-2-exact"
onClick={() => {
utils.count.invalidate('test');
}}
/>
<button
data-testid="invalidate-3-all"
onClick={() => {
utils.invalidate();
}}
/>{' '}
<button
data-testid="invalidate-4-predicate"
onClick={() => {
utils.invalidate(undefined, {
predicate(opts) {
const { queryKey } = opts;
const [path, data] = queryKey as QueryKey;
return path[0] === 'count' && data?.input === 'test';
},
});
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('count:test:0');
});
for (const [index, testId] of [
'invalidate-1-string',
'invalidate-2-exact',
'invalidate-3-all',
'invalidate-4-predicate',
].entries()) {
// click button to invalidate
await userEvent.click(utils.getByTestId(testId));
await waitFor(async () => {
// should become stale straight after the click
expect(utils.container).toHaveTextContent(`count:test:${index + 1}`);
});
}
});
test('test invalidateQueries() with a partial input', async () => {
const { trpc, client } = factory;
function MyComponent() {
const mockPostQuery1 = trpc.getMockPostByContent.useQuery(
{ id: 'id', content: { language: 'eng', type: 'fun' }, title: 'title' },
{
staleTime: Infinity,
},
);
const mockPostQuery2 = trpc.getMockPostByContent.useQuery(
{
id: 'id',
content: { language: 'eng', type: 'boring' },
title: 'title',
},
{
staleTime: Infinity,
},
);
const mockPostQuery3 = trpc.getMockPostByContent.useQuery(
{
id: 'id',
content: { language: 'de', type: 'fun' },
title: 'title',
},
{
staleTime: Infinity,
},
);
const utils = trpc.useUtils();
return (
<>
<pre>mockPostQuery1:{mockPostQuery1.status}</pre>
<pre>
mockPostQuery1:{mockPostQuery1.isStale ? 'stale' : 'not-stale'}
</pre>
<pre>mockPostQuery2:{mockPostQuery2.status}</pre>
<pre>
mockPostQuery2:{mockPostQuery2.isStale ? 'stale' : 'not-stale'}
</pre>
<pre>mockPostQuery3:{mockPostQuery3.status}</pre>
<pre>
mockPostQuery3:{mockPostQuery3.isStale ? 'stale' : 'not-stale'}
</pre>
<button
data-testid="invalidate-with-partial-input"
onClick={() => {
utils.getMockPostByContent.invalidate({
id: 'id',
content: { language: 'eng' },
});
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('mockPostQuery1:success');
expect(utils.container).toHaveTextContent('mockPostQuery2:success');
expect(utils.container).toHaveTextContent('mockPostQuery3:success');
});
// click button to invalidate
await userEvent.click(utils.getByTestId('invalidate-with-partial-input'));
// 1 & 2 should become stale straight after the click by fuzzy matching the query, 3 should not
await waitFor(() => {
expect(utils.container).toHaveTextContent(`mockPostQuery1:stale`);
expect(utils.container).toHaveTextContent(`mockPostQuery2:stale`);
expect(utils.container).toHaveTextContent(`mockPostQuery3:not-stale`);
});
});
});
test('predicate type should be narrowed', () => {
const { trpc } = factory;
() => {
const utils = trpc.useUtils();
// simple
utils.postById.invalidate('123', {
predicate: (query) => {
expectTypeOf(query.queryKey).toEqualTypeOf<
[string[], { input?: string; type: 'query' }?]
>();
return true;
},
});
// no cursor on infinite
utils.paginatedPosts.invalidate(undefined, {
predicate: (query) => {
expectTypeOf(query.queryKey).toEqualTypeOf<
[
string[],
{
input?: { limit?: number | undefined } | void;
type: 'infinite';
}?,
]
>();
return true;
},
});
// nested deep partial
utils.getMockPostByContent.invalidate(undefined, {
predicate: (query) => {
expectTypeOf(query.queryKey).toEqualTypeOf<
[
string[],
{
input?: {
id?: string;
content?: { language?: string; type?: string };
title?: string;
};
type: 'query';
}?,
]
>();
return true;
},
});
return null;
};
});
|
5,254 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/invalidateRouters.test.tsx | import { ignoreErrors } from '../___testHelpers';
import { getServerAndReactClient } from './__reactHelpers';
import { useIsFetching } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React from 'react';
import { z } from 'zod';
export type Post = {
id: string;
title: string;
createdAt: number;
};
const ctx = konn()
.beforeEach(() => {
/**
* An object of Vitest functions we can use to track how many times things
* have been called during invalidation etc.
*/
const resolvers = {
user: {
listAll: vi.fn(),
byId: {
'1': vi.fn(),
'2': vi.fn(),
},
details: {
getByUserId: {
'1': vi.fn(),
'2': vi.fn(),
},
},
},
'user.current.email.getMain': vi.fn(),
posts: {
getAll: vi.fn(),
getAllInfinite: vi.fn(),
byId: {
'1': vi.fn(),
'2': vi.fn(),
},
'comments.getById': {
1: vi.fn(),
2: vi.fn(),
},
},
};
const db: {
posts: Post[];
} = {
posts: [
{ id: '1', title: 'first post', createdAt: 0 },
{ id: '2', title: 'second post', createdAt: 1 },
],
};
const t = initTRPC.create({
errorFormatter({ shape }) {
return {
...shape,
data: {
...shape.data,
},
};
},
});
const appRouter = t.router({
user: t.router({
listAll: t.procedure.query(() => {
resolvers.user.listAll();
return 'user.listAll' as const;
}),
// A procedure and a sub router defined procedure that also both share
// an input variable.
byId: t.procedure
.input(
z.object({
userId: z.union([z.literal('1'), z.literal('2')]),
}),
)
.query(({ input: { userId } }) => {
resolvers.user.byId[userId]();
return `user.byId[${userId}]` as const;
}),
details: t.router({
getByUserId: t.procedure
.input(
z.object({
userId: z.union([z.literal('1'), z.literal('2')]),
}),
)
.query(({ input: { userId } }) => {
resolvers.user.details.getByUserId[userId]();
return `user.details.getByUserId[${userId}]` as const;
}),
}),
}),
// Add an example top level query defined using `.` to faux being a user sub router.
'user.current.email.getMain': t.procedure
.input(
z.object({
getExtraDetails: z.boolean(),
}),
)
.query(() => {
resolvers['user.current.email.getMain']();
return '[user.current.email.getMain]' as const;
}),
// Another sub router that should not be affected when operating on the
// user router.
posts: t.router({
getAll: t.procedure.query(() => {
resolvers.posts.getAll();
return `posts.getAll` as const;
}),
getAllInfinite: t.procedure
.input(
z.object({
limit: z.number().min(1).max(100).nullish(),
cursor: z.number().nullish(),
}),
)
.query(({ input }) => {
resolvers.posts.getAllInfinite();
const items: typeof db.posts = [];
const limit = input.limit ?? 50;
const { cursor } = input;
let nextCursor: typeof cursor = null;
for (const element of db.posts) {
if (cursor != null && element.createdAt < cursor) {
continue;
}
items.push(element);
if (items.length >= limit) {
break;
}
}
const last = items[items.length - 1];
const nextIndex = db.posts.findIndex((item) => item === last) + 1;
if (db.posts[nextIndex]) {
nextCursor = db.posts[nextIndex]!.createdAt;
}
return {
items,
nextCursor,
};
}),
// Define two procedures that have the same property but different
// types.
byId: t.procedure
.input(
z.object({
id: z.union([z.literal('1'), z.literal('2')]),
}),
)
.query(({ input: { id } }) => {
resolvers.posts.byId[id]();
return `posts.byId[${id}]` as const;
}),
'comments.getById': t.procedure
.input(
z.object({
id: z.union([z.literal(1), z.literal(2)]),
}),
)
.query(({ input: { id } }) => {
resolvers.posts['comments.getById'][id]();
return `posts.[comments.getById][${id}]` as const;
}),
}),
});
return { ...getServerAndReactClient(appRouter), resolvers };
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
/**
* A hook that will subscribe the component to all the hooks for the
* invalidation test.
*/
const useSetupAllTestHooks = (proxy: (typeof ctx)['proxy']) => {
const hooks = {
user: {
listAll: proxy.user.listAll.useQuery(),
byId: {
'1': proxy.user.byId.useQuery({ userId: '1' }),
'2': proxy.user.byId.useQuery({ userId: '2' }),
},
details: {
getByUserId: {
'1': proxy.user.details.getByUserId.useQuery({ userId: '1' }),
'2': proxy.user.details.getByUserId.useQuery({ userId: '2' }),
},
},
},
'user.current.email.getMain': proxy['user.current.email.getMain'].useQuery({
getExtraDetails: false,
}), // Really not a fan of allowing `.` in property names...
posts: {
getAll: proxy.posts.getAll.useQuery(),
getAllInfinite: proxy.posts.getAllInfinite.useInfiniteQuery({
limit: 1,
}),
byId: {
'1': proxy.posts.byId.useQuery({ id: '1' }),
'2': proxy.posts.byId.useQuery({ id: '2' }),
},
'comments.getById': {
1: proxy.posts['comments.getById'].useQuery({ id: 1 }),
2: proxy.posts['comments.getById'].useQuery({ id: 2 }),
},
},
};
return {
hooks,
};
};
//---------------------------------------------------------------------------------------------------
test('Check invalidation of Whole router', async () => {
const { proxy, App, resolvers } = ctx;
function MyComponent() {
useSetupAllTestHooks(ctx.proxy);
const isFetching = useIsFetching();
const utils = proxy.useUtils();
return (
<div>
{isFetching ? (
<p>{`Still fetching ${isFetching} queries`}</p>
) : (
<p>All queries finished fetching!</p>
)}
<button
data-testid="invalidate-user-router"
onClick={() => {
utils.user.invalidate();
}}
/>
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`All queries finished fetching!`);
});
await userEvent.click(utils.getByTestId('invalidate-user-router'));
await waitFor(() => {
expect(utils.container).toHaveTextContent(`All queries finished fetching!`);
});
// Invalidated!
expect(resolvers.user.byId[1]).toHaveBeenCalledTimes(2);
expect(resolvers.user.byId[2]).toHaveBeenCalledTimes(2);
expect(resolvers.user.details.getByUserId['1']).toHaveBeenCalledTimes(2);
expect(resolvers.user.details.getByUserId['2']).toHaveBeenCalledTimes(2);
expect(resolvers.user.listAll).toHaveBeenCalledTimes(2);
// Notice this one is defined using a `.` key at the top router level and still gets
// invalidated. This is due to React Query keys being split by . so
// `[['user','current','email','getMain']]`
// See: https://github.com/trpc/trpc/pull/2713#issuecomment-1249121655
// and: https://github.com/trpc/trpc/issues/2737
expect(resolvers['user.current.email.getMain']).toHaveBeenCalledTimes(2);
// Untouched!
expect(resolvers.posts.byId[1]).toHaveBeenCalledTimes(1);
expect(resolvers.posts.byId[2]).toHaveBeenCalledTimes(1);
expect(resolvers.posts['comments.getById'][1]).toHaveBeenCalledTimes(1);
expect(resolvers.posts['comments.getById'][2]).toHaveBeenCalledTimes(1);
expect(resolvers.posts.getAll).toHaveBeenCalledTimes(1);
expect(resolvers.posts.getAllInfinite).toHaveBeenCalledTimes(1);
});
//---------------------------------------------------------------------------------------------------
test('Check invalidating at router root invalidates all', async () => {
const { proxy, App, resolvers } = ctx;
function MyComponent() {
useSetupAllTestHooks(ctx.proxy);
const isFetching = useIsFetching();
const utils = proxy.useUtils();
return (
<div>
{isFetching ? (
<p>{`Still fetching ${isFetching} queries`}</p>
) : (
<p>All queries finished fetching!</p>
)}
<button
data-testid="invalidate-all"
onClick={() => {
utils.invalidate();
}}
/>
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`All queries finished fetching!`);
});
await userEvent.click(utils.getByTestId('invalidate-all'));
await waitFor(() => {
expect(utils.container).toHaveTextContent(`All queries finished fetching!`);
});
// Invalidated!
expect(resolvers.user.byId[1]).toHaveBeenCalledTimes(2);
expect(resolvers.user.byId[2]).toHaveBeenCalledTimes(2);
expect(resolvers.user.details.getByUserId['1']).toHaveBeenCalledTimes(2);
expect(resolvers.user.details.getByUserId['2']).toHaveBeenCalledTimes(2);
expect(resolvers.user.listAll).toHaveBeenCalledTimes(2);
expect(resolvers['user.current.email.getMain']).toHaveBeenCalledTimes(2);
expect(resolvers.posts.byId[1]).toHaveBeenCalledTimes(2);
expect(resolvers.posts.byId[2]).toHaveBeenCalledTimes(2);
expect(resolvers.posts['comments.getById'][1]).toHaveBeenCalledTimes(2);
expect(resolvers.posts['comments.getById'][2]).toHaveBeenCalledTimes(2);
expect(resolvers.posts.getAll).toHaveBeenCalledTimes(2);
// Invalidate should invalidate infinite queries as well as normal queries
expect(resolvers.posts.getAllInfinite).toHaveBeenCalledTimes(2);
});
//---------------------------------------------------------------------------------------------------
test('test TS types of the input variable', async () => {
const { proxy, App, resolvers } = ctx;
function MyComponent() {
useSetupAllTestHooks(ctx.proxy);
const isFetching = useIsFetching();
const utils = proxy.useUtils();
ignoreErrors(() => {
// @ts-expect-error from user.details should not see id from `posts.byid`
utils.user.details.getByUserId.invalidate({ id: '2' });
});
return (
<div>
{isFetching ? (
<p>{`Still fetching ${isFetching} queries`}</p>
) : (
<p>All queries finished fetching!</p>
)}
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`All queries finished fetching!`);
});
// No invalidation actually occurred.
expect(resolvers.user.byId[1]).toHaveBeenCalledTimes(1);
expect(resolvers.user.details.getByUserId['1']).toHaveBeenCalledTimes(1);
expect(resolvers.user.byId[2]).toHaveBeenCalledTimes(1);
expect(resolvers.user.details.getByUserId['2']).toHaveBeenCalledTimes(1);
expect(resolvers.user.listAll).toHaveBeenCalledTimes(1);
expect(resolvers['user.current.email.getMain']).toHaveBeenCalledTimes(1);
expect(resolvers.posts.byId[1]).toHaveBeenCalledTimes(1);
expect(resolvers.posts.byId[2]).toHaveBeenCalledTimes(1);
expect(resolvers.posts['comments.getById'][1]).toHaveBeenCalledTimes(1);
expect(resolvers.posts['comments.getById'][2]).toHaveBeenCalledTimes(1);
expect(resolvers.posts.getAll).toHaveBeenCalledTimes(1);
});
|
5,255 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/multiple-trpc-providers.test.tsx | import { routerToServerAndClientNew } from '../___testHelpers';
import { createQueryClient } from '../__queryClient';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import { createTRPCReact } from '@trpc/react-query/src';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React, { createContext } from 'react';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouterA = t.router({
serverAQuery: t.procedure.query(() => 'serverA'),
});
const appRouterB = t.router({
serverBQuery: t.procedure.query(() => 'serverB'),
});
const appRouterC = t.router({
serverCQuery: t.procedure.query(() => 'serverC'),
});
return {
A: routerToServerAndClientNew(appRouterA),
B: routerToServerAndClientNew(appRouterB),
C: routerToServerAndClientNew(appRouterC),
};
})
.afterEach(async (ctx) => {
await ctx.A?.close();
await ctx.B?.close();
await ctx.C?.close();
})
.done();
test('multiple trpcProviders', async () => {
const A = (() => {
return {
trpc: createTRPCReact<(typeof ctx)['A']['router']>({
// No custom context defined -- will use default
}),
queryClient: createQueryClient(),
reactQueryContext: undefined,
};
})();
const B = (() => {
const reactQueryContext = createContext<QueryClient | undefined>(undefined);
return {
trpc: createTRPCReact<(typeof ctx)['B']['router']>({
context: createContext(null),
reactQueryContext,
}),
reactQueryContext,
queryClient: createQueryClient(),
};
})();
const C = (() => {
const reactQueryContext = createContext<QueryClient | undefined>(undefined);
return {
trpc: createTRPCReact<(typeof ctx)['C']['router']>({
context: createContext(null),
reactQueryContext,
}),
reactQueryContext,
queryClient: createQueryClient(),
};
})();
function MyComponent() {
const queryA = A.trpc.serverAQuery.useQuery();
const queryB = B.trpc.serverBQuery.useQuery();
const queryC = C.trpc.serverCQuery.useQuery();
return (
<ul>
<li>A:{queryA.data}</li>
<li>B:{queryB.data}</li>
<li>C:{queryC.data}</li>
</ul>
);
}
function App() {
return (
<A.trpc.Provider queryClient={A.queryClient} client={ctx.A.client}>
<QueryClientProvider
client={A.queryClient}
context={A.reactQueryContext}
>
<B.trpc.Provider queryClient={B.queryClient} client={ctx.B.client}>
<QueryClientProvider
client={B.queryClient}
context={B.reactQueryContext}
>
<C.trpc.Provider
queryClient={C.queryClient}
client={ctx.C.client}
>
<QueryClientProvider
client={C.queryClient}
context={C.reactQueryContext}
>
<MyComponent />
</QueryClientProvider>
</C.trpc.Provider>
</QueryClientProvider>
</B.trpc.Provider>
</QueryClientProvider>
</A.trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('A:serverA');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('B:serverB');
});
await waitFor(() => {
expect(utils.container).toHaveTextContent('C:serverC');
});
});
|
5,256 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/mutationkey.test.tsx | import { getServerAndReactClient } from './__reactHelpers';
import { useIsMutating, useQueryClient } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
import React from 'react';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
post: t.router({
create: t.procedure.mutation(() => 'ok' as const),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
describe('mutation keys', () => {
test('can grab from cache using correct key', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const postCreate = proxy.post.create.useMutation();
const mutationKey = [['post', 'create']]; // TODO: Maybe add a getter later?
const isMutating = useIsMutating({ mutationKey });
const queryClient = useQueryClient();
const mutationCache = queryClient.getMutationCache();
React.useEffect(() => {
postCreate.mutate();
const mutation = mutationCache.find({ mutationKey });
expect(mutation).not.toBeUndefined();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div>
<button
onClick={() => {
postCreate.mutate();
}}
data-testid="mutate"
/>
<pre data-testid="status">{isMutating}</pre>
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
// should be mutating due to effect
await waitFor(() => {
expect(utils.getByTestId('status')).toHaveTextContent('1');
});
// let the mutation finish
await waitFor(() => {
expect(utils.getByTestId('status')).toHaveTextContent('0');
});
// should be mutating after button press
await userEvent.click(utils.getByTestId('mutate'));
await waitFor(() => {
expect(utils.getByTestId('status')).toHaveTextContent('1');
});
});
});
|
5,257 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/overrides.test.tsx | import { routerToServerAndClientNew } from '../___testHelpers';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createTRPCReact } from '@trpc/react-query';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
import React, { ReactNode } from 'react';
import { z } from 'zod';
describe('mutation override', () => {
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
interface Post {
title: string;
}
const onSuccessSpy = vi.fn();
const posts: Post[] = [];
const appRouter = t.router({
list: t.procedure.query(() => posts),
add: t.procedure.input(z.string()).mutation(({ input }) => {
posts.push({
title: input,
});
}),
});
const opts = routerToServerAndClientNew(appRouter);
const trpc = createTRPCReact<typeof appRouter>({
overrides: {
useMutation: {
async onSuccess(opts) {
if (!opts.meta.skipInvalidate) {
await opts.originalFn();
await opts.queryClient.invalidateQueries();
}
onSuccessSpy(opts);
},
},
},
});
const queryClient = new QueryClient();
function App(props: { children: ReactNode }) {
return (
<trpc.Provider {...{ queryClient, client: opts.client }}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</trpc.Provider>
);
}
return {
...opts,
App,
trpc,
onSuccessSpy,
};
})
.afterEach(async (opts) => {
await opts?.close?.();
})
.done();
test('clear cache on every mutation', async () => {
const { trpc } = ctx;
const nonce = `nonce-${Math.random()}`;
function MyComp() {
const listQuery = trpc.list.useQuery();
const mutation = trpc.add.useMutation();
return (
<>
<button
onClick={() => {
mutation.mutate(nonce);
}}
data-testid="add"
>
add
</button>
<pre>{JSON.stringify(listQuery.data ?? null, null, 4)}</pre>
</>
);
}
const $ = render(
<ctx.App>
<MyComp />
</ctx.App>,
);
await userEvent.click($.getByTestId('add'));
await waitFor(() => {
expect($.container).toHaveTextContent(nonce);
});
});
test('skip invalidate', async () => {
const { trpc } = ctx;
const nonce = `nonce-${Math.random()}`;
function MyComp() {
const listQuery = trpc.list.useQuery();
const mutation = trpc.add.useMutation({
meta: {
skipInvalidate: true,
},
});
return (
<>
<button
onClick={() => {
mutation.mutate(nonce);
}}
data-testid="add"
>
add
</button>
<pre>{JSON.stringify(listQuery.data ?? null, null, 4)}</pre>
</>
);
}
const $ = render(
<ctx.App>
<MyComp />
</ctx.App>,
);
await userEvent.click($.getByTestId('add'));
await waitFor(() => {
expect(ctx.onSuccessSpy).toHaveBeenCalledTimes(1);
});
expect(ctx.onSuccessSpy.mock.calls[0]![0]!.meta).toMatchInlineSnapshot(`
Object {
"skipInvalidate": true,
}
`);
await waitFor(() => {
expect($.container).not.toHaveTextContent(nonce);
});
});
});
|
5,260 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/polymorphism.test.tsx | /*
It's common to have a data interface which is used across multiple routes in an API,
for instance a shared CSV Export system which can be applied to multiple entities in an application.
By default this can present a challenge in tRPC clients, because the @trpc/react-query package
produces router interfaces which are not always considered structurally compatible by typescript.
The polymorphism types can be used to generate abstract types which routers sharing a common
interface are compatible with, and allow you to pass around deep router paths to generic components with ease.
*/
import { routerToServerAndClientNew } from '../___testHelpers';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createTRPCReact } from '@trpc/react-query';
import { InferQueryLikeData } from '@trpc/react-query/shared';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
import React, { ReactNode, useState } from 'react';
import { z } from 'zod';
/**
* We define a router factory which can be used many times.
*
* This also exports types generated by RouterLike and UtilsLike to describe
* interfaces which concrete router instances are compatible with
*/
import * as Factory from './polymorphism.factory';
/**
* We also define a factory which extends from the basic Factory with an entity sub-type and extra procedure
*/
import * as SubTypedFactory from './polymorphism.subtyped-factory';
/**
* The tRPC backend is defined here
*/
function createTRPCApi() {
const t = initTRPC.create();
/**
* Backend data sources.
*
* Here we use a simple array for demonstration, but in practice these might be
* an ORM Repository, a microservice's API Client, etc. Whatever you write your own router factory around.
*/
const IssueExportsProvider: Factory.FileExportStatusType[] = [];
const DiscussionExportsProvider: Factory.FileExportStatusType[] = [];
const PullRequestExportsProvider: SubTypedFactory.SubTypedFileExportStatusType[] =
[];
/**
* Create an AppRouter instance, with multiple routes using the data export interface
*/
const appRouter = t.router({
github: t.router({
issues: t.router({
export: Factory.createExportRoute(
t.router,
t.procedure,
IssueExportsProvider,
),
}),
discussions: t.router({
export: t.mergeRouters(
Factory.createExportRoute(
t.router,
t.procedure,
DiscussionExportsProvider,
),
// We want to be sure that routers with abstract types,
// which then get merged into a larger router, can be used polymorphically
t.router({
someExtraProcedure: t.procedure
.input(z.object({ name: z.string().min(0) }))
.mutation((opts) => {
return 'Hello ' + opts.input.name;
}),
}),
),
}),
pullRequests: t.router({
export: SubTypedFactory.createSubTypedExportRoute(
t.router,
t.procedure,
PullRequestExportsProvider,
),
}),
}),
});
return {
t,
appRouter,
IssueExportsProvider,
DiscussionExportsProvider,
PullRequestExportsProvider,
};
}
describe('polymorphism', () => {
/**
* Test setup
*/
const ctx = konn()
.beforeEach(() => {
const {
appRouter,
IssueExportsProvider,
DiscussionExportsProvider,
PullRequestExportsProvider,
} = createTRPCApi();
const opts = routerToServerAndClientNew(appRouter);
const trpc = createTRPCReact<typeof appRouter>();
const queryClient = new QueryClient();
function App(props: { children: ReactNode }) {
return (
<trpc.Provider {...{ queryClient, client: opts.client }}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</trpc.Provider>
);
}
return {
...opts,
App,
trpc,
IssueExportsProvider,
DiscussionExportsProvider,
PullRequestExportsProvider,
};
})
.afterEach(async (opts) => {
await opts?.close?.();
})
.done();
describe('simple factory', () => {
test('can use a simple factory router with an abstract interface', async () => {
const { trpc } = ctx;
/**
* Can now define page components which re-use functionality from components,
* and pass the specific backend functionality which is needed need
*/
function IssuesExportPage() {
const utils = trpc.useUtils();
const [currentExport, setCurrentExport] = useState<number | null>(null);
return (
<>
<StartExportButton
route={trpc.github.issues.export}
utils={utils.github.issues.export}
onExportStarted={setCurrentExport}
/>
<RefreshExportsListButton
invalidateAll={() => utils.invalidate()}
/>
<ExportStatus
status={trpc.github.issues.export.status}
currentExport={currentExport}
/>
<ExportsList list={trpc.github.issues.export.list} />
</>
);
}
/**
* Test Act & Assertions
*/
const $ = render(
<ctx.App>
<IssuesExportPage />
</ctx.App>,
);
await userEvent.click($.getByTestId('startExportBtn'));
await waitFor(() => {
expect($.container).toHaveTextContent(
'Last Export: `Search for Polymorphism React` (Working)',
);
});
await userEvent.click($.getByTestId('refreshBtn'));
await waitFor(() => {
expect($.container).toHaveTextContent(
'Last Export: `Search for Polymorphism React` (Ready!)',
);
});
});
test('can use the abstract interface with a factory instance which has been merged with some extra procedures', async () => {
const { trpc } = ctx;
function DiscussionsExportPage() {
const utils = trpc.useUtils();
const [currentExport, setCurrentExport] = useState<number | null>(null);
return (
<>
<StartExportButton
route={trpc.github.discussions.export}
utils={utils.github.discussions.export}
onExportStarted={setCurrentExport}
/>
<RefreshExportsListButton
invalidateAll={() => utils.invalidate()}
/>
<ExportStatus
status={trpc.github.discussions.export.status}
currentExport={currentExport}
/>
<ExportsList list={trpc.github.discussions.export.list} />
</>
);
}
/**
* Test Act & Assertions
*/
const $ = render(
<ctx.App>
<DiscussionsExportPage />
</ctx.App>,
);
await userEvent.click($.getByTestId('startExportBtn'));
await waitFor(() => {
expect($.container).toHaveTextContent(
'Last Export: `Search for Polymorphism React` (Working)',
);
});
await userEvent.click($.getByTestId('refreshBtn'));
await waitFor(() => {
expect($.container).toHaveTextContent(
'Last Export: `Search for Polymorphism React` (Ready!)',
);
});
});
});
describe('sub-typed factory', () => {
test('can use a sub-typed factory router with the interfaces from the supertype', async () => {
const { trpc } = ctx;
/**
* Can define page components which operate over interfaces generated by a super-typed router,
* but also extend types and functionality
*/
function PullRequestsExportPage() {
const utils = trpc.useUtils();
const [currentExport, setCurrentExport] = useState<number | null>(null);
return (
<>
{/* Some components may still need to be bespoke... */}
<SubTypedStartExportButton
route={trpc.github.pullRequests.export}
utils={utils.github.pullRequests.export}
onExportStarted={setCurrentExport}
/>
<RefreshExportsListButton
invalidateAll={() => utils.invalidate()}
/>
<RemoveExportButton
remove={trpc.github.pullRequests.export.delete}
utils={utils.github.pullRequests.export}
exportId={currentExport}
/>
{/* ... or you can adapt them to support sub-types */}
<ExportStatus
status={trpc.github.pullRequests.export.status}
currentExport={currentExport}
renderAdditionalFields={(data) => {
return `Description: "${data?.description}"`;
}}
/>
<ExportsList list={trpc.github.pullRequests.export.list} />
</>
);
}
/**
* Test Act & Assertions
*/
const $ = render(
<ctx.App>
<PullRequestsExportPage />
</ctx.App>,
);
await userEvent.click($.getByTestId('startExportBtn'));
await waitFor(() => {
expect($.container).toHaveTextContent(
'Last Export: `Search for Polymorphism React` (Working)',
);
});
await userEvent.click($.getByTestId('refreshBtn'));
await waitFor(() => {
expect($.container).toHaveTextContent(
'Last Export: `Search for Polymorphism React` (Ready!)',
);
});
});
});
});
/**
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* General use components which can consume any matching route interface
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
type StartExportButtonProps = {
route: Factory.ExportRouteLike;
utils: Factory.ExportUtilsLike;
onExportStarted: (id: number) => void;
};
function StartExportButton({
route,
utils,
onExportStarted,
}: StartExportButtonProps) {
const exportStarter = route.start.useMutation({
onSuccess(data) {
onExportStarted(data.id);
utils.invalidate();
},
});
return (
<button
data-testid="startExportBtn"
onClick={() => {
exportStarter.mutateAsync({
filter: 'polymorphism react',
name: 'Search for Polymorphism React',
});
}}
>
Start Export
</button>
);
}
type RemoveExportButtonProps = {
exportId: number | null;
remove: SubTypedFactory.ExportSubTypedRouteLike['delete'];
utils: SubTypedFactory.ExportSubTypesUtilsLike;
};
function RemoveExportButton({
remove,
utils,
exportId,
}: RemoveExportButtonProps) {
const exportDeleter = remove.useMutation({
onSuccess() {
utils.invalidate();
},
});
if (!exportId) {
return null;
}
return (
<button
data-testid="removeExportBtn"
onClick={() => {
exportDeleter.mutateAsync({
id: exportId,
});
}}
>
Remove Export
</button>
);
}
type SubTypedStartExportButtonProps = {
route: SubTypedFactory.ExportSubTypedRouteLike;
utils: SubTypedFactory.ExportSubTypesUtilsLike;
onExportStarted: (id: number) => void;
};
function SubTypedStartExportButton({
route,
utils,
onExportStarted,
}: SubTypedStartExportButtonProps) {
const exportStarter = route.start.useMutation({
onSuccess(data) {
onExportStarted(data.id);
utils.invalidate();
},
});
return (
<button
data-testid="startExportBtn"
onClick={() => {
exportStarter.mutateAsync({
filter: 'polymorphism react',
name: 'Search for Polymorphism React',
description: 'This field is unique to the sub-typed router',
});
}}
>
Start Export
</button>
);
}
type RefreshExportsListButtonProps = {
invalidateAll: () => void;
};
function RefreshExportsListButton({
invalidateAll,
}: RefreshExportsListButtonProps) {
return (
<button
data-testid="refreshBtn"
onClick={() => {
invalidateAll();
}}
>
Refresh
</button>
);
}
type ExportStatusProps<TStatus extends Factory.ExportRouteLike['status']> = {
status: TStatus;
renderAdditionalFields?: (data: InferQueryLikeData<TStatus>) => ReactNode;
currentExport: number | null;
};
function ExportStatus<TStatus extends Factory.ExportRouteLike['status']>({
status,
currentExport,
renderAdditionalFields,
}: ExportStatusProps<TStatus>) {
const exportStatus = status.useQuery(
{ id: currentExport ?? -1 },
{ enabled: currentExport !== null },
);
if (!exportStatus.data) {
return null;
}
return (
<p>
Last Export: `{exportStatus.data?.name}` (
{exportStatus.data.downloadUri ? 'Ready!' : 'Working'})
{renderAdditionalFields?.(exportStatus.data as any)}
</p>
);
}
type ExportsListProps = { list: Factory.ExportRouteLike['list'] };
function ExportsList({ list }: ExportsListProps) {
const exportsList = list.useQuery();
return (
<>
<h4>Downloads:</h4>
<ul>
{exportsList.data
?.map((item) =>
item.downloadUri ? (
<li key={item.id}>
<a href={item.downloadUri ?? '#'}>{item.name}</a>
</li>
) : null,
)
.filter(Boolean)}
</ul>
</>
);
}
|
5,261 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/prefetchQuery.test.tsx | import { createQueryClient } from '../__queryClient';
import { createAppRouter } from './__testHelpers';
import {
dehydrate,
QueryClientProvider,
useQueryClient,
} from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import React, { useEffect, useState } from 'react';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('prefetchQuery()', () => {
test('with input', async () => {
const { trpc, client } = factory;
function MyComponent() {
const [state, setState] = useState<string>('nope');
const utils = trpc.useUtils();
const queryClient = useQueryClient();
useEffect(() => {
async function prefetch() {
await utils.postById.prefetch('1');
setState(JSON.stringify(dehydrate(queryClient)));
}
prefetch();
}, [queryClient, utils]);
return <>{JSON.stringify(state)}</>;
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
});
|
5,262 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/setInfiniteQueryData.test.tsx | import { createQueryClient } from '../__queryClient';
import { createAppRouter } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React, { useState } from 'react';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('setInfiniteQueryData()', () => {
test('with & without callback', async () => {
const { trpc, client } = factory;
function MyComponent() {
const utils = trpc.useUtils();
const allPostsQuery = trpc.paginatedPosts.useInfiniteQuery(
{},
{
enabled: false,
getNextPageParam: (next) => next.nextCursor,
},
);
return (
<>
<pre>
{JSON.stringify(
allPostsQuery.data?.pages.map((p) => p.items) ?? null,
null,
4,
)}
</pre>
<button
data-testid="setInfiniteQueryData"
onClick={async () => {
// Add a new post to the first page (without callback)
utils.paginatedPosts.setInfiniteData(
{},
{
pages: [
{
items: [
{
id: 'id',
title: 'infinitePosts.title1',
createdAt: Date.now(),
},
],
nextCursor: null,
},
],
pageParams: [],
},
);
const newPost = {
id: 'id',
title: 'infinitePosts.title2',
createdAt: Date.now(),
};
// Add a new post to the first page (with callback)
utils.paginatedPosts.setInfiniteData({}, (data) => {
expect(data).not.toBe(undefined);
if (!data) {
return {
pages: [],
pageParams: [],
};
}
return {
...data,
pages: data.pages.map((page) => {
return {
...page,
items: [...page.items, newPost],
};
}),
};
});
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await userEvent.click(utils.getByTestId('setInfiniteQueryData'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('infinitePosts.title1');
expect(utils.container).toHaveTextContent('infinitePosts.title2');
});
});
});
|
5,263 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/setQueryData.test.tsx | import { createQueryClient } from '../__queryClient';
import { createAppRouter } from './__testHelpers';
import { QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React, { useState } from 'react';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
describe('setQueryData()', () => {
test('without & without callback', async () => {
const { trpc, client } = factory;
function MyComponent() {
const utils = trpc.useUtils();
const allPostsQuery = trpc.allPosts.useQuery(undefined, {
enabled: false,
});
const postByIdQuery = trpc.postById.useQuery('1', {
enabled: false,
});
return (
<>
<pre>{JSON.stringify(allPostsQuery.data ?? null, null, 4)}</pre>
<pre>{JSON.stringify(postByIdQuery.data ?? null, null, 4)}</pre>
<button
data-testid="setQueryData"
onClick={async () => {
utils.allPosts.setData(
undefined,
[
{
id: 'id',
title: 'allPost.title',
createdAt: Date.now(),
},
],
undefined,
);
const newPost = {
id: 'id',
title: 'postById.tmp.title',
createdAt: Date.now(),
};
utils.postById.setData('1', (data) => {
expect(data).toBe(undefined);
return newPost;
});
// now it should be set
utils.postById.setData('1', (data) => {
expect(data).toEqual(newPost);
if (!data) {
return newPost;
}
return {
...data,
title: 'postById.title',
};
});
}}
/>
</>
);
}
function App() {
const [queryClient] = useState(() => createQueryClient());
return (
<trpc.Provider {...{ queryClient, client }}>
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
</trpc.Provider>
);
}
const utils = render(<App />);
await userEvent.click(utils.getByTestId('setQueryData'));
await waitFor(() => {
expect(utils.container).toHaveTextContent('allPost.title');
expect(utils.container).toHaveTextContent('postById.title');
});
});
});
|
5,264 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/ssg.test.ts | import { InfiniteData } from '@tanstack/react-query';
import { createServerSideHelpers } from '@trpc/react-query/server';
import { initTRPC } from '@trpc/server/src';
import { z } from 'zod';
const t = initTRPC.create();
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
id: z.string(),
}),
)
.query(() => '__result' as const),
list: t.procedure
.input(
z.object({
cursor: z.string().optional(),
}),
)
.query(() => '__infResult' as const),
}),
});
test('fetch', async () => {
const ssg = createServerSideHelpers({ router: appRouter, ctx: {} });
const post = await ssg.post.byId.fetch({ id: '1' });
expectTypeOf<'__result'>(post);
});
test('fetchInfinite', async () => {
const ssg = createServerSideHelpers({ router: appRouter, ctx: {} });
const post = await ssg.post.list.fetchInfinite({});
expectTypeOf<InfiniteData<'__infResult'>>(post);
expect(post.pages).toStrictEqual(['__infResult']);
});
test('prefetch and dehydrate', async () => {
const ssg = createServerSideHelpers({ router: appRouter, ctx: {} });
await ssg.post.byId.prefetch({ id: '1' });
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('__result');
});
test('prefetchInfinite and dehydrate', async () => {
const ssg = createServerSideHelpers({ router: appRouter, ctx: {} });
await ssg.post.list.prefetchInfinite({});
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('__infResult');
});
|
5,265 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/ssgExternal.test.ts | import { getServerAndReactClient } from './__reactHelpers';
import { InfiniteData } from '@tanstack/react-query';
import { createServerSideHelpers } from '@trpc/react-query/server';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import SuperJSON from 'superjson';
import { z } from 'zod';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
id: z.string(),
}),
)
.query(() => '__result' as const),
list: t.procedure
.input(
z.object({
cursor: z.string().optional(),
}),
)
.query(() => '__infResult' as const),
throwsError: t.procedure.query(() => {
throw new Error('__error');
}),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('fetch', async () => {
const { opts } = ctx;
const ssg = createServerSideHelpers({
client: opts.proxy,
});
const post = await ssg.post.byId.fetch({ id: '1' });
expectTypeOf<'__result'>(post);
});
test('fetchInfinite', async () => {
const { opts } = ctx;
const ssg = createServerSideHelpers({
client: opts.proxy,
});
const post = await ssg.post.list.fetchInfinite({});
expectTypeOf<InfiniteData<'__infResult'>>(post);
expect(post.pages).toStrictEqual(['__infResult']);
});
test('prefetch and dehydrate', async () => {
const { opts } = ctx;
const ssg = createServerSideHelpers({
client: opts.proxy,
});
await ssg.post.byId.prefetch({ id: '1' });
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('__result');
});
test('prefetchInfinite and dehydrate', async () => {
const { opts } = ctx;
const ssg = createServerSideHelpers({
client: opts.proxy,
});
await ssg.post.list.prefetchInfinite({});
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('__infResult');
});
test('prefetch faulty query and dehydrate', async () => {
const { opts } = ctx;
const ssg = createServerSideHelpers({
client: opts.proxy,
transformer: SuperJSON,
});
await ssg.post.throwsError.prefetch();
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('__error');
});
test('prefetch and dehydrate', async () => {
const { opts } = ctx;
const ssg = createServerSideHelpers({
client: ctx.proxy.createClient(opts.trpcClientOptions),
});
await ssg.post.byId.prefetch({ id: '1' });
const data = JSON.stringify(ssg.dehydrate());
expect(data).toContain('__result');
});
|
5,266 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/trpc-options.test.tsx | import { getServerAndReactClient } from './__reactHelpers';
import { render, waitFor } from '@testing-library/react';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React, { useEffect } from 'react';
import { z } from 'zod';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
greeting: t.procedure
.input(
z.object({
id: z.string(),
}),
)
.query(() => '__result' as const),
doSomething: t.procedure
.input(
z.object({
id: z.string(),
}),
)
.mutation(() => '__result' as const),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('useQuery()', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const greetingQuery = proxy.greeting.useQuery(
{
id: '1',
},
{
trpc: {
context: {
foo: 'bar',
},
},
},
);
return <pre>{JSON.stringify(greetingQuery.data ?? 'n/a', null, 4)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__result`);
});
expect(ctx.spyLink).toHaveBeenCalledTimes(1);
const firstCall = ctx.spyLink.mock.calls[0]![0]!;
expect(firstCall.context.foo).toBe('bar');
expect(firstCall).toMatchInlineSnapshot(`
Object {
"context": Object {
"foo": "bar",
},
"id": 1,
"input": Object {
"id": "1",
},
"path": "greeting",
"type": "query",
}
`);
});
test('useMutation()', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const doSomethingMutation = proxy.doSomething.useMutation({
trpc: {
context: {
foo: 'bar',
},
},
});
useEffect(() => {
doSomethingMutation.mutate({
id: '1',
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<pre>{JSON.stringify(doSomethingMutation.data ?? 'n/a', null, 4)}</pre>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__result`);
});
expect(ctx.spyLink).toHaveBeenCalledTimes(1);
const firstCall = ctx.spyLink.mock.calls[0]![0]!;
expect(firstCall.context.foo).toBe('bar');
expect(firstCall).toMatchInlineSnapshot(`
Object {
"context": Object {
"foo": "bar",
},
"id": 1,
"input": Object {
"id": "1",
},
"path": "doSomething",
"type": "mutation",
}
`);
});
|
5,267 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/useMutation.test.tsx | import { getServerAndReactClient } from './__reactHelpers';
import { render, waitFor } from '@testing-library/react';
import { inferReactQueryProcedureOptions } from '@trpc/react-query';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React, { useEffect } from 'react';
import { z } from 'zod';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({
errorFormatter({ shape }) {
return {
...shape,
data: {
...shape.data,
foo: 'bar' as const,
},
};
},
});
const appRouter = t.router({
post: t.router({
create: t.procedure
.input(
z.object({
text: z.string(),
}),
)
.mutation(() => `__mutationResult` as const),
createWithSerializable: t.procedure
.input(
z.object({
text: z.string(),
}),
)
.mutation(({ input }) => ({
id: 1,
text: input.text,
date: new Date(),
})),
}),
/**
* @deprecated
*/
deprecatedRouter: t.router({
/**
* @deprecated
*/
deprecatedProcedure: t.procedure.query(() => '..'),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('useMutation', async () => {
const { App, proxy } = ctx;
function MyComponent() {
const mutation = proxy.post.create.useMutation();
expect(mutation.trpc.path).toBe('post.create');
useEffect(() => {
mutation.mutate({
text: 'hello',
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (!mutation.data) {
return <>...</>;
}
type TData = (typeof mutation)['data'];
expectTypeOf<TData>().toMatchTypeOf<'__mutationResult'>();
return <pre>{JSON.stringify(mutation.data ?? 'n/a', null, 4)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__mutationResult`);
});
});
test('useMutation options inference', () => {
const { appRouter, proxy, App } = ctx;
type ReactQueryProcedure = inferReactQueryProcedureOptions<typeof appRouter>;
type Options = ReactQueryProcedure['post']['createWithSerializable'];
type OptionsRequired = Required<Options>;
type OnSuccessVariables = Parameters<OptionsRequired['onSuccess']>[1];
expectTypeOf<OnSuccessVariables>().toMatchTypeOf<{ text: string }>();
function MyComponent() {
const options: Options = {};
proxy.post.createWithSerializable.useMutation({
...options,
onSuccess: (data) => {
expectTypeOf(data).toMatchTypeOf<{
id: number;
text: string;
date: string;
}>();
},
});
return <></>;
}
render(
<App>
<MyComponent />
</App>,
);
});
|
5,268 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/useQueries.test.tsx | import { getServerAndReactClient } from './__reactHelpers';
import { render, waitFor } from '@testing-library/react';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React from 'react';
import { z } from 'zod';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({
errorFormatter({ shape }) {
return {
...shape,
data: {
...shape.data,
foo: 'bar' as const,
},
};
},
});
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
id: z.string(),
}),
)
.query(({ input }) => `__result${input.id}` as const),
}),
foo: t.procedure.query(() => 'foo' as const),
bar: t.procedure.query(() => 'bar' as const),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('single query', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const results = proxy.useQueries((t) => [
t.post.byId({ id: '1' }),
t.post.byId(
{ id: '1' },
{
select(data) {
return data as Uppercase<typeof data>;
},
},
),
]);
return <pre>{JSON.stringify(results[0].data ?? 'n/a', null, 4)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__result1`);
});
});
test('different queries', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const results = proxy.useQueries((t) => [t.foo(), t.bar()]);
const foo = results[0].data;
const bar = results[1].data;
if (foo && bar) {
expectTypeOf(results[0].data).toEqualTypeOf<'foo'>();
expectTypeOf(results[1].data).toEqualTypeOf<'bar'>();
}
return (
<pre>{JSON.stringify(results.map((v) => v.data) ?? 'n/a', null, 4)}</pre>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`foo`);
expect(utils.container).toHaveTextContent(`bar`);
});
});
test('mapping queries', async () => {
const ids = ['1', '2', '3'];
const { proxy, App } = ctx;
function MyComponent() {
const results = proxy.useQueries((t) =>
ids.map((id) => t.post.byId({ id })),
);
if (results[0]?.data) {
// ^?
expectTypeOf(results[0].data).toEqualTypeOf<`__result${string}`>();
}
return (
<pre>{JSON.stringify(results.map((v) => v.data) ?? 'n/a', null, 4)}</pre>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__result1`);
expect(utils.container).toHaveTextContent(`__result2`);
expect(utils.container).toHaveTextContent(`__result3`);
});
});
test('single query with options', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const results = proxy.useQueries((t) => [
t.post.byId(
{ id: '1' },
{ enabled: false, placeholderData: '__result2' },
),
]);
return <pre>{JSON.stringify(results[0].data ?? 'n/a', null, 4)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__result2`);
});
});
// regression https://github.com/trpc/trpc/issues/4802
test('regression #4802: passes context to links', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const results = proxy.useQueries((t) => [
t.post.byId(
{ id: '1' },
{
trpc: {
context: {
id: '1',
},
},
},
),
t.post.byId(
{ id: '2' },
{
trpc: {
context: {
id: '2',
},
},
},
),
]);
if (results.some((v) => !v.data)) {
return <>...</>;
}
return <pre>{JSON.stringify(results, null, 4)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__result1`);
expect(utils.container).toHaveTextContent(`__result2`);
});
expect(ctx.spyLink).toHaveBeenCalledTimes(2);
const ops = ctx.spyLink.mock.calls.map((it) => it[0]);
expect(ops[0]!.context).toEqual({
id: '1',
});
expect(ops[1]!.context).toEqual({
id: '2',
});
});
|
5,269 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/useQuery.test.tsx | import { getServerAndReactClient } from './__reactHelpers';
import { InfiniteData } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { inferReactQueryProcedureOptions } from '@trpc/react-query';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React, { useEffect } from 'react';
import { z } from 'zod';
const fixtureData = ['1', '2', '3', '4'];
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({
errorFormatter({ shape }) {
return {
...shape,
data: {
...shape.data,
foo: 'bar' as const,
},
};
},
});
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
id: z.string(),
}),
)
.query(() => '__result' as const),
byIdWithSerializable: t.procedure
.input(
z.object({
id: z.string(),
}),
)
.query(() => ({
id: 1,
date: new Date(),
})),
list: t.procedure
.input(
z.object({
cursor: z.number().default(0),
}),
)
.query(({ input }) => {
return {
items: fixtureData.slice(input.cursor, input.cursor + 1),
next:
input.cursor + 1 > fixtureData.length
? undefined
: input.cursor + 1,
};
}),
}),
/**
* @deprecated
*/
deprecatedRouter: t.router({
/**
* @deprecated
*/
deprecatedProcedure: t.procedure.query(() => '..'),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
describe('useQuery()', () => {
test('loading data', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const query1 = proxy.post.byId.useQuery({
id: '1',
});
expect(query1.trpc.path).toBe('post.byId');
// @ts-expect-error Should not exist
proxy.post.byId.useInfiniteQuery;
const utils = proxy.useUtils();
useEffect(() => {
utils.post.byId.invalidate();
// @ts-expect-error Should not exist
utils.doesNotExist.invalidate();
}, [utils]);
if (!query1.data) {
return <>...</>;
}
type TData = (typeof query1)['data'];
expectTypeOf<TData>().toMatchTypeOf<'__result'>();
return <pre>{JSON.stringify(query1.data ?? 'n/a', null, 4)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__result`);
});
});
test('data type without initialData', () => {
const expectation = expectTypeOf(() =>
ctx.proxy.post.byId.useQuery({ id: '1' }),
).returns;
expectation.toMatchTypeOf<{ data: '__result' | undefined }>();
expectation.not.toMatchTypeOf<{ data: '__result' }>();
});
test('data type with initialData', () => {
const expectation = expectTypeOf(() =>
ctx.proxy.post.byId.useQuery(
{ id: '1' },
{
initialData: '__result',
},
),
).returns;
expectation.toMatchTypeOf<{ data: '__result' }>();
expectation.not.toMatchTypeOf<{ data: undefined }>();
});
});
test('useSuspenseQuery()', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const [data, query1] = proxy.post.byId.useSuspenseQuery({
id: '1',
});
expectTypeOf(data).toEqualTypeOf<'__result'>();
type TData = typeof data;
expectTypeOf<TData>().toMatchTypeOf<'__result'>();
expect(data).toBe('__result');
expect(query1.data).toBe('__result');
return <>{query1.data}</>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__result`);
});
});
test('useSuspenseInfiniteQuery()', async () => {
const { App, proxy } = ctx;
function MyComponent() {
const [data, query1] = proxy.post.list.useSuspenseInfiniteQuery(
{},
{
getNextPageParam(lastPage) {
return lastPage.next;
},
},
);
expect(query1.trpc.path).toBe('post.list');
expect(query1.data).not.toBeFalsy();
expect(data).not.toBeFalsy();
type TData = (typeof query1)['data'];
expectTypeOf<TData>().toMatchTypeOf<
InfiniteData<{
items: typeof fixtureData;
next?: number | undefined;
}>
>();
return (
<>
<button
data-testid="fetchMore"
onClick={() => {
query1.fetchNextPage();
}}
>
Fetch more
</button>
<pre>{JSON.stringify(data, null, 4)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`[ "1" ]`);
});
await userEvent.click(utils.getByTestId('fetchMore'));
await waitFor(() => {
expect(utils.container).toHaveTextContent(`[ "1" ]`);
expect(utils.container).toHaveTextContent(`[ "2" ]`);
});
});
test('useInfiniteQuery()', async () => {
const { App, proxy } = ctx;
function MyComponent() {
const query1 = proxy.post.list.useInfiniteQuery(
{},
{
getNextPageParam(lastPage) {
return lastPage.next;
},
},
);
expect(query1.trpc.path).toBe('post.list');
if (!query1.data) {
return <>...</>;
}
type TData = (typeof query1)['data'];
expectTypeOf<TData>().toMatchTypeOf<
InfiniteData<{
items: typeof fixtureData;
next?: number | undefined;
}>
>();
return (
<>
<button
data-testid="fetchMore"
onClick={() => {
query1.fetchNextPage();
}}
>
Fetch more
</button>
<pre>{JSON.stringify(query1.data ?? 'n/a', null, 4)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`[ "1" ]`);
});
await userEvent.click(utils.getByTestId('fetchMore'));
await waitFor(() => {
expect(utils.container).toHaveTextContent(`[ "1" ]`);
expect(utils.container).toHaveTextContent(`[ "2" ]`);
});
});
test('useInfiniteQuery() initialCursor', async () => {
const { App, proxy } = ctx;
function MyComponent() {
const query1 = proxy.post.list.useInfiniteQuery(
{},
{
getNextPageParam(lastPage) {
return lastPage.next;
},
initialCursor: 2,
},
);
expect(query1.trpc.path).toBe('post.list');
if (query1.isLoading || query1.isFetching || !query1.data) {
return <>...</>;
}
type TData = (typeof query1)['data'];
expectTypeOf<TData>().toMatchTypeOf<
InfiniteData<{
items: typeof fixtureData;
next?: number | undefined;
}>
>();
return (
<>
<button
data-testid="fetchMore"
onClick={() => {
query1.fetchNextPage();
}}
>
Fetch more
</button>
<pre>{JSON.stringify(query1.data ?? 'n/a', null, 4)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`[ "3" ]`);
});
await userEvent.click(utils.getByTestId('fetchMore'));
await waitFor(() => {
expect(utils.container).toHaveTextContent(`[ "3" ]`);
expect(utils.container).toHaveTextContent(`[ "4" ]`);
});
});
test('deprecated routers', async () => {
const { proxy, App } = ctx;
function MyComponent() {
// FIXME this should have strike-through
proxy.deprecatedRouter.deprecatedProcedure.useQuery();
return null;
}
render(
<App>
<MyComponent />
</App>,
);
});
test('deprecated routers', async () => {
const { proxy, App } = ctx;
function MyComponent() {
// FIXME this should have strike-through
proxy.deprecatedRouter.deprecatedProcedure.useQuery();
return null;
}
render(
<App>
<MyComponent />
</App>,
);
});
test('useQuery options inference', () => {
const { appRouter, proxy, App } = ctx;
type ReactQueryProcedure = inferReactQueryProcedureOptions<typeof appRouter>;
type Options = ReactQueryProcedure['post']['byIdWithSerializable'];
function MyComponent() {
const options: Options = {};
proxy.post.byIdWithSerializable.useQuery(
{ id: '1' },
{
...options,
onSuccess: (data) => {
expectTypeOf(data).toMatchTypeOf<{
id: number;
date: string;
}>();
},
},
);
return <></>;
}
render(
<App>
<MyComponent />
</App>,
);
});
|
5,270 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/useSubscription.test.tsx | import { EventEmitter } from 'events';
import { getServerAndReactClient } from './__reactHelpers';
import { render, waitFor } from '@testing-library/react';
import { initTRPC } from '@trpc/server/src';
import { observable } from '@trpc/server/src/observable';
import { konn } from 'konn';
import React, { useState } from 'react';
import { z } from 'zod';
const ee = new EventEmitter();
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({
errorFormatter({ shape }) {
return {
...shape,
data: {
...shape.data,
foo: 'bar' as const,
},
};
},
});
const appRouter = t.router({
onEvent: t.procedure.input(z.number()).subscription(({ input }) => {
return observable<number>((emit) => {
const onData = (data: number) => {
emit.next(data + input);
};
ee.on('data', onData);
return () => {
ee.off('data', onData);
};
});
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('useSubscription', async () => {
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const { App, proxy } = ctx;
function MyComponent() {
const [isStarted, setIsStarted] = useState(false);
const [data, setData] = useState<number>();
proxy.onEvent.useSubscription(10, {
enabled: true,
onStarted: () => {
setIsStarted(true);
},
onData: (data) => {
expectTypeOf(data).toMatchTypeOf<number>();
onDataMock(data);
setData(data);
},
onError: onErrorMock,
});
if (!isStarted) {
return <>{'__connecting'}</>;
}
if (!data) {
return <>{'__connected'}</>;
}
return <pre>{`__data:${data}`}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__connecting`);
});
expect(onDataMock).toHaveBeenCalledTimes(0);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__connected`);
});
ee.emit('data', 20);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`__data:30`);
});
expect(onDataMock).toHaveBeenCalledTimes(1);
expect(onErrorMock).toHaveBeenCalledTimes(0);
});
|
5,271 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/useUtils.test.tsx | /* eslint-disable react-hooks/exhaustive-deps */
import { getServerAndReactClient } from './__reactHelpers';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { initTRPC } from '@trpc/server/src/core';
import { konn } from 'konn';
import React, { useEffect, useState } from 'react';
import { z } from 'zod';
type Post = {
id: number;
text: string;
};
const defaultPost = { id: 0, text: 'new post' };
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({
errorFormatter({ shape }) {
return {
...shape,
data: {
...shape.data,
foo: 'bar' as const,
},
};
},
});
const posts: Post[] = [defaultPost];
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
id: z.number(),
}),
)
.query(({ input }) => posts.find((post) => post.id === input.id)),
all: t.procedure.query(() => posts),
list: t.procedure
.input(
z.object({
cursor: z.string().optional(),
}),
)
.query(() => posts),
create: t.procedure
.input(
z.object({
text: z.string(),
}),
)
.mutation(({ input }) => {
const newPost: Post = { id: posts.length, text: input.text };
posts.push(newPost);
return newPost;
}),
}),
greeting: t.router({
get: t.procedure.query(() => 'hello'),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('client query', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const utils = proxy.useUtils();
const [post, setPost] = useState<Post>();
useEffect(() => {
(async () => {
const res = await utils.client.post.byId.query({ id: 0 });
expectTypeOf<Post | undefined>(res);
setPost(res);
})();
}, [utils]);
return <p>{post?.text}</p>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('new post');
});
});
test('client query sad path', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const utils = proxy.useUtils();
const [isError, setIsError] = useState(false);
useEffect(() => {
(async () => {
try {
// @ts-expect-error - byUser does not exist on postRouter
await utils.client.post.byUser.query({ id: 0 });
} catch (e) {
setIsError(true);
}
})();
}, []);
return <p>{isError ? 'Query errored' : "Query didn't error"}</p>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('Query errored');
});
});
test('client mutation', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const utils = proxy.useUtils();
const { data: posts } = proxy.post.all.useQuery();
const [newPost, setNewPost] = useState<Post>();
useEffect(() => {
(async () => {
const newPost = await utils.client.post.create.mutate({
text: 'another post',
});
expectTypeOf<Post | undefined>(newPost);
setNewPost(newPost);
})();
}, []);
return (
<div>
<p data-testid="initial-post">{posts?.[0]?.text}</p>
<p data-testid="newpost">{newPost?.text}</p>
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('initial-post')).toHaveTextContent('new post');
expect(utils.getByTestId('newpost')).toHaveTextContent('another post');
});
});
test('fetch', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const utils = proxy.useUtils();
const [posts, setPosts] = useState<Post[]>([]);
useEffect(() => {
utils.post.all.fetch().then((allPosts) => {
setPosts(allPosts);
});
}, []);
return <p>{posts[0]?.text}</p>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('new post');
});
});
test('prefetch', async () => {
const { proxy, App } = ctx;
const renderProxy = vi.fn();
function Posts() {
const allPosts = proxy.post.all.useQuery();
renderProxy(allPosts.data);
return (
<>
{allPosts.data!.map((post) => {
return <div key={post.id}>{post.text}</div>;
})}
</>
);
}
function MyComponent() {
const utils = proxy.useUtils();
const [hasPrefetched, setHasPrefetched] = useState(false);
useEffect(() => {
utils.post.all.prefetch().then(() => {
setHasPrefetched(true);
});
}, [utils]);
return hasPrefetched ? <Posts /> : null;
}
render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(renderProxy).toHaveBeenNthCalledWith<[Post[]]>(1, [defaultPost]);
});
});
test('invalidate', async () => {
const { proxy, App } = ctx;
const stableProxySpy = vi.fn();
function MyComponent() {
const allPosts = proxy.post.all.useQuery(undefined, {
onSuccess: () => {
stableProxySpy();
},
});
const createPostMutation = proxy.post.create.useMutation();
const utils = proxy.useUtils();
if (!allPosts.data) {
return <>...</>;
}
return (
<>
<button
data-testid="add-post"
onClick={() => {
createPostMutation.mutate(
{ text: 'invalidate' },
{
onSuccess() {
utils.post.all.invalidate();
// @ts-expect-error Should not exist
utils.post.create.invalidate;
},
},
);
}}
/>
{allPosts.isFetching ? 'fetching' : 'done'}
{allPosts.data.map((post) => {
return <div key={post.id}>{post.text}</div>;
})}
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('done');
});
expect(stableProxySpy).toHaveBeenCalledTimes(1);
const addPostButton = await utils.findByTestId('add-post');
await userEvent.click(addPostButton);
await waitFor(() => {
expect(utils.container).toHaveTextContent('invalidate');
});
expect(stableProxySpy).toHaveBeenCalledTimes(2);
});
test('invalidate procedure for both query and infinite', async () => {
const { proxy, App } = ctx;
const invalidateQuerySpy = vi.fn();
const invalidateInfiniteSpy = vi.fn();
function MyComponent() {
const allPostsList = proxy.post.list.useQuery(
{ cursor: undefined },
{
onSuccess: invalidateQuerySpy,
},
);
const allPostsListInfinite = proxy.post.list.useInfiniteQuery(
{ cursor: undefined },
{ onSuccess: invalidateInfiniteSpy },
);
const utils = proxy.useUtils();
return (
<>
<button
data-testid="invalidate-button"
onClick={() => {
utils.post.list.invalidate();
}}
/>
<div data-testid="list-status">
{allPostsList.isFetching || allPostsListInfinite.isFetching
? 'fetching'
: 'done'}
</div>
<div>
{allPostsListInfinite.data?.pages.map((page) => {
return page.map((post) => {
return <div key={post.id}>{post.text}</div>;
});
})}
</div>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('done');
expect(utils.container).toHaveTextContent('new post');
expect(invalidateQuerySpy).toHaveBeenCalledTimes(1);
expect(invalidateInfiniteSpy).toHaveBeenCalledTimes(1);
});
const invalidateButton = await utils.findByTestId('invalidate-button');
await userEvent.click(invalidateButton);
await waitFor(() => {
expect(utils.container).toHaveTextContent('done');
expect(invalidateQuerySpy).toHaveBeenCalledTimes(2);
expect(invalidateInfiniteSpy).toHaveBeenCalledTimes(2);
});
});
test('reset', async () => {
const { proxy, App } = ctx;
const stableProxySpy = vi.fn();
function MyComponent() {
const allPosts = proxy.post.all.useQuery();
const createPostMutation = proxy.post.create.useMutation();
const utils = proxy.useUtils();
useEffect(() => {
stableProxySpy(proxy);
}, []);
if (!allPosts.data) {
return <>...</>;
}
return (
<>
<button
data-testid="add-post"
onClick={() => {
createPostMutation.mutate(
{ text: 'reset' },
{
onSuccess() {
utils.post.all.reset();
},
},
);
}}
/>
{allPosts.data.map((post) => {
return <div key={post.id}>{post.text}</div>;
})}
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
const addPostButton = await utils.findByTestId('add-post');
await userEvent.click(addPostButton);
await waitFor(() => {
expect(utils.container).toHaveTextContent('reset');
});
expect(stableProxySpy).toHaveBeenCalledTimes(1);
});
test('refetch', async () => {
const { proxy, App } = ctx;
const querySuccessSpy = vi.fn();
function MyComponent() {
const utils = proxy.useUtils();
const allPosts = proxy.post.all.useQuery(undefined, {
onSuccess() {
querySuccessSpy();
},
});
useEffect(() => {
if (allPosts.data) {
utils.post.all.refetch();
}
}, [allPosts.data, utils]);
return null;
}
render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(querySuccessSpy).toHaveBeenCalledTimes(2);
});
});
test('setData', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const allPosts = proxy.post.all.useQuery(undefined, { enabled: false });
const utils = proxy.useUtils();
useEffect(() => {
if (!allPosts.data) {
utils.post.all.setData(undefined, [{ id: 0, text: 'setData1' }]);
}
if (allPosts.data) {
utils.post.all.setData(undefined, (prev) => [
...(prev ?? []), // ^?
{ id: 1, text: 'setData2' },
]);
}
}, [allPosts.data]);
if (!allPosts.data) {
return <>...</>;
}
return <>{JSON.stringify(allPosts.data, null, 4)}</>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('setData1');
expect(utils.container).toHaveTextContent('setData2');
expect(utils.container).toMatchInlineSnapshot(`
<div>
[
{
"id": 0,
"text": "setData1"
},
{
"id": 1,
"text": "setData2"
}
]
</div>
`);
});
});
test('setInfiniteData', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const listPosts = proxy.post.list.useInfiniteQuery({}, { enabled: false });
const utils = proxy.useUtils();
useEffect(() => {
if (!listPosts.data) {
utils.post.list.setInfiniteData(
{},
{
pageParams: [{}],
pages: [[{ id: 0, text: 'setInfiniteData1' }]],
},
);
}
if (listPosts.data) {
utils.post.list.setInfiniteData({}, (prev) => {
const data = prev ?? {
pageParams: [],
pages: [],
};
return {
pageParams: [
...data.pageParams,
{
cursor: 1,
},
],
pages: [
...data.pages,
[
{
id: 1,
text: 'setInfiniteData2',
},
],
],
};
});
}
}, [listPosts.data]);
if (!listPosts.data) {
return <>...</>;
}
return <>{JSON.stringify(listPosts.data, null, 4)}</>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('setInfiniteData1');
expect(utils.container).toHaveTextContent('setInfiniteData2');
expect(utils.container).toMatchInlineSnapshot(`
<div>
{
"pageParams": [
{},
{
"cursor": 1
}
],
"pages": [
[
{
"id": 0,
"text": "setInfiniteData1"
}
],
[
{
"id": 1,
"text": "setInfiniteData2"
}
]
]
}
</div>
`);
});
});
test('getData', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const allPosts = proxy.post.all.useQuery();
const [posts, setPosts] = useState<Post[]>([]);
const utils = proxy.useUtils();
useEffect(() => {
if (allPosts.data) {
const getDataPosts = utils.post.all.getData();
if (getDataPosts) {
setPosts(getDataPosts);
}
}
}, [allPosts.data, utils]);
if (!allPosts.data) {
return <>...</>;
}
return (
<>
{posts.map((post) => {
return <div key={post.id}>{post.text}</div>;
})}
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('new post');
});
});
describe('cancel', () => {
test('aborts with utils', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const allPosts = proxy.post.all.useQuery();
const utils = proxy.useUtils();
useEffect(() => {
utils.post.all.cancel();
});
return (
<div>
<p data-testid="data">
{allPosts.data ? 'data loaded' : 'undefined'}
</p>
<p data-testid="isFetching">
{allPosts.isFetching ? 'fetching' : 'idle'}
</p>
<p data-testid="isPaused">
{allPosts.isPaused ? 'paused' : 'not paused'}
</p>
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('data')).toHaveTextContent('undefined');
expect(utils.getByTestId('isFetching')).toHaveTextContent('idle');
expect(utils.getByTestId('isPaused')).toHaveTextContent('paused');
});
});
test('abort query and infinite with utils', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const allList = proxy.post.list.useQuery({ cursor: '0' });
const allListInfinite = proxy.post.list.useInfiniteQuery({ cursor: '0' });
const utils = proxy.useUtils();
useEffect(() => {
utils.post.list.cancel();
});
return (
<div>
<p data-testid="data">{allList.data ? 'data loaded' : 'undefined'}</p>
<p data-testid="isFetching">
{allList.isFetching ? 'fetching' : 'idle'}
</p>
<p data-testid="isPaused">
{allList.isPaused ? 'paused' : 'not paused'}
</p>
<p data-testid="dataInfinite">
{allListInfinite.data ? 'data loaded' : 'undefined'}
</p>
<p data-testid="isFetchingInfinite">
{allListInfinite.isFetching ? 'fetching' : 'idle'}
</p>
<p data-testid="isPausedInfinite">
{allListInfinite.isPaused ? 'paused' : 'not paused'}
</p>
</div>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.getByTestId('data')).toHaveTextContent('undefined');
expect(utils.getByTestId('isFetching')).toHaveTextContent('idle');
expect(utils.getByTestId('isPaused')).toHaveTextContent('paused');
expect(utils.getByTestId('dataInfinite')).toHaveTextContent('undefined');
expect(utils.getByTestId('isFetchingInfinite')).toHaveTextContent('idle');
expect(utils.getByTestId('isPausedInfinite')).toHaveTextContent('paused');
});
});
test('typeerrors and continues with signal', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const ac = new AbortController();
const allPosts = proxy.post.all.useQuery(undefined, {
// @ts-expect-error Signal not allowed for React Query. We use the internal signal instead
trpc: { signal: ac.signal },
});
// this is not how you cancel a query in @trpc/react-query, so query should still be valid
ac.abort();
if (!allPosts.data) {
return <>...</>;
}
return (
<ul>
{allPosts.data.map((post) => (
<li key={post.id}>{post.text}</li>
))}
</ul>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('new post');
});
});
});
describe('query keys are stored separately', () => {
test('getInfiniteData() does not data from useQuery()', async () => {
const { proxy, App } = ctx;
const unset = '__unset' as const;
const data = {
infinite: unset as unknown,
query: unset as unknown,
};
function MyComponent() {
const utils = proxy.useUtils();
const { data: posts } = proxy.post.all.useQuery(undefined, {
onSuccess() {
data.infinite = utils.post.all.getInfiniteData();
data.query = utils.post.all.getData();
},
});
return (
<div>
<p data-testid="initial-post">{posts?.[0]?.text}</p>
</div>
);
}
render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(data.infinite).not.toBe(unset);
expect(data.query).not.toBe(unset);
});
expect(data.query).toMatchInlineSnapshot(`
Array [
Object {
"id": 0,
"text": "new post",
},
]
`);
expect(data.infinite).toBeUndefined();
});
});
|
5,272 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/react/withTRPC.test.tsx | /* eslint-disable @typescript-eslint/ban-ts-comment */
import { createAppRouter } from './__testHelpers';
import { DehydratedState } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import { withTRPC } from '@trpc/next/src';
import { konn } from 'konn';
import { AppType, NextPageContext } from 'next/dist/shared/lib/utils';
import React from 'react';
import { afterEach, beforeEach, expect, vitest } from 'vitest';
const ctx = konn()
.beforeEach(() => createAppRouter())
.afterEach((ctx) => ctx?.close?.())
.done();
describe('withTRPC()', () => {
test('useQuery', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).toHaveTextContent('first post');
});
describe('NextPageContext conditional ssr', async () => {
test('useQuery: conditional ssr', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const mockContext = {
pathname: '/',
query: {},
} as NextPageContext;
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: ({ ctx }) => {
return ctx?.pathname === '/';
},
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
ctx: mockContext,
} as any);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).toHaveTextContent('first post');
});
test('useQuery: should not ssr when conditional function throws', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const mockContext = {
pathname: '/',
query: {},
} as NextPageContext;
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: () => {
throw new Error('oops');
},
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
ctx: mockContext,
} as any);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).not.toHaveTextContent('first post');
});
test('useQuery: conditional ssr false', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const mockContext = {
pathname: '/',
query: {},
} as NextPageContext;
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: ({ ctx }) => {
return ctx?.pathname === '/not-matching-path';
},
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
ctx: mockContext,
} as any);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).not.toHaveTextContent('first post');
});
test('useQuery: async conditional ssr with delay', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const mockContext = {
pathname: '/',
query: {},
} as NextPageContext;
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: async ({ ctx }) => {
await new Promise((resolve) => setTimeout(resolve, 100));
return ctx?.pathname === '/';
},
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
ctx: mockContext,
} as any);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).toHaveTextContent('first post');
}, 7000); // increase the timeout just for this test
test('browser render', async () => {
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: async () => {
return true;
},
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
const utils = render(<Wrapped {...props} />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
test('useInfiniteQuery with ssr: false in query but conditional ssr returns true', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.paginatedPosts.useInfiniteQuery(
{
limit: 10,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
trpc: {
ssr: false,
},
},
);
return <>{JSON.stringify(query.data ?? query.error)}</>;
};
const mockContext = {
pathname: '/',
query: {},
} as NextPageContext;
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: async ({ ctx }) => {
return ctx?.pathname === '/';
},
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
ctx: mockContext,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).not.toHaveTextContent('first post');
// should eventually be fetched
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
}, 20000);
test('ssr function not called on browser render', async () => {
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const ssrFn = vitest.fn().mockResolvedValue(true);
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: ssrFn,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
const utils = render(<Wrapped {...props} />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
expect(ssrFn).not.toHaveBeenCalled();
});
});
test('useQueries', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const results = trpc.useQueries((t) => {
return [t.allPosts()];
});
return <>{JSON.stringify(results[0].data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
const propsTyped = props as {
pageProps: {
trpcState: DehydratedState;
};
};
const allData = propsTyped.pageProps.trpcState.queries.map((v) => [
v.queryKey,
v.state.data,
]);
expect(allData).toHaveLength(1);
expect(allData).toMatchInlineSnapshot(`
Array [
Array [
Array [
Array [
"allPosts",
],
Object {
"type": "query",
},
],
Array [
Object {
"createdAt": 0,
"id": "1",
"title": "first post",
},
Object {
"createdAt": 1,
"id": "2",
"title": "second post",
},
],
],
]
`);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).toHaveTextContent('first post');
});
test('useInfiniteQuery', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.paginatedPosts.useInfiniteQuery(
{
limit: 10,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
return <>{JSON.stringify(query.data ?? query.error)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).toHaveTextContent('first post');
});
test('browser render', async () => {
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
const utils = render(<Wrapped {...props} />);
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
describe('`ssr: false` on query', () => {
test('useQuery()', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.allPosts.useQuery(undefined, {
trpc: { ssr: false },
});
return <>{JSON.stringify(query.data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).not.toHaveTextContent('first post');
// should eventually be fetched
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
test('useInfiniteQuery', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query = trpc.paginatedPosts.useInfiniteQuery(
{
limit: 10,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
trpc: {
ssr: false,
},
},
);
return <>{JSON.stringify(query.data ?? query.error)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).not.toHaveTextContent('first post');
// should eventually be fetched
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
});
test('useQuery - ssr batching', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions, createContext } = ctx;
const App: AppType = () => {
const query1 = trpc.postById.useQuery('1');
const query2 = trpc.postById.useQuery('2');
return <>{JSON.stringify([query1.data, query2.data])}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped {...props} />);
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
// confirm we've batched if createContext has only been called once
expect(createContext).toHaveBeenCalledTimes(1);
});
describe('`enabled: false` on query during ssr', () => {
describe('useQuery', () => {
test('queryKey does not change', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query1 = trpc.postById.useQuery('1');
// query2 depends only on query1 status
const query2 = trpc.postById.useQuery('2', {
enabled: query1.status === 'success',
});
return (
<>
<>{JSON.stringify(query1.data)}</>
<>{JSON.stringify(query2.data)}</>
</>
);
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
// when queryKey does not change query2 only fetched in the browser
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
});
test('queryKey changes', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query1 = trpc.postById.useQuery('1');
// query2 depends on data fetched by query1
const query2 = trpc.postById.useQuery(
// workaround of TS requiring a string param
query1.data
? (parseInt(query1.data.id) + 1).toString()
: 'definitely not a post id',
{
enabled: !!query1.data,
},
);
return (
<>
<>{JSON.stringify(query1.data)}</>
<>{JSON.stringify(query2.data)}</>
</>
);
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
// when queryKey changes both queries are fetched on the server
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
});
});
describe('useInfiniteQuery', () => {
test('queryKey does not change', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query1 = trpc.paginatedPosts.useInfiniteQuery(
{ limit: 1 },
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
// query2 depends only on query1 status
const query2 = trpc.paginatedPosts.useInfiniteQuery(
{ limit: 2 },
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: query1.status === 'success',
},
);
return (
<>
<>{JSON.stringify(query1.data)}</>
<>{JSON.stringify(query2.data)}</>
</>
);
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
// when queryKey does not change query2 only fetched in the browser
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).not.toHaveTextContent('second post');
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
});
test('queryKey changes', async () => {
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App: AppType = () => {
const query1 = trpc.paginatedPosts.useInfiniteQuery(
{ limit: 1 },
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
// query2 depends on data fetched by query1
const query2 = trpc.paginatedPosts.useInfiniteQuery(
{ limit: query1.data ? query1.data.pageParams.length + 1 : 0 },
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: query1.status === 'success',
},
);
return (
<>
<>{JSON.stringify(query1.data)}</>
<>{JSON.stringify(query2.data)}</>
</>
);
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
const props = await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
global.window = window;
const utils = render(<Wrapped {...props} />);
// when queryKey changes both queries are fetched on the server
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
expect(utils.container).toHaveTextContent('second post');
});
});
});
});
describe('individual pages', () => {
test('useQuery', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
})(App);
// @ts-ignore
global.window = window;
const utils = render(<Wrapped />);
expect(utils.container).not.toHaveTextContent('first post');
// should eventually be fetched
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
test('useQuery - ssr', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = ctx;
const App = () => {
const query = trpc.allPosts.useQuery();
return <>{JSON.stringify(query.data)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
// @ts-ignore
global.window = window;
// ssr should not work
const utils = render(<Wrapped />);
expect(utils.container).not.toHaveTextContent('first post');
// should eventually be fetched
await waitFor(() => {
expect(utils.container).toHaveTextContent('first post');
});
});
});
});
|
5,273 | 0 | petrpan-code/trpc/trpc/packages/tests/server/react | petrpan-code/trpc/trpc/packages/tests/server/react/deprecated/dehydrate.test.tsx | import { createAppRouter } from '../__testHelpers';
import { createProxySSGHelpers } from '@trpc/react-query/src/ssg';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
test('dehydrate', async () => {
const { db, appRouter } = factory;
const ssg = createProxySSGHelpers({ router: appRouter, ctx: {} });
await ssg.allPosts.prefetch();
await ssg.postById.prefetch('1');
const dehydrated = ssg.dehydrate().queries;
expect(dehydrated).toHaveLength(2);
const [cache, cache2] = dehydrated;
expect(cache!.queryHash).toMatchInlineSnapshot(
`"[[\\"allPosts\\"],{\\"type\\":\\"query\\"}]"`,
);
expect(cache!.queryKey).toMatchInlineSnapshot(`
Array [
Array [
"allPosts",
],
Object {
"type": "query",
},
]
`);
expect(cache!.state.data).toEqual(db.posts);
expect(cache2!.state.data).toMatchInlineSnapshot(`
Object {
"createdAt": 0,
"id": "1",
"title": "first post",
}
`);
});
|
5,274 | 0 | petrpan-code/trpc/trpc/packages/tests/server/react | petrpan-code/trpc/trpc/packages/tests/server/react/deprecated/overrides.test.tsx | import { routerToServerAndClientNew } from '../../___testHelpers';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createTRPCReact } from '@trpc/react-query';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
import React, { ReactNode } from 'react';
import { z } from 'zod';
describe('mutation override', () => {
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
interface Post {
title: string;
}
const onSuccessSpy = vi.fn();
const posts: Post[] = [];
const appRouter = t.router({
list: t.procedure.query(() => posts),
add: t.procedure.input(z.string()).mutation(({ input }) => {
posts.push({
title: input,
});
}),
});
const opts = routerToServerAndClientNew(appRouter);
const trpc = createTRPCReact<typeof appRouter>({
unstable_overrides: {
useMutation: {
async onSuccess(opts) {
if (!opts.meta.skipInvalidate) {
await opts.originalFn();
await opts.queryClient.invalidateQueries();
}
onSuccessSpy(opts);
},
},
},
});
const queryClient = new QueryClient();
function App(props: { children: ReactNode }) {
return (
<trpc.Provider {...{ queryClient, client: opts.client }}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</trpc.Provider>
);
}
return {
...opts,
App,
trpc,
onSuccessSpy,
};
})
.afterEach(async (opts) => {
await opts?.close?.();
})
.done();
test('clear cache on every mutation', async () => {
const { trpc } = ctx;
const nonce = `nonce-${Math.random()}`;
function MyComp() {
const listQuery = trpc.list.useQuery();
const mutation = trpc.add.useMutation();
return (
<>
<button
onClick={() => {
mutation.mutate(nonce);
}}
data-testid="add"
>
add
</button>
<pre>{JSON.stringify(listQuery.data ?? null, null, 4)}</pre>
</>
);
}
const $ = render(
<ctx.App>
<MyComp />
</ctx.App>,
);
await userEvent.click($.getByTestId('add'));
await waitFor(() => {
expect($.container).toHaveTextContent(nonce);
});
});
test('skip invalidate', async () => {
const { trpc } = ctx;
const nonce = `nonce-${Math.random()}`;
function MyComp() {
const listQuery = trpc.list.useQuery();
const mutation = trpc.add.useMutation({
meta: {
skipInvalidate: true,
},
});
return (
<>
<button
onClick={() => {
mutation.mutate(nonce);
}}
data-testid="add"
>
add
</button>
<pre>{JSON.stringify(listQuery.data ?? null, null, 4)}</pre>
</>
);
}
const $ = render(
<ctx.App>
<MyComp />
</ctx.App>,
);
await userEvent.click($.getByTestId('add'));
await waitFor(() => {
expect(ctx.onSuccessSpy).toHaveBeenCalledTimes(1);
});
expect(ctx.onSuccessSpy.mock.calls[0]![0]!.meta).toMatchInlineSnapshot(`
Object {
"skipInvalidate": true,
}
`);
await waitFor(() => {
expect($.container).not.toHaveTextContent(nonce);
});
});
});
|
5,275 | 0 | petrpan-code/trpc/trpc/packages/tests/server/react | petrpan-code/trpc/trpc/packages/tests/server/react/regression/issue-1645-setErrorStatusSSR.test.tsx | /* eslint-disable @typescript-eslint/ban-ts-comment */
import { createAppRouter } from '../__testHelpers';
import { withTRPC } from '@trpc/next/src';
import { AppType } from 'next/dist/shared/lib/utils';
import React from 'react';
let factory: ReturnType<typeof createAppRouter>;
beforeEach(() => {
factory = createAppRouter();
});
afterEach(async () => {
await factory.close();
});
/**
* @link https://github.com/trpc/trpc/pull/1645
*/
test('regression: SSR with error sets `status`=`error`', async () => {
// @ts-ignore
const { window } = global;
let queryState: any;
// @ts-ignore
delete global.window;
const { trpc, trpcClientOptions } = factory;
const App: AppType = () => {
// @ts-ignore
const query1 = trpc.bad_useQuery.useQuery();
// @ts-ignore
const query2 = trpc.bad_useInfiniteQuery.useInfiniteQuery();
queryState = {
query1: {
status: query1.status,
error: query1.error,
},
query2: {
status: query2.status,
error: query2.error,
},
};
return <>{JSON.stringify(query1.data || null)}</>;
};
const Wrapped = withTRPC({
config: () => trpcClientOptions,
ssr: true,
})(App);
await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any);
// @ts-ignore
global.window = window;
expect(queryState.query1.error).toMatchInlineSnapshot(
`[TRPCClientError: No "query"-procedure on path "bad_useQuery"]`,
);
expect(queryState.query2.error).toMatchInlineSnapshot(
`[TRPCClientError: No "query"-procedure on path "bad_useInfiniteQuery"]`,
);
expect(queryState.query1.status).toBe('error');
expect(queryState.query2.status).toBe('error');
});
|
5,276 | 0 | petrpan-code/trpc/trpc/packages/tests/server/react | petrpan-code/trpc/trpc/packages/tests/server/react/regression/issue-3461-reserved-properties.test.tsx | import { getServerAndReactClient } from '../__reactHelpers';
import { render } from '@testing-library/react';
import { createTRPCProxyClient } from '@trpc/client';
import { createProxySSGHelpers } from '@trpc/react-query/src/ssg';
import { IntersectionError } from '@trpc/server';
import { initTRPC } from '@trpc/server/src/core';
import React from 'react';
import { z } from 'zod';
test('vanilla client', async () => {
const t = initTRPC.create();
const appRouter = t.router({
links: t.procedure.query(() => 'hello'),
a: t.procedure.query(() => 'a'),
});
const client = createTRPCProxyClient<typeof appRouter>({ links: [] });
expectTypeOf(client).toMatchTypeOf<IntersectionError<'links'>>();
});
test('utils client', async () => {
const t = initTRPC.create();
const appRouter = t.router({
Provider: t.router({
greeting: t.procedure
.input(z.object({ text: z.string().optional() }))
.query(({ input }) => `Hello ${input.text ?? 'world'}`),
}),
a: t.procedure.query(() => 'a'),
});
const { proxy, App } = getServerAndReactClient(appRouter);
function MyComponent() {
expectTypeOf(proxy).toMatchTypeOf<IntersectionError<'Provider'>>();
return null;
}
render(
<App>
<MyComponent />
</App>,
);
});
test('utils client', async () => {
const t = initTRPC.create();
const appRouter = t.router({
client: t.router({
greeting: t.procedure
.input(z.object({ text: z.string().optional() }))
.query(({ input }) => `Hello ${input.text ?? 'world'}`),
}),
});
const { proxy, App } = getServerAndReactClient(appRouter);
function MyComponent() {
const utils = proxy.useContext();
expectTypeOf(utils).toEqualTypeOf<IntersectionError<'client'>>();
return null;
}
render(
<App>
<MyComponent />
</App>,
);
});
test('ssg queryClient', async () => {
const t = initTRPC.create();
const appRouter = t.router({
queryClient: t.router({
greeting: t.procedure
.input(z.object({ text: z.string().optional() }))
.query(({ input }) => `Hello ${input.text ?? 'world'}`),
}),
});
const ssg = createProxySSGHelpers({ router: appRouter, ctx: {} });
expectTypeOf(ssg).toEqualTypeOf<IntersectionError<'queryClient'>>();
});
|
5,277 | 0 | petrpan-code/trpc/trpc/packages/tests/server/react | petrpan-code/trpc/trpc/packages/tests/server/react/regression/issue-4486-initialData-types.test.tsx | import { ignoreErrors } from '../../___testHelpers';
import { getServerAndReactClient } from '../__reactHelpers';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
/**
* For reference,
* @see https://github.com/trpc/trpc/issues/4486
*/
const fixtureData = ['1', '2'];
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
post: t.router({
list: t.procedure.query(() => ({
posts: fixtureData,
foo: 'bar' as const,
})),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
describe('placeholderData', async () => {
test('invalid placeholderData should typeerror', () => {
const { proxy } = ctx;
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
placeholderData() {
return {
barbaz: null,
};
},
});
proxy.post.list.useSuspenseQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
placeholderData() {
return {
barbaz: null,
};
},
});
});
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
placeholderData() {
return 123;
},
});
proxy.post.list.useSuspenseQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
placeholderData() {
return 123;
},
});
});
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
placeholderData: {
// @ts-expect-error can't return data that doesn't match the output type
barbaz: null,
},
});
proxy.post.list.useSuspenseQuery(undefined, {
placeholderData: {
// @ts-expect-error can't return data that doesn't match the output type
barbaz: null,
},
});
});
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
placeholderData: 123,
});
proxy.post.list.useSuspenseQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
placeholderData: 123,
});
});
});
test('good placeholderData does not typeerror', () => {
const { proxy } = ctx;
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
placeholderData() {
return {
posts: [],
foo: 'bar',
};
},
});
proxy.post.list.useSuspenseQuery(undefined, {
placeholderData() {
return {
posts: [],
foo: 'bar',
};
},
});
});
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
placeholderData: {
posts: [],
foo: 'bar',
},
});
proxy.post.list.useSuspenseQuery(undefined, {
placeholderData: {
posts: [],
foo: 'bar',
},
});
});
});
});
describe('initialData', async () => {
test('invalid initialData should typeerror', () => {
const { proxy } = ctx;
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
initialData() {
return {
barbaz: null,
};
},
});
proxy.post.list.useSuspenseQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
initialData() {
return {
barbaz: null,
};
},
});
});
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
initialData() {
return 123;
},
});
proxy.post.list.useSuspenseQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
initialData() {
return 123;
},
});
});
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
initialData: {
// @ts-expect-error can't return data that doesn't match the output type
barbaz: null,
},
});
proxy.post.list.useSuspenseQuery(undefined, {
initialData: {
// @ts-expect-error can't return data that doesn't match the output type
barbaz: null,
},
});
});
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
initialData: 123,
});
proxy.post.list.useSuspenseQuery(undefined, {
// @ts-expect-error can't return data that doesn't match the output type
initialData: 123,
});
});
});
test('good initialData does not typeerror', () => {
const { proxy } = ctx;
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
initialData() {
return {
posts: [],
foo: 'bar',
};
},
});
proxy.post.list.useSuspenseQuery(undefined, {
initialData() {
return {
posts: [],
foo: 'bar',
};
},
});
});
ignoreErrors(() => {
proxy.post.list.useQuery(undefined, {
initialData: {
posts: [],
foo: 'bar',
},
});
proxy.post.list.useSuspenseQuery(undefined, {
initialData: {
posts: [],
foo: 'bar',
},
});
});
});
});
|
5,278 | 0 | petrpan-code/trpc/trpc/packages/tests/server/react | petrpan-code/trpc/trpc/packages/tests/server/react/regression/issue-4519-invalid-select-as-transform.test.tsx | import { getServerAndReactClient } from '../__reactHelpers';
import { render, waitFor } from '@testing-library/react';
import { inferProcedureOutput, initTRPC } from '@trpc/server';
import { konn } from 'konn';
import * as React from 'react';
import * as z from 'zod';
/**
* For reference,
* @see https://github.com/trpc/trpc/issues/4519
*/
const ctx = konn()
.beforeEach(() => {
const { router, procedure } = initTRPC.create();
const appRouter = router({
greeting: procedure
.input(
z.object({
name: z.string().nullish(),
}),
)
.query(({ input }) => {
return {
text: `hello ${input?.name ?? 'world'}`,
};
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('select as transform', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const result = proxy.greeting.useQuery(
{ name: 'foo' },
{
select(data) {
// remap text prop to foo
return { foo: data.text };
},
},
);
if (!result.data) return null;
type AppRouter = typeof ctx.appRouter;
type Data = inferProcedureOutput<AppRouter['greeting']>;
expectTypeOf(result.data).not.toMatchTypeOf<Data>();
expectTypeOf<{ foo: string }>(result.data);
return <pre>{JSON.stringify(result.data)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`{"foo":"hello foo"}`);
});
});
test('select as transform in suspense', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const [data] = proxy.greeting.useSuspenseQuery(
{ name: 'foo' },
{
select(data) {
// remap text prop to foo
return { foo: data.text };
},
},
);
type AppRouter = typeof ctx.appRouter;
type Data = inferProcedureOutput<AppRouter['greeting']>;
expectTypeOf(data).not.toMatchTypeOf<Data>();
expectTypeOf<{ foo: string }>(data);
return <pre>{JSON.stringify(data)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`{"foo":"hello foo"}`);
});
});
test('select as transform with initial data', async () => {
const { proxy, App } = ctx;
function MyComponent() {
// @ts-expect-error - initialData must match the procedure output, not the select
proxy.greeting.useQuery(
{ name: 'foo' },
{
select(data) {
// remap text prop to foo
return { foo: data.text };
},
initialData: {
foo: 'hello foo',
},
},
);
const { data } = proxy.greeting.useQuery(
{ name: 'foo' },
{
select(data) {
// remap text prop to foo
return { foo: data.text };
},
initialData: {
text: 'hello foo',
},
},
);
type AppRouter = typeof ctx.appRouter;
type Data = inferProcedureOutput<AppRouter['greeting']>;
expectTypeOf(data).not.toMatchTypeOf<Data>();
expectTypeOf<{ foo: string }>(data);
return <pre>{JSON.stringify(data)}</pre>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`{"foo":"hello foo"}`);
});
});
|
5,279 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-2506-headers-throwing.test.ts | import { routerToServerAndClientNew, waitError } from '../___testHelpers';
import { httpBatchLink, httpLink, TRPCClientError } from '@trpc/client/src';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import { z } from 'zod';
const t = initTRPC.create();
const appRouter = t.router({
q: t.procedure.input(z.enum(['good', 'bad'])).query(({ input }) => {
if (input === 'bad') {
throw new Error('Bad');
}
return 'good';
}),
});
describe('httpLink', () => {
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
links: [
httpLink({
url: httpUrl,
headers() {
throw new Error('Bad headers fn');
},
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('headers() failure', async () => {
const error = (await waitError(
ctx.proxy.q.query('bad'),
TRPCClientError,
)) as any as TRPCClientError<typeof appRouter>;
expect(error).toMatchInlineSnapshot(`[TRPCClientError: Bad headers fn]`);
});
});
describe('httpBatchLink', () => {
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
links: [
httpBatchLink({
url: httpUrl,
headers() {
throw new Error('Bad headers fn');
},
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('headers() failure', async () => {
const error = (await waitError(
ctx.proxy.q.query('bad'),
TRPCClientError,
)) as any as TRPCClientError<typeof appRouter>;
expect(error).toMatchInlineSnapshot(`[TRPCClientError: Bad headers fn]`);
});
});
|
5,280 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-2540-undefined-mutation.test.ts | // https://github.com/trpc/trpc/issues/2540
import { routerToServerAndClientNew } from '../___testHelpers';
import { httpBatchLink, httpLink } from '@trpc/client/src';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import superjson from 'superjson';
describe('no transformer', () => {
const t = initTRPC.create();
const appRouter = t.router({
goodQuery: t.procedure.query(async () => {
return 'good' as const;
}),
goodMutation: t.procedure.mutation(async () => {
return 'good' as const;
}),
voidQuery: t.procedure.query(async () => {
// void
}),
voidMutation: t.procedure.mutation(async () => {
// void
}),
});
describe('httpLink', () => {
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
links: [
httpLink({
url: httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('query with response: good', async () => {
expect(await ctx.proxy.goodQuery.query()).toBe('good');
});
test('query, void response', async () => {
expect(await ctx.proxy.voidQuery.query()).toBe(undefined);
});
test('mutate with response: good', async () => {
expect(await ctx.proxy.goodMutation.mutate()).toBe('good');
});
test('mutate, void response', async () => {
expect(await ctx.proxy.voidMutation.mutate()).toBe(undefined);
});
});
describe('httpBatchLink', () => {
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
links: [
httpBatchLink({
url: httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('query with response: good', async () => {
expect(await ctx.proxy.goodQuery.query()).toBe('good');
});
test('query, void response', async () => {
expect(await ctx.proxy.voidQuery.query()).toBe(undefined);
});
test('mutate with response: good', async () => {
expect(await ctx.proxy.goodMutation.mutate()).toBe('good');
});
test('mutate, void response', async () => {
expect(await ctx.proxy.voidMutation.mutate()).toBe(undefined);
});
});
describe('httpLink', () => {
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
links: [
httpLink({
url: httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('query with response: good', async () => {
expect(await ctx.proxy.goodQuery.query()).toBe('good');
});
test('query, void response', async () => {
expect(await ctx.proxy.voidQuery.query()).toBe(undefined);
});
test('mutate with response: good', async () => {
expect(await ctx.proxy.goodMutation.mutate()).toBe('good');
});
test('mutate, void response', async () => {
expect(await ctx.proxy.voidMutation.mutate()).toBe(undefined);
});
});
describe('httpBatchLink', () => {
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
links: [
httpBatchLink({
url: httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('query with response: good', async () => {
expect(await ctx.proxy.goodQuery.query()).toBe('good');
});
test('query, void response', async () => {
expect(await ctx.proxy.voidQuery.query()).toBe(undefined);
});
test('mutate with response: good', async () => {
expect(await ctx.proxy.goodMutation.mutate()).toBe('good');
});
test('mutate, void response', async () => {
expect(await ctx.proxy.voidMutation.mutate()).toBe(undefined);
});
});
});
describe('with superjson', () => {
const t = initTRPC.create({
transformer: superjson,
});
const appRouter = t.router({
goodQuery: t.procedure.query(async () => {
return 'good' as const;
}),
goodMutation: t.procedure.mutation(async () => {
return 'good' as const;
}),
voidQuery: t.procedure.query(async () => {
// void
}),
voidMutation: t.procedure.mutation(async () => {
// void
}),
});
describe('httpLink', () => {
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
transformer: superjson,
links: [
httpLink({
url: httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('query with response: good', async () => {
expect(await ctx.proxy.goodQuery.query()).toBe('good');
});
test('query, void response', async () => {
expect(await ctx.proxy.voidQuery.query()).toBe(undefined);
});
test('mutate with response: good', async () => {
expect(await ctx.proxy.goodMutation.mutate()).toBe('good');
});
test('mutate, void response', async () => {
expect(await ctx.proxy.voidMutation.mutate()).toBe(undefined);
});
});
describe('httpBatchLink', () => {
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
transformer: superjson,
links: [
httpBatchLink({
url: httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('query with response: good', async () => {
expect(await ctx.proxy.goodQuery.query()).toBe('good');
});
test('query, void response', async () => {
expect(await ctx.proxy.voidQuery.query()).toBe(undefined);
});
test('mutate with response: good', async () => {
expect(await ctx.proxy.goodMutation.mutate()).toBe('good');
});
test('mutate, void response', async () => {
expect(await ctx.proxy.voidMutation.mutate()).toBe(undefined);
});
});
});
|
5,281 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-2824-createCaller.test.ts | import { routerToServerAndClientNew } from '../___testHelpers';
import * as trpc from '@trpc/server';
import { z } from 'zod';
const ignoreErrors = async (fn: () => Promise<void> | void) => {
try {
await fn();
} catch {
// ignore
}
};
test('createCaller', async () => {
interface Context {
userId: string;
}
const createRouterWithContext = () => trpc.router<Context>();
const createRouter = createRouterWithContext;
const legacyRouter = createRouter()
.mutation('withInput', {
input: z.string(),
resolve: () => 'this is a test',
})
.mutation('noInput', {
resolve: () => 'this is also a test',
});
const router = legacyRouter.interop();
const opts = routerToServerAndClientNew(router);
const caller = opts.router.createCaller({ userId: 'user1' });
expect(
await caller.mutation('withInput', 'hello world'),
).toMatchInlineSnapshot(`"this is a test"`);
expect(await opts.client.mutation('withInput', 'foo')).toMatchInlineSnapshot(
`"this is a test"`,
);
await ignoreErrors(async () => {
// @ts-expect-error this should complain
await caller.mutation('withInput');
// @ts-expect-error this should complain
await caller.mutation('withInput');
await caller.mutation('noInput');
// @ts-expect-error this should complain
await caller.mutation('noInput', 'this has no input');
});
await opts.close();
});
|
5,282 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-2842-createSSGHelpers-promise.test.ts | import '../___packages';
import { createProxySSGHelpers } from '@trpc/react-query/ssg';
import { initTRPC } from '@trpc/server';
test('createSSGPromise', async () => {
const t = initTRPC.create();
const router = t.router({
foo: t.procedure.query(() => 'bar'),
});
async function createSSGProxy() {
return createProxySSGHelpers({
router,
ctx: {},
});
}
const ssg = await createSSGProxy();
const foo = await ssg.foo.fetch();
expect(foo).toBe('bar');
});
|
5,283 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-2856-middleware-infer.test.ts | import '../___packages';
import { initTRPC, TRPCError } from '@trpc/server';
test('middleware next()', async () => {
const t = initTRPC.create();
t.middleware(async (opts) => {
const result = await opts.next();
if (!result.ok) {
expectTypeOf(result.error).toEqualTypeOf<TRPCError>();
}
return result;
});
});
|
5,284 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-2942-useInfiniteQuery-setData.test.tsx | import { getServerAndReactClient } from '../react/__reactHelpers';
import {
dehydrate,
DehydratedState,
InfiniteData,
} from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React from 'react';
import { z } from 'zod';
const fixtureData = ['1', '2'];
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
post: t.router({
list: t.procedure
.input(
z.object({
cursor: z.number().default(0),
foo: z.literal('bar').optional().default('bar'),
}),
)
.query(({ input }) => {
return {
items: fixtureData.slice(input.cursor, input.cursor + 1),
next:
input.cursor + 1 > fixtureData.length
? undefined
: input.cursor + 1,
};
}),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('with input', async () => {
const { App, proxy } = ctx;
function MyComponent() {
const utils = proxy.useContext();
const query1 = proxy.post.list.useInfiniteQuery(
{
foo: 'bar',
},
{
getNextPageParam(lastPage) {
return lastPage.next;
},
},
);
expect(query1.trpc.path).toBe('post.list');
if (!query1.data) {
return <>...</>;
}
type TData = (typeof query1)['data'];
expectTypeOf<TData>().toMatchTypeOf<
InfiniteData<{
items: typeof fixtureData;
next?: number | undefined;
}>
>();
return (
<>
<button
data-testid="setInfinite"
onClick={() => {
utils.post.list.setInfiniteData(
{
foo: 'bar',
},
(data) => data,
);
}}
>
Fetch more
</button>
<pre>{JSON.stringify(query1.data ?? 'n/a', null, 4)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`[ "1" ]`);
});
const before: DehydratedState['queries'] = JSON.parse(
JSON.stringify(dehydrate(ctx.queryClient).queries),
);
await userEvent.click(utils.getByTestId('setInfinite'));
await new Promise((resolve) => setTimeout(resolve, 100));
const after: DehydratedState['queries'] = JSON.parse(
JSON.stringify(dehydrate(ctx.queryClient).queries),
);
{
// Remove update info from diff
for (const value of before) {
value.state.dataUpdateCount = -1;
value.state.dataUpdatedAt = -1;
}
for (const value of after) {
value.state.dataUpdateCount = -1;
value.state.dataUpdatedAt = -1;
}
}
expect(before).toEqual(after);
});
test('w/o input', async () => {
const { App, proxy } = ctx;
function MyComponent() {
const utils = proxy.useContext();
const query1 = proxy.post.list.useInfiniteQuery(
{},
{
getNextPageParam(lastPage) {
return lastPage.next;
},
},
);
expect(query1.trpc.path).toBe('post.list');
if (!query1.data) {
return <>...</>;
}
type TData = (typeof query1)['data'];
expectTypeOf<TData>().toMatchTypeOf<
InfiniteData<{
items: typeof fixtureData;
next?: number | undefined;
}>
>();
return (
<>
<button
data-testid="setInfinite"
onClick={() => {
utils.post.list.setInfiniteData({}, (data) => data);
}}
>
Fetch more
</button>
<pre>{JSON.stringify(query1.data ?? 'n/a', null, 4)}</pre>
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent(`[ "1" ]`);
});
const before: DehydratedState['queries'] = JSON.parse(
JSON.stringify(dehydrate(ctx.queryClient).queries),
);
await userEvent.click(utils.getByTestId('setInfinite'));
await new Promise((resolve) => setTimeout(resolve, 100));
const after: DehydratedState['queries'] = JSON.parse(
JSON.stringify(dehydrate(ctx.queryClient).queries),
);
before.forEach((value) => {
value.state.dataUpdateCount = -1;
value.state.dataUpdatedAt = -1;
});
after.forEach((value) => {
value.state.dataUpdateCount = -1;
value.state.dataUpdatedAt = -1;
});
expect(before).toEqual(after);
});
|
5,285 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-2996-defined-data.test.tsx | import { getServerAndReactClient } from '../react/__reactHelpers';
import { useQuery } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
import React from 'react';
const posts = [
{ id: 1, title: 'foo' },
{ id: 2, title: 'bar' },
];
type Post = (typeof posts)[number];
const fetchPosts = async () => posts;
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
posts: t.procedure.query(fetchPosts),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('destructuring data', async () => {
const { App, proxy } = ctx;
function MyComponent() {
const { data: trpcData = [] } = proxy.posts.useQuery();
expectTypeOf<typeof trpcData>().toEqualTypeOf<Post[]>();
// verify tanstack returns the same
const { data: rqData = [] } = useQuery(['key'], fetchPosts);
expectTypeOf<typeof rqData>().toEqualTypeOf<Post[]>();
if (!trpcData) throw new Error('should not happen');
if (trpcData.length === 0) return <div>No posts</div>;
return <div>{trpcData.map((post) => post.title).join(', ')}</div>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
expect(utils.container).toHaveTextContent('No posts');
await waitFor(() => {
expect(utils.container).toHaveTextContent('foo, bar');
});
});
test('using `initialData`', async () => {
const { App, proxy } = ctx;
function MyComponent() {
const { data: trpcData } = proxy.posts.useQuery(undefined, {
initialData: [],
});
expectTypeOf<typeof trpcData>().toEqualTypeOf<Post[]>();
// verify tanstack returns the same
const { data: rqData } = useQuery(['key'], fetchPosts, {
initialData: [],
});
expectTypeOf<typeof rqData>().toEqualTypeOf<Post[]>();
if (!trpcData) throw new Error('should not happen');
if (trpcData.length === 0) return <div>No posts</div>;
return <div>{trpcData.map((post) => post.title).join(', ')}</div>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
expect(utils.container).toHaveTextContent('No posts');
await waitFor(() => {
expect(utils.container).toHaveTextContent('foo, bar');
});
});
test('using `placeholderData`', async () => {
const { App, proxy } = ctx;
function MyComponent() {
const { data: trpcData } = proxy.posts.useQuery(undefined, {
placeholderData: [],
});
expectTypeOf<typeof trpcData>().toEqualTypeOf<Post[] | undefined>();
// verify tanstack returns the same
const { data: rqData } = useQuery(['key'], fetchPosts, {
placeholderData: [],
});
expectTypeOf<typeof rqData>().toEqualTypeOf<Post[] | undefined>();
if (!trpcData) throw new Error('should not happen');
if (trpcData.length === 0) return <div>No posts</div>;
return <div>{trpcData.map((post) => post.title).join(', ')}</div>;
}
const utils = render(
<App>
<MyComponent />
</App>,
);
expect(utils.container).toHaveTextContent('No posts');
await waitFor(() => {
expect(utils.container).toHaveTextContent('foo, bar');
});
});
|
5,286 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-3085-bad-responses.test.ts | import '../___packages';
import http from 'http';
import { waitError } from '../___testHelpers';
import { createTRPCProxyClient, httpLink, TRPCClientError } from '@trpc/client';
import { observable } from '@trpc/server/observable';
import fetch from 'node-fetch';
import superjson from 'superjson';
type Handler = (opts: {
req: http.IncomingMessage;
res: http.ServerResponse;
}) => void;
function createServer(handler: Handler) {
const server = http.createServer((req, res) => {
handler({ req, res });
});
server.listen(0);
const port = (server.address() as any).port as number;
return {
url: `http://localhost:${port}`,
async close() {
await new Promise((resolve) => {
server.close(resolve);
});
},
};
}
test('badly formatted response', async () => {
const server = createServer(({ res }) => {
res.setHeader('content-type', 'application/json');
res.write(JSON.stringify({}));
res.end();
});
const client: any = createTRPCProxyClient({
links: [
httpLink({
url: server.url,
fetch: fetch as any,
}),
],
});
const error = await waitError(client.test.query(), TRPCClientError);
expect(error).toMatchInlineSnapshot(
`[TRPCClientError: Unable to transform response from server]`,
);
await server.close();
});
test('badly formatted superjson response', async () => {
const server = createServer(({ res }) => {
res.setHeader('content-type', 'application/json');
res.write(
JSON.stringify({
result: {},
}),
);
res.end();
});
const client: any = createTRPCProxyClient({
links: [
httpLink({
url: server.url,
fetch: fetch as any,
}),
],
transformer: superjson,
});
const error = await waitError(client.test.query(), TRPCClientError);
expect(error).toMatchInlineSnapshot(
`[TRPCClientError: Unable to transform response from server]`,
);
await server.close();
});
test('badly formatted superjson response', async () => {
const server = createServer(({ res }) => {
res.setHeader('content-type', 'application/json');
res.write(
JSON.stringify({
result: {},
}),
);
res.end();
});
const client: any = createTRPCProxyClient({
links: [
httpLink({
url: server.url,
fetch: fetch as any,
}),
],
transformer: superjson,
});
const error = await waitError(client.test.query(), TRPCClientError);
expect(error).toMatchInlineSnapshot(
`[TRPCClientError: Unable to transform response from server]`,
);
await server.close();
});
test('bad link', async () => {
const server = createServer(({ res }) => {
res.setHeader('content-type', 'application/json');
res.write(
JSON.stringify({
result: {},
}),
);
res.end();
});
const client: any = createTRPCProxyClient({
links: [
() => (opts) => {
return observable((observer) => {
opts.next(opts.op).subscribe({
...observer,
next() {
throw new Error('whoops');
},
});
});
},
httpLink({
url: server.url,
fetch: fetch as any,
}),
],
});
const error = await waitError(client.test.query(), TRPCClientError);
expect(error).toMatchInlineSnapshot(`[TRPCClientError: whoops]`);
await server.close();
});
|
5,287 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-3351-TRPCError.test.ts | import '../___testHelpers';
import { TRPCError } from '@trpc/server';
test('TRPCError cause', async () => {
const err = new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
});
expect(err.cause).toBeUndefined();
});
|
5,288 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-3359-http-status-413-payload-too-large.test.ts | import http from 'http';
import { waitError } from '../___testHelpers';
import {
createTRPCProxyClient,
httpBatchLink,
httpLink,
TRPCClientError,
} from '@trpc/client';
import fetch from 'node-fetch';
type Handler = (opts: {
req: http.IncomingMessage;
res: http.ServerResponse;
}) => void;
function createServer(handler: Handler) {
const server = http.createServer((req, res) => {
handler({ req, res });
});
server.listen(0);
const address = server.address();
if (!address || typeof address === 'string')
throw new Error('Expected address to be AddressInfo');
const port = address.port;
return {
url: `http://localhost:${port}`,
async close() {
await new Promise((resolve) => {
server.close(resolve);
});
},
};
}
describe('server responds with 413 Payload Too Large', () => {
test('httpLink', async () => {
const server = createServer(({ res }) => {
res.setHeader('content-type', 'application/json');
res.statusCode = 413;
res.statusMessage = 'Payload Too Large';
res.write(
JSON.stringify({
statusCode: 413,
code: 'FST_ERR_CTP_BODY_TOO_LARGE',
error: 'Payload Too Large',
message: 'Request body is too large',
}),
);
res.end();
});
const client: any = createTRPCProxyClient({
links: [
httpLink({
url: server.url,
fetch: fetch as any,
}),
],
});
const error = await waitError(client.test.query(), TRPCClientError);
expect(error).toMatchInlineSnapshot(
'[TRPCClientError: Unable to transform response from server]',
);
expect(error.message).toMatchInlineSnapshot(
'"Unable to transform response from server"',
);
await server.close();
});
test('batchLink', async () => {
const server = createServer(({ res }) => {
res.setHeader('content-type', 'application/json');
res.statusCode = 413;
res.statusMessage = 'Payload Too Large';
res.write(
JSON.stringify({
statusCode: 413,
code: 'FST_ERR_CTP_BODY_TOO_LARGE',
error: 'Payload Too Large',
message: 'Request body is too large',
}),
);
res.end();
});
const client: any = createTRPCProxyClient({
links: [
httpBatchLink({
url: server.url,
fetch: fetch as any,
}),
],
});
const error = await waitError(client.test.query(), TRPCClientError);
expect(error).toMatchInlineSnapshot(
'[TRPCClientError: Unable to transform response from server]',
);
expect(error.message).toMatchInlineSnapshot(
'"Unable to transform response from server"',
);
await server.close();
});
});
|
5,289 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-3453-meta-interface.test.ts | import '../___packages';
import { initTRPC } from '@trpc/server';
test('meta as interface', () => {
interface Meta {
foo: 'bar';
}
initTRPC.meta<Meta>();
});
test('context as interface', () => {
interface Context {
foo: 'bar';
}
initTRPC.context<Context>();
});
test('bad: meta as primitive', () => {
// @ts-expect-error this is not allowed
initTRPC.meta<1>();
});
test('bad: context as primitive', () => {
// @ts-expect-error this is not allowed
initTRPC.context<1>();
});
|
5,290 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-3455-56-invalidate-queries.test.tsx | import { getServerAndReactClient } from '../react/__reactHelpers';
import { useQuery } from '@tanstack/react-query';
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import React from 'react';
import { z } from 'zod';
const post = { id: 1, text: 'foo' };
const posts = [post];
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
id: z.number(),
}),
)
.query(({ input }) => posts.find((post) => post.id === input.id)),
all: t.procedure.query(() => posts),
}),
greeting: t.procedure.query(async () => {
await new Promise((res) => setTimeout(res, 500));
return 'Hello trpc';
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('invalidate with filter', async () => {
const { proxy, App } = ctx;
const greetingSpy = vi.fn();
const postSpy = vi.fn();
function MyComponent() {
const allPosts = proxy.post.all.useQuery(undefined, {
onSuccess: () => postSpy(),
});
const greeting = proxy.greeting.useQuery(undefined, {
onSuccess: () => greetingSpy(),
});
const utils = proxy.useContext();
return (
<>
<button
data-testid="invalidate"
onClick={() => {
utils.invalidate(undefined, {
predicate: (query) => {
return (query.queryKey[0] as string[])[0] === 'post';
},
});
}}
/>
{allPosts.isFetching ? 'posts:fetching' : 'posts:done'}
{allPosts.data?.map((post) => {
return <div key={post.id}>{post.text}</div>;
})}
{greeting.isFetching ? 'greeting:fetching' : 'greeting:done'}
{greeting.data}
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('posts:done');
expect(utils.container).toHaveTextContent('greeting:done');
});
const invalidateButton = await utils.findByTestId('invalidate');
await userEvent.click(invalidateButton);
// post should match the filter and be invalidated
// greeting should not and thus still be done
expect(utils.container).toHaveTextContent('posts:fetching');
expect(utils.container).toHaveTextContent('greeting:done');
await waitFor(() => {
expect(utils.container).toHaveTextContent('posts:done');
expect(utils.container).toHaveTextContent('greeting:done');
});
expect(postSpy).toHaveBeenCalledTimes(2);
expect(greetingSpy).toHaveBeenCalledTimes(1);
});
test('tanstack query queries are invalidated', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const utils = proxy.useContext();
const rqQuery = useQuery(['test'], async () => {
await new Promise((res) => setTimeout(res, 500));
return 'Hello tanstack';
});
const trpcQuery = proxy.greeting.useQuery();
return (
<>
<button data-testid="invalidate" onClick={() => utils.invalidate()} />
{rqQuery.isFetching ? 'rq:fetching' : 'rq:done'}
{trpcQuery.isFetching ? 'trpc:fetching' : 'trpc:done'}
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('rq:done');
expect(utils.container).toHaveTextContent('trpc:done');
});
await userEvent.click(utils.getByTestId('invalidate'));
expect(utils.container).toHaveTextContent('rq:fetching');
expect(utils.container).toHaveTextContent('trpc:fetching');
await waitFor(() => {
expect(utils.container).toHaveTextContent('rq:done');
expect(utils.container).toHaveTextContent('trpc:done');
});
});
test('mixed providers with more "advanced" filter', async () => {
const { proxy, App } = ctx;
function MyComponent() {
const utils = proxy.useContext();
const rqQuery1 = useQuery(
['test', 1],
async () => {
await new Promise((res) => setTimeout(res, 500));
return 'Hello tanstack1';
},
{ retry: false },
);
const rqQuery2 = useQuery(
['test', 2],
async () => {
await new Promise((res) => setTimeout(res, 500));
return 'Hello tanstack2';
},
{ retry: true },
);
const trpcQuery = proxy.greeting.useQuery(undefined, {
retry: false,
});
return (
<>
<button
data-testid="invalidate"
onClick={() => {
utils.invalidate(undefined, {
predicate: (query) => {
// invalidate all queries that have `retry: false`
return query.options.retry === false;
},
});
}}
/>
{rqQuery1.isFetching ? 'rq1:fetching' : 'rq1:done'}
{rqQuery2.isFetching ? 'rq2:fetching' : 'rq2:done'}
{trpcQuery.isFetching ? 'trpc:fetching' : 'trpc:done'}
</>
);
}
const utils = render(
<App>
<MyComponent />
</App>,
);
await waitFor(() => {
expect(utils.container).toHaveTextContent('rq1:done');
expect(utils.container).toHaveTextContent('rq2:done');
expect(utils.container).toHaveTextContent('trpc:done');
});
await userEvent.click(utils.getByTestId('invalidate'));
expect(utils.container).toHaveTextContent('rq1:fetching');
expect(utils.container).toHaveTextContent('rq2:done');
expect(utils.container).toHaveTextContent('trpc:fetching');
await waitFor(() => {
expect(utils.container).toHaveTextContent('rq1:done');
expect(utils.container).toHaveTextContent('rq2:done');
expect(utils.container).toHaveTextContent('trpc:done');
});
});
|
5,291 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4049-stripped-undefined.test.tsx | import { routerToServerAndClientNew } from '../___testHelpers';
import { httpLink } from '@trpc/client/src';
import { createTRPCReact } from '@trpc/react-query';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
describe('undefined on server response is inferred on the client', () => {
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
num: t.procedure.query(() => {
const nums = [1, 2, 3, 4, 5];
const num = nums.find((n) => n === Math.floor(Math.random() * 10));
// ^?
expectTypeOf(num).toEqualTypeOf<number | undefined>();
return num;
}),
obj: t.procedure.query(() => {
const objs = [{ id: 1 } as { id: number | undefined }];
const obj = objs.find((n) => n.id === Math.floor(Math.random() * 5));
// ^?
expectTypeOf(obj).toEqualTypeOf<
{ id: number | undefined } | undefined
>();
return obj;
}),
und: t.procedure.query(() => {
return undefined;
}),
});
return routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
links: [httpLink({ url: httpUrl })],
};
},
});
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('using vanilla client', async () => {
const num = await ctx.proxy.num.query();
expectTypeOf(num).toEqualTypeOf<number | undefined>();
const obj = await ctx.proxy.obj.query();
// key might be stripped entirely 👇, or value should be defined
expectTypeOf(obj).toEqualTypeOf<{ id?: number } | undefined>();
const und = await ctx.proxy.und.query();
expectTypeOf(und).toEqualTypeOf<undefined>();
});
test('using createCaller', async () => {
const router = ctx.router;
const caller = router.createCaller({});
const num = await caller.num();
expectTypeOf(num).toEqualTypeOf<number | undefined>();
const obj = await caller.obj();
// key should not be stripped 👇, since we're not calling JSON.stringify/parse on createCaller, value can be undefined though
expectTypeOf(obj).toEqualTypeOf<{ id: number | undefined } | undefined>();
const und = await caller.und();
expectTypeOf(und).toEqualTypeOf<undefined>();
});
test('using react hooks', async () => {
const hooks = createTRPCReact<typeof ctx.router>();
() => {
const { data: num, isSuccess: numSuccess } = hooks.num.useQuery();
if (numSuccess) expectTypeOf(num).toEqualTypeOf<number | undefined>();
const { data: obj, isSuccess: objSuccess } = hooks.obj.useQuery();
if (objSuccess)
expectTypeOf(obj).toEqualTypeOf<{ id?: number } | undefined>();
const { data: und, isSuccess: undSuccess } = hooks.und.useQuery();
if (undSuccess) expectTypeOf(und).toEqualTypeOf<undefined>();
return null;
};
});
});
|
5,292 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4130-ssr-different-transformers.test.tsx | /* eslint-disable @typescript-eslint/ban-ts-comment */
import { routerToServerAndClientNew } from '../___testHelpers';
import { DehydratedState } from '@tanstack/react-query';
import { createTRPCNext } from '@trpc/next';
import type { CombinedDataTransformer } from '@trpc/server';
import { initTRPC } from '@trpc/server';
import { uneval } from 'devalue';
import { konn } from 'konn';
import { AppType } from 'next/dist/shared/lib/utils';
import React from 'react';
import superjson from 'superjson';
// [...]
export const transformer: CombinedDataTransformer = {
input: superjson,
output: {
serialize: (object) => {
return uneval(object);
},
// This `eval` only ever happens on the **client**
deserialize: (object) => eval(`(${object})`),
},
};
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({
transformer,
});
const appRouter = t.router({
foo: t.procedure.query(() => 'bar' as const),
});
const opts = routerToServerAndClientNew(appRouter, {
client(opts) {
return {
...opts,
transformer,
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('withTRPC - SSR', async () => {
// @ts-ignore
const { window } = global;
// @ts-ignore
delete global.window;
const trpc = createTRPCNext({
config() {
return ctx.trpcClientOptions;
},
ssr: true,
});
const App: AppType = () => {
const query = trpc.foo.useQuery();
return <>{JSON.stringify(query.data ?? null)}</>;
};
const Wrapped = trpc.withTRPC(App);
const props = (await Wrapped.getInitialProps!({
AppTree: Wrapped,
Component: <div />,
} as any)) as any;
const trpcState: DehydratedState = transformer.output.deserialize(
props.pageProps.trpcState,
);
const relevantData = trpcState.queries.map((it) => ({
data: it.state.data,
queryKey: it.queryKey,
}));
expect(relevantData).toMatchInlineSnapshot(`
Array [
Object {
"data": "bar",
"queryKey": Array [
Array [
"foo",
],
Object {
"type": "query",
},
],
},
]
`);
// @ts-ignore
global.window = window;
});
|
5,293 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4217-throw-non-errors.test.ts | import { routerToServerAndClientNew, waitError } from '../___testHelpers';
import { httpLink, TRPCClientError } from '@trpc/client';
import { initTRPC, TRPCError } from '@trpc/server';
import { konn } from 'konn';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
throws: t.procedure.query(() => {
throw {
message: 'Custom error message',
name: 'Third Party API error',
foo: 'bar',
};
}),
});
return routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
links: [httpLink({ url: httpUrl })],
};
},
});
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('preserve `.cause` even on non-error objects', async () => {
type TClientError = TRPCClientError<typeof ctx.router>;
await waitError<TClientError>(() => ctx.proxy.throws.query());
expect(ctx.onError).toHaveBeenCalledTimes(1);
const error = ctx.onError.mock.calls[0]![0]!.error as TRPCError & {
cause: any;
};
expect(error).toMatchInlineSnapshot('[TRPCError: Custom error message]');
expect(error.cause.message).toBe('Custom error message');
expect(error.cause.foo).toBe('bar');
});
|
5,294 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4243-serialize-string.test.ts | import EventEmitter from 'events';
import { initTRPC } from '@trpc/server';
import * as trpcNext from '@trpc/server/src/adapters/next';
import { z } from 'zod';
function mockReq(opts: {
query: Record<string, any>;
headers?: Record<string, string>;
method?:
| 'CONNECT'
| 'DELETE'
| 'GET'
| 'HEAD'
| 'OPTIONS'
| 'POST'
| 'PUT'
| 'TRACE';
body?: any;
parseBody?: boolean;
}) {
const req = new EventEmitter() as any;
req.method = opts.method;
req.query = opts.query;
const headers = opts.headers ?? {};
req.headers = headers;
if (req.method === 'POST') {
if (
'content-type' in headers &&
headers['content-type'] === 'application/json' &&
opts.parseBody
) {
req.body = JSON.parse(opts.body);
} else {
setImmediate(() => {
req.emit('data', opts.body);
req.emit('end');
});
}
}
const socket = {
destroy: vi.fn(),
};
req.socket = socket;
return { req, socket };
}
function mockRes() {
const res = new EventEmitter() as any;
const json = vi.fn(() => res);
const setHeader = vi.fn(() => res);
const end = vi.fn(() => res);
res.json = json;
res.setHeader = setHeader;
res.end = end;
return { res, json, setHeader, end };
}
describe('string inputs are properly serialized and deserialized', () => {
const t = initTRPC.create();
const router = t.router({
doSomething: t.procedure.input(z.string()).mutation((opts) => {
return `did mutate ${opts.input}` as const;
}),
querySomething: t.procedure.input(z.string()).query((opts) => {
return `did query ${opts.input}` as const;
}),
});
const handler = trpcNext.createNextApiHandler({
router,
});
test('mutation', async () => {
const { req } = mockReq({
query: {
trpc: ['doSomething'],
},
headers: {
'content-type': 'application/json',
},
method: 'POST',
body: JSON.stringify('something'),
});
const { res, end } = mockRes();
await handler(req, res);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]);
expect(json).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "did mutate something",
},
}
`);
expect(res.statusCode).toBe(200);
});
});
describe('works good with bodyParser disabled', () => {
const t = initTRPC.create();
const router = t.router({
doSomething: t.procedure.input(z.string()).mutation((opts) => {
return `did mutate ${opts.input}` as const;
}),
querySomething: t.procedure.input(z.string()).query((opts) => {
return `did query ${opts.input}` as const;
}),
});
const handler = trpcNext.createNextApiHandler({
router,
});
test('mutation', async () => {
const { req } = mockReq({
query: {
trpc: ['doSomething'],
},
headers: {
'content-type': 'application/json',
},
method: 'POST',
parseBody: false,
body: JSON.stringify('something'),
});
const { res, end } = mockRes();
await handler(req, res);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]).result.data;
expect(res.statusCode).toBe(200);
expect(json).toMatchInlineSnapshot('"did mutate something"');
});
});
|
5,295 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4292-content-type-json-fallback.test.ts | import { getPostBody } from '@trpc/server/src/adapters/node-http/content-type/json/getPostBody';
test('POST w/o specifying content-type should work', async () => {
{
const req = {
body: '',
headers: {
'content-type': 'application/json',
},
} as any;
const result = await getPostBody({
req,
});
assert(result.ok);
expect(result.preprocessed).toBe(true);
}
{
const req = {
body: '',
headers: {},
} as any;
const result = await getPostBody({
req,
});
assert(result.ok);
expect(result.preprocessed).toBe(false);
}
});
|
5,296 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4321-context-union-inference.test.ts | import '../___packages';
import { initTRPC, TRPCError } from '@trpc/server';
test('context union type is inferred correctly', async () => {
type UnsetContext = { user: null; session: null };
type SetContext = {
user: {
id: string;
name: string;
};
session: {
id: string;
state: string;
};
};
type ContextUnion = SetContext | UnsetContext;
const t = initTRPC.context<ContextUnion>().create();
const baseProcedure = t.procedure
// This line was causing the union to be simplified away
// Bug was due to Overwrite mapping away the union
// Resolved by "distributing over the union members": https://stackoverflow.com/a/51691257
.use(async ({ ctx, next }) => {
expectTypeOf<ContextUnion>(ctx);
return await next();
});
const protectedProcedure = baseProcedure.use(({ next, ctx }) => {
expectTypeOf<ContextUnion>(ctx);
// we narrow the type of `user` and `session` by throwing when either are null
if (!ctx.user || !ctx.session) {
expectTypeOf<UnsetContext>(ctx);
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'not signed in' });
}
expectTypeOf<SetContext>(ctx);
return next({ ctx });
});
protectedProcedure.use(async ({ next, ctx }) => {
// Should be definitely defined
ctx.user.id;
ctx.session.id;
expectTypeOf<SetContext>(ctx);
return next({
ctx: {
...ctx,
},
});
});
});
|
5,297 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4360-useInfiniteQuery-placeHolderData.test.tsx | import { ignoreErrors } from '../___testHelpers';
import { getServerAndReactClient } from '../react/__reactHelpers';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import { z } from 'zod';
const fixtureData = ['1', '2'];
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
post: t.router({
list: t.procedure
.input(
z.object({
cursor: z.number().default(0),
foo: z.literal('bar').optional().default('bar'),
}),
)
.query(({ input }) => {
return {
items: fixtureData.slice(input.cursor, input.cursor + 1),
next:
input.cursor + 1 > fixtureData.length
? undefined
: input.cursor + 1,
};
}),
}),
});
return getServerAndReactClient(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('with input', async () => {
const { proxy } = ctx;
ignoreErrors(() => {
proxy.post.list.useInfiniteQuery(
{ foo: 'bar' },
{
// @ts-expect-error can't return page data that doesn't match the output type
placeholderData() {
return {
pageParams: [undefined],
pages: [undefined],
};
},
getNextPageParam(lastPage) {
return lastPage.next;
},
onSuccess: (data) => {
if (data.pages[0]?.next) {
}
},
},
);
proxy.post.list.useSuspenseInfiniteQuery(
{ foo: 'bar' },
{
// @ts-expect-error can't return page data that doesn't match the output type
placeholderData() {
return {
pageParams: [undefined],
pages: [undefined],
};
},
getNextPageParam(lastPage) {
return lastPage.next;
},
onSuccess: (data) => {
if (data.pages[0]?.next) {
}
},
},
);
});
});
test('good placeholderData', () => {
const { proxy } = ctx;
ignoreErrors(() => {
proxy.post.list.useInfiniteQuery(
{ foo: 'bar' },
{
placeholderData() {
return {
pageParams: [undefined],
pages: [
{
items: ['1', '2', '3'],
},
],
};
},
getNextPageParam(lastPage) {
return lastPage.next;
},
onSuccess: (data) => {
if (data.pages[0]?.next) {
}
},
},
);
});
});
|
5,298 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4527-nested-middleware-root-context.test.ts | import { initTRPC, TRPCError } from '@trpc/server/src';
import { z } from 'zod';
test('root context override on nested middlewares', () => {
const t = initTRPC
.context<{
apiKey?: string | null;
req?: Request;
}>()
.create();
const enforceApiKey = t.middleware(async ({ ctx, next }) => {
if (!ctx.apiKey) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next({ ctx: { apiKey: ctx.apiKey } });
});
const formDataMiddleware = t.middleware(async ({ next }) => {
return next({ rawInput: new FormData() });
});
// root context -> enforceApiKey -> formDataMiddleware
t.procedure
.use(enforceApiKey)
.use(formDataMiddleware)
.input(
z.object({
somehash: z.string(),
}),
)
.query(async (opts) => {
expectTypeOf<{
req?: Request;
apiKey: string;
}>(opts.ctx);
return { status: 'ok' };
});
// root context -> formDataMiddleware -> enforceApiKey
t.procedure
.use(formDataMiddleware)
.use(enforceApiKey)
.input(
z.object({
somehash: z.string(),
}),
)
.query(async (opts) => {
expectTypeOf<{
req?: Request;
apiKey: string;
}>(opts.ctx);
return { status: 'ok' };
});
});
|
5,299 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4645-inferProcedureOutput.test.ts | import {
inferProcedureOutput,
inferRouterOutputs,
initTRPC,
} from '@trpc/server';
import { inferTransformedProcedureOutput } from '@trpc/server/shared';
import SuperJSON from 'superjson';
import { z } from 'zod';
test('infer json-esque', async () => {
const t = initTRPC.create();
const helloProcedure = t.procedure.input(z.string()).query(() => {
return {
hello: Math.random() > 0.5 ? 'hello' : undefined,
};
});
{
type Inferred = inferProcedureOutput<typeof helloProcedure>;
expectTypeOf<Inferred>().toEqualTypeOf<{ hello: string | undefined }>();
}
{
// This type is what the client will receive
// Because it will be sent as JSON, the undefined will be stripped by `JSON.stringify`
// Example: JSON.stringify({ hello: undefined }) === '{}'
type Inferred = inferTransformedProcedureOutput<typeof helloProcedure>;
expectTypeOf<Inferred>().toEqualTypeOf<{ hello?: string }>();
}
});
test('infer with superjson', async () => {
const t = initTRPC.create({
transformer: SuperJSON,
});
const helloProcedure = t.procedure.input(z.string()).query(() => {
return {
hello: Math.random() > 0.5 ? 'hello' : undefined,
};
});
{
type Inferred = inferProcedureOutput<typeof helloProcedure>;
expectTypeOf<Inferred>().toEqualTypeOf<{ hello: string | undefined }>();
}
{
// This type is what the client will receive
// Here, we use a transformer which will handle preservation of undefined
type Inferred = inferTransformedProcedureOutput<typeof helloProcedure>;
expectTypeOf<Inferred>().toEqualTypeOf<{ hello: string | undefined }>();
}
});
test('inference helpers', async () => {
const t = initTRPC.create();
const helloProcedure = t.procedure.input(z.string()).query(() => {
return {
hello: Math.random() > 0.5 ? 'hello' : undefined,
};
});
const router = t.router({
hello: helloProcedure,
});
type Outputs = inferRouterOutputs<typeof router>;
expectTypeOf<Outputs['hello']>().toEqualTypeOf<{ hello?: string }>();
});
|
5,300 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4673-url-encoded-batching.test.ts | import { routerToServerAndClientNew } from '../___testHelpers';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
import { z } from 'zod';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
a: t.procedure.query(() => 'a'),
b: t.procedure.query(() => 'b'),
withInput: t.procedure.input(z.string()).query((opts) => opts.input),
});
return routerToServerAndClientNew(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('handle URL encoded commas in URL.pathname', async () => {
const url = ctx.httpUrl;
const normalResult = await (
await fetch(`${url}/a,b?batch=1&input={}`)
).json();
const uriEncodedResult = await (
await fetch(`${url}/a%2Cb?batch=1&input={}`)
).json();
expect(normalResult).toMatchInlineSnapshot(`
Array [
Object {
"result": Object {
"data": "a",
},
},
Object {
"result": Object {
"data": "b",
},
},
]
`);
expect(normalResult).toEqual(uriEncodedResult);
});
test('handle URL encoded input in search params', async () => {
const url = ctx.httpUrl;
const normalResult = await (
await fetch(
`${url}/withInput?batch=1&input=${JSON.stringify({ 0: 'hello' })}`,
)
).json();
const uriEncodedResult = await (
await fetch(
`${url}/withInput?batch=1&input=${encodeURIComponent(
JSON.stringify({ 0: 'hello' }),
)}`,
)
).json();
expect(normalResult).toMatchInlineSnapshot(`
Array [
Object {
"result": Object {
"data": "hello",
},
},
]
`);
expect(normalResult).toEqual(uriEncodedResult);
});
|
5,301 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4750-no-cancel.test.ts | import { routerToServerAndClientNew, waitMs } from '../___testHelpers';
import { httpBatchLink, httpLink } from '@trpc/client';
import { AbortControllerEsque } from '@trpc/client/internals/types';
import { initTRPC } from '@trpc/server/src/core';
const t = initTRPC.create();
const router = t.router({
q: t.procedure.query(() => {
throw 'hello';
}),
});
function abortControllerSpy() {
const abortSpy = vi.fn();
const instanceSpy = vi.fn();
const AC = function AbortControllerSpy() {
instanceSpy();
const ac = new AbortController();
ac.abort = abortSpy;
return ac;
} as unknown as AbortControllerEsque;
return {
AC,
abortSpy,
instanceSpy,
};
}
test('httpLink', async () => {
const spy = abortControllerSpy();
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
links: [httpLink({ url: httpUrl, AbortController: spy.AC })],
};
},
});
await proxy.q.query(undefined).catch(() => {
/// ..
});
expect(spy.instanceSpy).toHaveBeenCalledTimes(1);
expect(spy.abortSpy).toHaveBeenCalledTimes(0);
await close();
});
test('httpBatchLink', async () => {
const spy = abortControllerSpy();
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
links: [httpBatchLink({ url: httpUrl, AbortController: spy.AC })],
};
},
});
await proxy.q.query(undefined).catch(() => {
/// ..
});
expect(spy.instanceSpy).toHaveBeenCalledTimes(1);
expect(spy.abortSpy).toHaveBeenCalledTimes(0);
await close();
});
|
5,302 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4783-charset.test.ts | import { routerToServerAndClientNew } from '../___testHelpers';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
a: t.procedure.query(() => 'a'),
});
return routerToServerAndClientNew(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('allow ;charset=utf-8 after application/json in content-type', async () => {
const url = ctx.httpUrl;
const json = await (
await fetch(`${url}/a?input={}`, {
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
})
).json();
expect(json).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "a",
},
}
`);
});
|
5,303 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4794-error-bad-access.test.ts | import { TRPCClientError } from '@trpc/client';
import '../___packages';
test('test passing non error like object to TRPCClientError.from', () => {
const cause = null;
expect(TRPCClientError.from(cause as any)).toMatchInlineSnapshot(
'[TRPCClientError: Unknown error]',
);
});
test('empty obj', () => {
const cause = {};
expect(TRPCClientError.from(cause as any)).toMatchInlineSnapshot(
'[TRPCClientError: Unknown error]',
);
});
|
5,304 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4947-merged-middleware-inputs.test.ts | import { createTRPCProxyClient } from '@trpc/react-query';
import {
experimental_standaloneMiddleware,
inferRouterInputs,
initTRPC,
} from '@trpc/server';
import * as z from 'zod';
test('Fix #4947: standalone middlewares -- inputs are merged properly when using multiple standalone middlewares', async () => {
const t = initTRPC.create();
const schemaA = z.object({ valueA: z.string() });
const schemaB = z.object({ valueB: z.string() });
const valueAUppercaserMiddleware = experimental_standaloneMiddleware<{
input: z.infer<typeof schemaA>;
}>().create((opts) => {
return opts.next({
ctx: { valueAUppercase: opts.input.valueA.toUpperCase() },
});
});
const valueBUppercaserMiddleware = experimental_standaloneMiddleware<{
input: z.infer<typeof schemaB>;
}>().create((opts) => {
return opts.next({
ctx: { valueBUppercase: opts.input.valueB.toUpperCase() },
});
});
const combinedInputThatSatisfiesBothMiddlewares = z.object({
valueA: z.string(),
valueB: z.string(),
extraProp: z.string(),
});
const proc = t.procedure
.input(combinedInputThatSatisfiesBothMiddlewares)
.use(valueAUppercaserMiddleware)
.use(valueBUppercaserMiddleware)
.query(
({
input: { valueA, valueB, extraProp },
ctx: { valueAUppercase, valueBUppercase },
}) =>
`valueA: ${valueA}, valueB: ${valueB}, extraProp: ${extraProp}, valueAUppercase: ${valueAUppercase}, valueBUppercase: ${valueBUppercase}`,
);
const router = t.router({
proc,
});
type Inputs = inferRouterInputs<typeof router>;
expectTypeOf(null as unknown as Inputs['proc']).toEqualTypeOf<{
valueA: string;
valueB: string;
extraProp: string;
}>();
const serverSideCaller = router.createCaller({});
const result = await serverSideCaller.proc({
valueA: 'a',
valueB: 'b',
extraProp: 'extra',
});
expect(result).toEqual(
'valueA: a, valueB: b, extraProp: extra, valueAUppercase: A, valueBUppercase: B',
);
const client = createTRPCProxyClient<typeof router>({
links: [],
});
type QueryKey = Parameters<typeof client.proc.query>[0];
expectTypeOf<{
valueA: 'a';
valueB: 'b';
extraProp: 'extra';
}>().toMatchTypeOf<QueryKey>();
});
|
5,305 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-4985-serialize-type.test.ts | import {
inferRouterInputs,
inferRouterOutputs,
initTRPC,
} from '@trpc/server/src';
import * as z from 'zod';
describe('Serialization of Record types', () => {
const t = initTRPC.create();
const appRouter = t.router({
recordStringAny: t.procedure.output(z.record(z.any())).query(() => {
return {
foo: 'bar',
};
}),
recordStringUnknown: t.procedure.output(z.record(z.unknown())).query(() => {
return {
foo: 'bar',
};
}),
symbolKey: t.procedure.query(() => {
return {
[Symbol('test')]: 'symbol',
str: 'string',
};
}),
// output serialization behaves differently if the output is inferred vs. given with .output()
inputWithRecord: t.procedure
.input(z.record(z.string()))
.query(({ input }) => input),
inputWithComplexRecord: t.procedure
.input(
z.record(
z.object({
name: z.string(),
age: z.number(),
symbol: z.symbol(),
}),
),
)
.query(({ input }) => input),
});
test('Record<string, any> gets inferred on the client as { [x: string]: any }', async () => {
type Output = inferRouterOutputs<typeof appRouter>['recordStringAny'];
expectTypeOf<Output>().toEqualTypeOf<Record<string, any>>();
});
test('Record<string, unknown> gets inferred on the client as { [x: string]: unknown }', async () => {
type Output = inferRouterOutputs<typeof appRouter>['recordStringUnknown'];
expectTypeOf<Output>().toEqualTypeOf<Record<string, unknown>>();
});
test('Symbol keys get erased on the client', async () => {
type Output = inferRouterOutputs<typeof appRouter>['symbolKey'];
expectTypeOf<Output>().toEqualTypeOf<{
str: string;
}>();
});
test('input type with a record, returned as inferred output', async () => {
type Input = inferRouterInputs<typeof appRouter>['inputWithRecord'];
type Output = inferRouterOutputs<typeof appRouter>['inputWithRecord'];
expectTypeOf<Input>().toEqualTypeOf<Record<string, string>>();
expectTypeOf<Output>().toEqualTypeOf<Record<string, string>>();
});
test('input type with a complex record, returned as inferred output', async () => {
type Input = inferRouterInputs<typeof appRouter>['inputWithComplexRecord'];
type Output = inferRouterOutputs<
typeof appRouter
>['inputWithComplexRecord'];
expectTypeOf<Input>().toEqualTypeOf<
Record<string, { name: string; age: number; symbol: symbol }>
>();
expectTypeOf<Output>().toEqualTypeOf<
Record<string, { name: string; age: number }>
>();
});
});
|
5,306 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-5020-inference-middleware.test.ts | import { inferRouterInputs, inferRouterOutputs, initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.create();
const appRouter = t.router({
str: t.procedure.input(z.string()).query(({ input }) => input),
strWithMiddleware: t.procedure
// ^?
.input(z.string())
.use((opts) => opts.next())
.query(({ input }) => input),
voidWithMiddleware: t.procedure
.use((opts) => opts.next())
.query(() => {
// ..
}),
});
type AppRouter = typeof appRouter;
describe('inferRouterInputs', () => {
type AppRouterInputs = inferRouterInputs<AppRouter>;
type AppRouterOutputs = inferRouterOutputs<AppRouter>;
test('string', async () => {
{
type Input = AppRouterInputs['str'];
type Output = AppRouterOutputs['str'];
expectTypeOf<Input>().toBeString();
expectTypeOf<Output>().toBeString();
}
{
type Input = AppRouterInputs['strWithMiddleware'];
// ^?
type Output = AppRouterOutputs['strWithMiddleware'];
expectTypeOf<Input>().toBeString();
expectTypeOf<Output>().toBeString();
}
});
});
|
Subsets and Splits