Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: update trpc to use server caller #814

Merged
merged 2 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/nextjs/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default async function HomePage() {
// You don't need to fetch these here, just showing different usages
// If you don't want the Suspense loading state, you could pass these
// posts as props as use as initialData in the query.
const posts = await api.post.all.query();
const posts = await api.post.all();
console.log("RSC Posts:", posts);

return (
Expand Down
4 changes: 2 additions & 2 deletions apps/nextjs/src/trpc/react.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ export function TRPCReactProvider(props: {
unstable_httpBatchStreamLink({
url: getBaseUrl() + "/api/trpc",
async headers() {
const headers = new Map(await props.headersPromise);
const headers = new Headers(await props.headersPromise);
headers.set("x-trpc-source", "nextjs-react");
return Object.fromEntries(headers);
return headers;
},
}),
],
Expand Down
44 changes: 2 additions & 42 deletions apps/nextjs/src/trpc/server.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import type { TRPCErrorResponse } from "@trpc/server/rpc";
import { cache } from "react";
import { headers } from "next/headers";
import { createTRPCClient, loggerLink, TRPCClientError } from "@trpc/client";
import { callProcedure } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import SuperJSON from "superjson";

import { appRouter, createTRPCContext } from "@acme/api";
import { createCaller, createTRPCContext } from "@acme/api";
import { auth } from "@acme/auth";

/**
Expand All @@ -23,39 +18,4 @@ const createContext = cache(async () => {
});
});

export const api = createTRPCClient<typeof appRouter>({
transformer: SuperJSON,
links: [
loggerLink({
enabled: (op) =>
process.env.NODE_ENV === "development" ||
(op.direction === "down" && op.result instanceof Error),
}),
/**
* Custom RSC link that invokes procedures directly in the server component Don't be too afraid
* about the complexity here, it's just wrapping `callProcedure` with an observable to make it a
* valid ending link for tRPC.
*/
() =>
({ op }) =>
observable((observer) => {
createContext()
.then((ctx) => {
return callProcedure({
procedures: appRouter._def.procedures,
path: op.path,
getRawInput: () => Promise.resolve(op.input),
ctx,
type: op.type,
});
})
.then((data) => {
observer.next({ result: { data } });
observer.complete();
})
.catch((cause: TRPCErrorResponse) => {
observer.error(TRPCClientError.from(cause));
});
}),
],
});
export const api = createCaller(createContext);
27 changes: 21 additions & 6 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,33 @@
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";

import type { AppRouter } from "./root";
import { appRouter } from "./root";
import { createCallerFactory, createTRPCContext } from "./trpc";

export { appRouter, type AppRouter } from "./root";
export { createTRPCContext } from "./trpc";
/**
* Create a server-side caller for the tRPC API
* @example
* const trpc = createCaller(createContext);
* const res = await trpc.post.all();
* ^? Post[]
*/
const createCaller = createCallerFactory(appRouter);

/**
* Inference helpers for input types
* @example type HelloInput = RouterInputs['example']['hello']
* @example
* type PostByIdInput = RouterInputs['post']['byId']
* ^? { id: number }
**/
export type RouterInputs = inferRouterInputs<AppRouter>;
type RouterInputs = inferRouterInputs<AppRouter>;

/**
* Inference helpers for output types
* @example type HelloOutput = RouterOutputs['example']['hello']
* @example
* type AllPostsOutput = RouterOutputs['post']['all']
* ^? Post[]
**/
export type RouterOutputs = inferRouterOutputs<AppRouter>;
type RouterOutputs = inferRouterOutputs<AppRouter>;

export { createTRPCContext, appRouter, createCaller };
export type { AppRouter, RouterInputs, RouterOutputs };
6 changes: 6 additions & 0 deletions packages/api/src/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ const t = initTRPC.context<typeof createTRPCContext>().create({
}),
});

/**
* Create a server-side caller
* @see https://trpc.io/docs/server/server-side-calls
*/
export const createCallerFactory = t.createCallerFactory;

/**
* 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)
*
Expand Down
58 changes: 29 additions & 29 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.