@trpc/server 11.22.2-canary.9.85bcf328a → 11.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -8
- package/dist/adapters/aws-lambda/index.cjs +1 -1
- package/dist/adapters/aws-lambda/index.d.cts.map +1 -1
- package/dist/adapters/aws-lambda/index.d.mts.map +1 -1
- package/dist/adapters/aws-lambda/index.mjs +1 -1
- package/dist/adapters/aws-lambda/index.mjs.map +1 -1
- package/dist/adapters/express.cjs +1 -1
- package/dist/adapters/express.mjs +1 -1
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/fastify/index.cjs +3 -3
- package/dist/adapters/fastify/index.mjs +3 -3
- package/dist/adapters/fetch/index.cjs +1 -1
- package/dist/adapters/fetch/index.mjs +1 -1
- package/dist/adapters/next-app-dir.mjs.map +1 -1
- package/dist/adapters/next.cjs +1 -1
- package/dist/adapters/next.mjs +1 -1
- package/dist/adapters/next.mjs.map +1 -1
- package/dist/adapters/node-http/index.cjs +1 -1
- package/dist/adapters/node-http/index.mjs +1 -1
- package/dist/adapters/standalone.cjs +9 -3
- package/dist/adapters/standalone.d.cts +0 -1
- package/dist/adapters/standalone.d.cts.map +1 -1
- package/dist/adapters/standalone.d.mts +0 -1
- package/dist/adapters/standalone.d.mts.map +1 -1
- package/dist/adapters/standalone.mjs +9 -3
- package/dist/adapters/standalone.mjs.map +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.mjs +1 -1
- package/dist/asyncGeneratorDelegate-FcEJT04i.mjs.map +1 -1
- package/dist/codes-C9N0z0an.mjs.map +1 -1
- package/dist/getErrorShape-zlj81BiC.mjs.map +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.mjs +1 -1
- package/dist/initTRPC-RMeQIy9H.mjs.map +1 -1
- package/dist/{node-http-B5jkpWn7.mjs → node-http-ChhZEv1k.mjs} +2 -2
- package/dist/node-http-ChhZEv1k.mjs.map +1 -0
- package/dist/{node-http-BZ0HlzkC.cjs → node-http-X8RiQEuH.cjs} +1 -1
- package/dist/parseTRPCMessage-CJ4DJVBp.mjs.map +1 -1
- package/dist/{resolveResponse-b9D_SrLs.cjs → resolveResponse-CoGjFxK0.cjs} +8 -4
- package/dist/{resolveResponse-DH5L33sC.mjs → resolveResponse-DksrxZ2k.mjs} +9 -5
- package/dist/resolveResponse-DksrxZ2k.mjs.map +1 -0
- package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -1
- package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -1
- package/dist/unstable-core-do-not-import.cjs +1 -1
- package/dist/unstable-core-do-not-import.mjs +1 -1
- package/dist/unstable-core-do-not-import.mjs.map +1 -1
- package/dist/{ws-83TNWW-W.cjs → ws-7qWW7Uec.cjs} +2 -2
- package/dist/{ws-DJ2SSChC.mjs → ws-BYfo-HED.mjs} +3 -3
- package/dist/ws-BYfo-HED.mjs.map +1 -0
- package/package.json +9 -12
- package/skills/adapter-aws-lambda/SKILL.md +152 -134
- package/skills/adapter-express/SKILL.md +127 -113
- package/skills/adapter-fastify/SKILL.md +228 -136
- package/skills/adapter-fetch/SKILL.md +388 -111
- package/skills/adapter-standalone/SKILL.md +184 -94
- package/skills/auth/SKILL.md +327 -202
- package/skills/auth/references/client-cors.md +29 -0
- package/skills/caching/SKILL.md +58 -148
- package/skills/error-handling/SKILL.md +280 -174
- package/skills/middlewares/SKILL.md +320 -121
- package/skills/non-json-content-types/SKILL.md +149 -168
- package/skills/server-setup/SKILL.md +355 -253
- package/skills/server-setup/references/server-context.md +219 -0
- package/skills/server-setup/references/server-merging-routers.md +141 -0
- package/skills/server-setup/references/server-metadata.md +105 -0
- package/skills/server-setup/references/server-procedures.md +172 -0
- package/skills/server-setup/references/server-routers.md +123 -0
- package/skills/server-side-calls/SKILL.md +247 -152
- package/skills/service-oriented-architecture/SKILL.md +81 -177
- package/skills/subscriptions/SKILL.md +341 -297
- package/skills/subscriptions/references/client-links-httpSubscriptionLink.md +404 -0
- package/skills/subscriptions/references/client-links-wsLink.md +122 -0
- package/skills/subscriptions/references/server-websockets.md +297 -0
- package/skills/trpc-router/SKILL.md +156 -86
- package/skills/validators/SKILL.md +384 -128
- package/src/adapters/aws-lambda/getPlanner.ts +4 -3
- package/src/adapters/aws-lambda/index.ts +2 -1
- package/src/adapters/express.ts +1 -1
- package/src/adapters/next-app-dir/nextAppDirCaller.ts +4 -4
- package/src/adapters/next-app-dir/rethrowNextErrors.ts +1 -1
- package/src/adapters/next.ts +1 -1
- package/src/adapters/node-http/incomingMessageToRequest.ts +1 -1
- package/src/adapters/node-http/nodeHTTPRequestHandler.ts +1 -1
- package/src/adapters/node-http/types.ts +1 -1
- package/src/adapters/node-http/writeResponse.ts +1 -1
- package/src/adapters/standalone.ts +12 -6
- package/src/adapters/ws.ts +5 -5
- package/src/unstable-core-do-not-import/clientish/inferrable.ts +4 -1
- package/src/unstable-core-do-not-import/clientish/serialize.ts +4 -4
- package/src/unstable-core-do-not-import/error/TRPCError.ts +3 -3
- package/src/unstable-core-do-not-import/http/formDataToObject.ts +1 -1
- package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +1 -1
- package/src/unstable-core-do-not-import/http/resolveResponse.ts +13 -2
- package/src/unstable-core-do-not-import/procedure.ts +5 -2
- package/src/unstable-core-do-not-import/procedureBuilder.ts +3 -2
- package/src/unstable-core-do-not-import/rootConfig.ts +2 -2
- package/src/unstable-core-do-not-import/router.ts +5 -2
- package/src/unstable-core-do-not-import/rpc/envelopes.ts +3 -2
- package/src/unstable-core-do-not-import/stream/jsonl.ts +2 -1
- package/src/unstable-core-do-not-import/stream/sse.types.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/disposable.ts +6 -6
- package/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts +2 -2
- package/src/unstable-core-do-not-import/stream/utils/withPing.ts +3 -1
- package/src/unstable-core-do-not-import/transformer.ts +4 -1
- package/src/unstable-core-do-not-import/types.ts +3 -2
- package/src/unstable-core-do-not-import/utils.ts +1 -1
- package/src/vendor/standard-schema-v1/spec.ts +2 -2
- package/src/vendor/unpromise/unpromise.ts +1 -1
- package/bin/intent.js +0 -20
- package/dist/node-http-B5jkpWn7.mjs.map +0 -1
- package/dist/resolveResponse-DH5L33sC.mjs.map +0 -1
- package/dist/ws-DJ2SSChC.mjs.map +0 -1
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Define Routers
|
|
2
|
+
|
|
3
|
+
From https://trpc.io/docs/server/routers
|
|
4
|
+
|
|
5
|
+
To begin building your tRPC-based API, you'll first need to define your router. Once you've mastered the fundamentals, you can [customize your routers](https://trpc.io/docs/server/routers#advanced-usage) for more advanced use cases.
|
|
6
|
+
|
|
7
|
+
## Initialize tRPC
|
|
8
|
+
|
|
9
|
+
You should initialize tRPC **exactly once** per application. Multiple instances of tRPC will cause issues: for example, `t.mergeRouters()` throws if the routers come from different instances that each set a [transformer](https://trpc.io/docs/server/data-transformers) or [error formatter](https://trpc.io/docs/server/error-formatting). Create `t` in one file and import your procedures and `router` from it everywhere.
|
|
10
|
+
|
|
11
|
+
```ts no-check title="server/trpc.ts"
|
|
12
|
+
import { initTRPC } from '@trpc/server';
|
|
13
|
+
|
|
14
|
+
// You can use any variable name you like.
|
|
15
|
+
// We use t to keep things simple.
|
|
16
|
+
const t = initTRPC.create();
|
|
17
|
+
|
|
18
|
+
export const router = t.router;
|
|
19
|
+
export const publicProcedure = t.procedure;
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
You'll notice we are exporting certain methods of the `t` variable here rather than `t` itself. This is to establish a certain set of procedures that we will use idiomatically in our codebase.
|
|
23
|
+
|
|
24
|
+
## Defining a router
|
|
25
|
+
|
|
26
|
+
Next, let's define a router with a procedure to use in our application. We have now created an API "endpoint".
|
|
27
|
+
|
|
28
|
+
In order for these endpoints to be exposed to the frontend, your [Adapter](https://trpc.io/docs/server/adapters) should be configured with your `appRouter` instance.
|
|
29
|
+
|
|
30
|
+
```ts no-check title="server/_app.ts"
|
|
31
|
+
import { publicProcedure, router } from './trpc';
|
|
32
|
+
|
|
33
|
+
const appRouter = router({
|
|
34
|
+
greeting: publicProcedure.query(() => 'hello tRPC v11!'),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
// Export only the type of a router!
|
|
38
|
+
// This prevents us from importing server code on the client.
|
|
39
|
+
export type AppRouter = typeof appRouter;
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
On the client, import it with `import type { AppRouter } from '...'` and never import the `appRouter` value: a type-only import is always erased, so your server code can't end up in the client bundle.
|
|
43
|
+
|
|
44
|
+
Procedures can't be named `then`, `call` or `apply`: `router()` throws if you use these names.
|
|
45
|
+
|
|
46
|
+
## Defining an inline sub-router
|
|
47
|
+
|
|
48
|
+
When you define an inline sub-router, you can represent your router as a plain object.
|
|
49
|
+
|
|
50
|
+
In the below example, `nested1` and `nested2` are equal:
|
|
51
|
+
|
|
52
|
+
```ts no-check title="server/_app.ts"
|
|
53
|
+
import * as trpc from '@trpc/server';
|
|
54
|
+
import { publicProcedure, router } from './trpc';
|
|
55
|
+
|
|
56
|
+
const appRouter = router({
|
|
57
|
+
// Using the router() method
|
|
58
|
+
nested1: router({
|
|
59
|
+
proc: publicProcedure.query(() => '...'),
|
|
60
|
+
}),
|
|
61
|
+
// Using an inline sub-router
|
|
62
|
+
nested2: {
|
|
63
|
+
proc: publicProcedure.query(() => '...'),
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Advanced usage
|
|
69
|
+
|
|
70
|
+
When initializing your router, tRPC allows you to:
|
|
71
|
+
|
|
72
|
+
- Setup [request contexts](https://trpc.io/docs/server/context)
|
|
73
|
+
- Assign [metadata](https://trpc.io/docs/server/metadata) to procedures
|
|
74
|
+
- [Format](https://trpc.io/docs/server/error-formatting) and [handle](https://trpc.io/docs/server/error-handling) errors
|
|
75
|
+
- [Transform data](https://trpc.io/docs/server/data-transformers) as needed
|
|
76
|
+
- Customize the [runtime configuration](https://trpc.io/docs/server/routers#runtime-configuration)
|
|
77
|
+
|
|
78
|
+
You can use method chaining to customize your `t`-object on initialization. For example:
|
|
79
|
+
|
|
80
|
+
```ts no-check
|
|
81
|
+
const t = initTRPC.context<Context>().meta<Meta>().create({
|
|
82
|
+
/* [...] */
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Runtime Configuration
|
|
87
|
+
|
|
88
|
+
```ts no-check
|
|
89
|
+
interface RootConfig {
|
|
90
|
+
/**
|
|
91
|
+
* Use a data transformer
|
|
92
|
+
* @see https://trpc.io/docs/v11/data-transformers
|
|
93
|
+
*/
|
|
94
|
+
transformer: DataTransformerOptions;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Use custom error formatting
|
|
98
|
+
* @see https://trpc.io/docs/v11/error-formatting
|
|
99
|
+
*/
|
|
100
|
+
errorFormatter: ErrorFormatter;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Allow `@trpc/server` to run in non-server environments
|
|
104
|
+
* @warning **Use with caution**, this should likely mainly be used within testing.
|
|
105
|
+
* @default false
|
|
106
|
+
*/
|
|
107
|
+
allowOutsideOfServer: boolean;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Is this a server environment?
|
|
111
|
+
* @warning **Use with caution**, this should likely mainly be used within testing.
|
|
112
|
+
* @default typeof window === 'undefined' || 'Deno' in window || process.env.NODE_ENV === 'test'
|
|
113
|
+
*/
|
|
114
|
+
isServer: boolean;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Is this development?
|
|
118
|
+
* Will be used to decide if the API should return stack traces
|
|
119
|
+
* @default process.env.NODE_ENV !== 'production'
|
|
120
|
+
*/
|
|
121
|
+
isDev: boolean;
|
|
122
|
+
}
|
|
123
|
+
```
|
|
@@ -1,249 +1,344 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: server-side-calls
|
|
3
|
-
description:
|
|
4
|
-
Call tRPC procedures directly from server code using t.createCallerFactory()
|
|
5
|
-
and router.createCaller(context) for integration testing, internal server logic,
|
|
6
|
-
and custom API endpoints. Catch TRPCError and extract HTTP status with
|
|
7
|
-
getHTTPStatusCodeFromError(). Error handling via onError option.
|
|
8
|
-
type: core
|
|
9
|
-
library: trpc
|
|
10
|
-
library_version: '11.16.0'
|
|
3
|
+
description: Call tRPC procedures directly from server code using t.createCallerFactory(router) and router.createCaller(ctx) for integration testing, internal server logic, and custom API endpoints. Pass the context as an object or a function, e.g. an inner context without a request. Catch TRPCError and extract HTTP status with getHTTPStatusCodeFromError(), report errors with createCaller's onError option. Don't use a caller inside another procedure; share a plain function instead.
|
|
11
4
|
requires:
|
|
12
5
|
- server-setup
|
|
13
6
|
sources:
|
|
14
|
-
-
|
|
7
|
+
- www/v11/docs/server/server-side-calls.md
|
|
8
|
+
metadata:
|
|
9
|
+
type: core
|
|
10
|
+
library: trpc
|
|
11
|
+
library_version: 11.23.0
|
|
15
12
|
---
|
|
16
13
|
|
|
17
|
-
|
|
14
|
+
<!-- Generated from www/v11/docs/server/server-side-calls.md by www/build/skills.ts. Edit the docs instead. -->
|
|
18
15
|
|
|
19
|
-
|
|
16
|
+
# Server Side Calls
|
|
20
17
|
|
|
21
|
-
|
|
22
|
-
// server/trpc.ts
|
|
23
|
-
import { initTRPC } from '@trpc/server';
|
|
18
|
+
From https://trpc.io/docs/server/server-side-calls
|
|
24
19
|
|
|
25
|
-
|
|
20
|
+
You may need to call your procedure(s) directly from the same server they're hosted in, `createCallerFactory()` can be used to achieve this. This is useful for server-side calls and for integration testing of your tRPC procedures.
|
|
26
21
|
|
|
27
|
-
|
|
22
|
+
> [!NOTE] Info
|
|
23
|
+
>
|
|
24
|
+
> `createCaller` should not be used to call procedures from within other procedures. This creates overhead by (potentially) creating context again, executing all middlewares, and validating the input - all of which were already done by the current procedure. Instead, you should extract the shared logic into a separate function and call that from within the procedures, like so:
|
|
25
|
+
>
|
|
26
|
+
> <div class="flex gap-2 w-full justify-between pt-2">
|
|
27
|
+
> <img src="https://assets.trpc.io/www/docs/server/server-side-calls/bad.png" alt="Instead of this: procedures in paymentRouter call customerRouter.createCaller(ctx).byUserId(ctx.user.id) to reuse its logic" class="w-[49.5%]" />
|
|
28
|
+
> <img src="https://assets.trpc.io/www/docs/server/server-side-calls/good.png" alt="Do this: a standalone getCustomerId(userId, prisma) function holds the shared logic, and every procedure calls it with values from ctx and input" class="w-[49.5%]" />
|
|
29
|
+
> </div>
|
|
28
30
|
|
|
29
|
-
export const router = t.router;
|
|
30
|
-
export const publicProcedure = t.procedure;
|
|
31
|
-
export const createCallerFactory = t.createCallerFactory;
|
|
32
|
-
```
|
|
33
31
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
32
|
+
## Create caller
|
|
33
|
+
|
|
34
|
+
With the `t.createCallerFactory`-function you can create a server-side caller of any router. You first call `createCallerFactory` with an argument of the router you want to call, then this returns a function where you can pass in a `Context` for the following procedure calls.
|
|
35
|
+
|
|
36
|
+
### Basic example
|
|
37
|
+
|
|
38
|
+
We create the router with a query to list posts and a mutation to add posts, and then we call each method.
|
|
39
|
+
|
|
40
|
+
```ts no-check
|
|
41
|
+
import { initTRPC } from '@trpc/server';
|
|
37
42
|
import { z } from 'zod';
|
|
38
|
-
|
|
43
|
+
|
|
44
|
+
type Context = {
|
|
45
|
+
foo: string;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const t = initTRPC.context<Context>().create();
|
|
49
|
+
|
|
50
|
+
const publicProcedure = t.procedure;
|
|
51
|
+
const { createCallerFactory, router } = t;
|
|
39
52
|
|
|
40
53
|
interface Post {
|
|
41
54
|
id: string;
|
|
42
55
|
title: string;
|
|
43
56
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
57
|
+
const posts: Post[] = [
|
|
58
|
+
{
|
|
59
|
+
id: '1',
|
|
60
|
+
title: 'Hello world',
|
|
61
|
+
},
|
|
62
|
+
];
|
|
63
|
+
const appRouter = router({
|
|
48
64
|
post: router({
|
|
49
65
|
add: publicProcedure
|
|
50
|
-
.input(
|
|
51
|
-
|
|
52
|
-
|
|
66
|
+
.input(
|
|
67
|
+
z.object({
|
|
68
|
+
title: z.string().min(2),
|
|
69
|
+
}),
|
|
70
|
+
)
|
|
71
|
+
.mutation((opts) => {
|
|
72
|
+
const post: Post = {
|
|
73
|
+
...opts.input,
|
|
74
|
+
id: `${Math.random()}`,
|
|
75
|
+
};
|
|
53
76
|
posts.push(post);
|
|
54
77
|
return post;
|
|
55
78
|
}),
|
|
56
|
-
byId: publicProcedure
|
|
57
|
-
.input(z.object({ id: z.string() }))
|
|
58
|
-
.query(({ input }) => {
|
|
59
|
-
const post = posts.find((p) => p.id === input.id);
|
|
60
|
-
if (!post) throw new TRPCError({ code: 'NOT_FOUND' });
|
|
61
|
-
return post;
|
|
62
|
-
}),
|
|
63
79
|
list: publicProcedure.query(() => posts),
|
|
64
80
|
}),
|
|
65
81
|
});
|
|
66
82
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
```
|
|
83
|
+
// 1. create a caller-function for your router
|
|
84
|
+
const createCaller = createCallerFactory(appRouter);
|
|
70
85
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
86
|
+
// 2. create a caller using your `Context`
|
|
87
|
+
const caller = createCaller({
|
|
88
|
+
foo: 'bar',
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// 3. use the caller to add and list posts
|
|
92
|
+
const addedPost = await caller.post.add({
|
|
93
|
+
title: 'How to make server-side call in tRPC',
|
|
94
|
+
});
|
|
74
95
|
|
|
75
|
-
const caller = createCaller({ user: { id: '1' } });
|
|
76
96
|
const postList = await caller.post.list();
|
|
77
|
-
const newPost = await caller.post.add({ title: 'New post' });
|
|
78
97
|
```
|
|
79
98
|
|
|
80
|
-
|
|
99
|
+
The caller doesn't run your adapter's `createContext`, so pass everything your procedures and middlewares expect. An [inner context](https://trpc.io/docs/server/context#inner-and-outer-context) works well here, as it doesn't need a request.
|
|
100
|
+
|
|
101
|
+
Instead of a context object, you can also pass a function that returns the context, or a promise of it. The caller calls it for every procedure call, so cache it (e.g. with React's `cache()`) if it's expensive:
|
|
102
|
+
|
|
103
|
+
```ts no-check
|
|
104
|
+
const createCaller = t.createCallerFactory(appRouter);
|
|
105
|
+
|
|
106
|
+
const caller = createCaller(async () => createContext());
|
|
107
|
+
const greeting = await caller.hello();
|
|
108
|
+
```
|
|
81
109
|
|
|
82
|
-
###
|
|
110
|
+
### Example usage in an integration test
|
|
83
111
|
|
|
84
|
-
|
|
85
|
-
// server/appRouter.test.ts
|
|
86
|
-
import type { inferProcedureInput } from '@trpc/server';
|
|
87
|
-
import { createCaller } from './appRouter';
|
|
88
|
-
import type { AppRouter } from './appRouter';
|
|
89
|
-
import { createContextInner } from './context';
|
|
112
|
+
> Taken from [https://github.com/trpc/examples-next-prisma-starter/blob/main/src/server/routers/post.test.ts](https://github.com/trpc/examples-next-prisma-starter/blob/main/src/server/routers/post.test.ts)
|
|
90
113
|
|
|
114
|
+
```ts no-check
|
|
91
115
|
async function testAddAndGetPost() {
|
|
92
|
-
const ctx = await createContextInner({
|
|
116
|
+
const ctx = await createContextInner({});
|
|
93
117
|
const caller = createCaller(ctx);
|
|
94
118
|
|
|
95
119
|
const input: inferProcedureInput<AppRouter['post']['add']> = {
|
|
96
|
-
|
|
120
|
+
text: 'hello test',
|
|
121
|
+
title: 'hello test',
|
|
97
122
|
};
|
|
98
123
|
|
|
99
124
|
const post = await caller.post.add(input);
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
console.assert(allPosts.some((p) => p.id === post.id));
|
|
125
|
+
const byId = await caller.post.byId({ id: post.id });
|
|
103
126
|
}
|
|
104
127
|
```
|
|
105
128
|
|
|
106
|
-
|
|
129
|
+
## `router.createCaller()`
|
|
130
|
+
|
|
131
|
+
With the `router.createCaller({})` function (first argument is `Context`) we retrieve an instance of `RouterCaller`.
|
|
132
|
+
|
|
133
|
+
### Input query example
|
|
134
|
+
|
|
135
|
+
We create the router with an input query, and then we call the asynchronous `greeting` procedure to get the result.
|
|
107
136
|
|
|
108
|
-
```ts
|
|
137
|
+
```ts no-check
|
|
109
138
|
import { initTRPC } from '@trpc/server';
|
|
110
139
|
import { z } from 'zod';
|
|
111
140
|
|
|
112
141
|
const t = initTRPC.create();
|
|
113
142
|
|
|
114
|
-
const
|
|
143
|
+
const router = t.router({
|
|
144
|
+
// Create procedure at path 'greeting'
|
|
115
145
|
greeting: t.procedure
|
|
116
146
|
.input(z.object({ name: z.string() }))
|
|
117
|
-
.query((
|
|
147
|
+
.query((opts) => `Hello ${opts.input.name}`),
|
|
118
148
|
});
|
|
119
149
|
|
|
120
|
-
const caller =
|
|
150
|
+
const caller = router.createCaller({});
|
|
121
151
|
const result = await caller.greeting({ name: 'tRPC' });
|
|
122
152
|
```
|
|
123
153
|
|
|
124
|
-
###
|
|
154
|
+
### Mutation example
|
|
125
155
|
|
|
126
|
-
|
|
127
|
-
import { TRPCError } from '@trpc/server';
|
|
128
|
-
import { getHTTPStatusCodeFromError } from '@trpc/server/http';
|
|
129
|
-
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
130
|
-
import { appRouter } from './appRouter';
|
|
131
|
-
|
|
132
|
-
export default async function handler(
|
|
133
|
-
req: NextApiRequest,
|
|
134
|
-
res: NextApiResponse,
|
|
135
|
-
) {
|
|
136
|
-
const caller = appRouter.createCaller({});
|
|
156
|
+
We create the router with a mutation, and then we call the asynchronous `post` procedure to get the result.
|
|
137
157
|
|
|
138
|
-
|
|
139
|
-
const post = await caller.post.byId({ id: req.query.id as string });
|
|
140
|
-
res.status(200).json({ data: { postTitle: post.title } });
|
|
141
|
-
} catch (cause) {
|
|
142
|
-
if (cause instanceof TRPCError) {
|
|
143
|
-
const httpStatusCode = getHTTPStatusCodeFromError(cause);
|
|
144
|
-
res.status(httpStatusCode).json({ error: { message: cause.message } });
|
|
145
|
-
return;
|
|
146
|
-
}
|
|
147
|
-
res.status(500).json({ error: { message: 'Internal server error' } });
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
### Caller with onError callback
|
|
153
|
-
|
|
154
|
-
```ts
|
|
158
|
+
```ts no-check
|
|
155
159
|
import { initTRPC } from '@trpc/server';
|
|
156
160
|
import { z } from 'zod';
|
|
157
161
|
|
|
158
|
-
const
|
|
162
|
+
const posts = ['One', 'Two', 'Three'];
|
|
159
163
|
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
.
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
return `Hello ${input.name}`;
|
|
164
|
+
const t = initTRPC.create();
|
|
165
|
+
const router = t.router({
|
|
166
|
+
post: t.router({
|
|
167
|
+
add: t.procedure.input(z.string()).mutation((opts) => {
|
|
168
|
+
posts.push(opts.input);
|
|
169
|
+
return posts;
|
|
168
170
|
}),
|
|
171
|
+
}),
|
|
169
172
|
});
|
|
170
173
|
|
|
171
|
-
const caller =
|
|
172
|
-
|
|
173
|
-
{
|
|
174
|
-
onError: (opts) => {
|
|
175
|
-
console.error('An error occurred:', opts.error);
|
|
176
|
-
},
|
|
177
|
-
},
|
|
178
|
-
);
|
|
174
|
+
const caller = router.createCaller({});
|
|
175
|
+
const result = await caller.post.add('Four');
|
|
179
176
|
```
|
|
180
177
|
|
|
181
|
-
|
|
178
|
+
### Context with middleware example
|
|
182
179
|
|
|
183
|
-
|
|
180
|
+
We create a middleware to check the context before executing the `secret` procedure. Below are two examples: the former fails because the context doesn't fit the middleware logic, and the latter works correctly.
|
|
184
181
|
|
|
185
|
-
|
|
182
|
+
<br />
|
|
186
183
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
184
|
+
> [!NOTE] Info
|
|
185
|
+
>
|
|
186
|
+
> Middlewares are performed before any procedure(s) are called.
|
|
190
187
|
|
|
191
|
-
const createCaller = createCallerFactory(appRouter);
|
|
192
188
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
189
|
+
<br />
|
|
190
|
+
|
|
191
|
+
```ts no-check
|
|
192
|
+
import { initTRPC, TRPCError } from '@trpc/server';
|
|
193
|
+
|
|
194
|
+
type Context = {
|
|
195
|
+
user?: {
|
|
196
|
+
id: string;
|
|
197
|
+
};
|
|
198
|
+
};
|
|
199
|
+
const t = initTRPC.context<Context>().create();
|
|
200
|
+
|
|
201
|
+
const protectedProcedure = t.procedure.use((opts) => {
|
|
202
|
+
const { ctx } = opts;
|
|
203
|
+
if (!ctx.user) {
|
|
204
|
+
throw new TRPCError({
|
|
205
|
+
code: 'UNAUTHORIZED',
|
|
206
|
+
message: 'You are not authorized',
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return opts.next({
|
|
211
|
+
ctx: {
|
|
212
|
+
// Infers that the `user` is non-nullable
|
|
213
|
+
user: ctx.user,
|
|
214
|
+
},
|
|
215
|
+
});
|
|
196
216
|
});
|
|
197
|
-
```
|
|
198
217
|
|
|
199
|
-
|
|
218
|
+
const router = t.router({
|
|
219
|
+
secret: protectedProcedure.query((opts) => opts.ctx.user),
|
|
220
|
+
});
|
|
200
221
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
222
|
+
{
|
|
223
|
+
// ❌ this will return an error because there isn't the right context param
|
|
224
|
+
const caller = router.createCaller({});
|
|
204
225
|
|
|
205
|
-
|
|
206
|
-
return ctx.db.post.findMany();
|
|
226
|
+
const result = await caller.secret();
|
|
207
227
|
}
|
|
208
228
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
229
|
+
{
|
|
230
|
+
// ✅ this will work because user property is present inside context param
|
|
231
|
+
const authorizedCaller = router.createCaller({
|
|
232
|
+
user: {
|
|
233
|
+
id: 'KATT',
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
const result = await authorizedCaller.secret();
|
|
237
|
+
}
|
|
212
238
|
```
|
|
213
239
|
|
|
214
|
-
|
|
240
|
+
### Example for a Next.js API endpoint
|
|
215
241
|
|
|
216
|
-
|
|
242
|
+
> [!TIP]
|
|
243
|
+
>
|
|
244
|
+
> This example shows how to use the caller in a Next.js API endpoint. tRPC creates API endpoints for you already, so this file is only meant to show
|
|
245
|
+
> how to call a procedure from another, custom endpoint.
|
|
217
246
|
|
|
218
|
-
### [MEDIUM] Not providing context to createCaller
|
|
219
247
|
|
|
220
|
-
|
|
248
|
+
```ts no-check
|
|
249
|
+
type ResponseData = {
|
|
250
|
+
data?: {
|
|
251
|
+
postTitle: string;
|
|
252
|
+
};
|
|
253
|
+
error?: {
|
|
254
|
+
message: string;
|
|
255
|
+
};
|
|
256
|
+
};
|
|
221
257
|
|
|
222
|
-
|
|
223
|
-
|
|
258
|
+
export default async (
|
|
259
|
+
req: NextApiRequest,
|
|
260
|
+
res: NextApiResponse<ResponseData>,
|
|
261
|
+
) => {
|
|
262
|
+
/** We want to simulate an error, so we pick a post ID that does not exist in the database. */
|
|
263
|
+
const postId = `this-id-does-not-exist-${Math.random()}`;
|
|
224
264
|
|
|
225
|
-
const caller = appRouter.createCaller({});
|
|
226
|
-
|
|
227
|
-
|
|
265
|
+
const caller = appRouter.createCaller({});
|
|
266
|
+
|
|
267
|
+
try {
|
|
268
|
+
// the server-side call
|
|
269
|
+
const postResult = await caller.post.byId({ id: postId });
|
|
270
|
+
|
|
271
|
+
res.status(200).json({ data: { postTitle: postResult.title } });
|
|
272
|
+
} catch (cause) {
|
|
273
|
+
// If this a tRPC error, we can extract additional information.
|
|
274
|
+
if (cause instanceof TRPCError) {
|
|
275
|
+
// We can get the specific HTTP status code coming from tRPC (e.g. 404 for `NOT_FOUND`).
|
|
276
|
+
const httpStatusCode = getHTTPStatusCodeFromError(cause);
|
|
277
|
+
|
|
278
|
+
res.status(httpStatusCode).json({ error: { message: cause.message } });
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// This is not a tRPC error, so we don't have specific information.
|
|
283
|
+
res.status(500).json({
|
|
284
|
+
error: { message: `Error while accessing post with ID ${postId}` },
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
};
|
|
228
288
|
```
|
|
229
289
|
|
|
230
|
-
|
|
290
|
+
### Error handling
|
|
291
|
+
|
|
292
|
+
A procedure called through a caller throws its error as a `TRPCError`; errors that weren't thrown as one become an `INTERNAL_SERVER_ERROR` with the original error as their `cause`.
|
|
231
293
|
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
import { createContextInner } from './context';
|
|
294
|
+
The `createCaller` function can also take an error handler through the `onError` option, for example to log or report errors. The caller still throws the error after the handler runs. Its options also take a `signal`, which your procedures receive as `opts.signal`.
|
|
295
|
+
The handler is called with the same arguments as an error formatter would be, except for the shape field:
|
|
235
296
|
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
297
|
+
```ts no-check
|
|
298
|
+
interface OnErrorShape {
|
|
299
|
+
ctx: unknown;
|
|
300
|
+
error: TRPCError;
|
|
301
|
+
path: string | undefined;
|
|
302
|
+
input: unknown;
|
|
303
|
+
type: 'query' | 'mutation' | 'subscription' | 'unknown';
|
|
304
|
+
}
|
|
239
305
|
```
|
|
240
306
|
|
|
241
|
-
|
|
307
|
+
```ts no-check
|
|
308
|
+
import { initTRPC } from '@trpc/server';
|
|
309
|
+
import { z } from 'zod';
|
|
310
|
+
|
|
311
|
+
const t = initTRPC
|
|
312
|
+
.context<{
|
|
313
|
+
foo?: 'bar';
|
|
314
|
+
}>()
|
|
315
|
+
.create();
|
|
316
|
+
|
|
317
|
+
const router = t.router({
|
|
318
|
+
greeting: t.procedure.input(z.object({ name: z.string() })).query((opts) => {
|
|
319
|
+
if (opts.input.name === 'invalid') {
|
|
320
|
+
throw new Error('Invalid name');
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
return `Hello ${opts.input.name}`;
|
|
324
|
+
}),
|
|
325
|
+
});
|
|
242
326
|
|
|
243
|
-
|
|
327
|
+
const caller = router.createCaller(
|
|
328
|
+
{
|
|
329
|
+
/* context */
|
|
330
|
+
},
|
|
331
|
+
{
|
|
332
|
+
onError: (opts) => {
|
|
333
|
+
console.error('An error occurred:', opts.error);
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
);
|
|
337
|
+
|
|
338
|
+
// The following will log "An error occurred: Error: Invalid name", and then throw the error
|
|
339
|
+
await caller.greeting({ name: 'invalid' });
|
|
340
|
+
```
|
|
244
341
|
|
|
245
|
-
##
|
|
342
|
+
## Related skills
|
|
246
343
|
|
|
247
|
-
- `server-setup`
|
|
248
|
-
- `middlewares` -- auth middleware that callers must satisfy
|
|
249
|
-
- `error-handling` -- TRPCError and getHTTPStatusCodeFromError
|
|
344
|
+
- `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
|