I am a Dev
I am a Dev15mo ago

Review of inner and outer context with express

Hello, I didn't find any example that uses inner (for testing) and outer context with express. That's how I implemented it for my express trpc boilerplate, I wanted to know if I did it right, or if there was some error. Thank you so much TLDR; The inner context and options is a custom object with partial express options. the outer context and options is an extension of the inner but now the express options are mandatory.
import { initTRPC } from '@trpc/server';
import type * as trpcExpress from '@trpc/server/adapters/express';
import superjson from 'superjson';
import type { OpenApiMeta } from 'trpc-openapi';

// Fake prisma
const prisma = 'prisma';

export interface CreateInnerTRPCContextOptions
extends Partial<trpcExpress.CreateExpressContextOptions> {}

export interface AppInnerContext
extends Partial<trpcExpress.CreateExpressContextOptions> {
prisma: string;
}

export async function createInnerTRPCContext(
_opts: CreateInnerTRPCContextOptions,
): Promise<AppInnerContext> {
return {
prisma,
};
}

type CreateTRPCContextOptions = CreateInnerTRPCContextOptions &
trpcExpress.CreateExpressContextOptions;

export type AppContext = AppInnerContext &
trpcExpress.CreateExpressContextOptions;

export async function createTRPCContext(
opts: CreateTRPCContextOptions,
): Promise<AppContext> {
const innerContext = await createInnerTRPCContext(opts);

return {
...innerContext,
req: opts.req,
res: opts.res,
};
}

const t = initTRPC.meta<OpenApiMeta>().context<AppInnerContext>().create({
transformer: superjson,
});

export const createTRPCRouter = t.router;

export const publicProcedure = t.procedure;
import { initTRPC } from '@trpc/server';
import type * as trpcExpress from '@trpc/server/adapters/express';
import superjson from 'superjson';
import type { OpenApiMeta } from 'trpc-openapi';

// Fake prisma
const prisma = 'prisma';

export interface CreateInnerTRPCContextOptions
extends Partial<trpcExpress.CreateExpressContextOptions> {}

export interface AppInnerContext
extends Partial<trpcExpress.CreateExpressContextOptions> {
prisma: string;
}

export async function createInnerTRPCContext(
_opts: CreateInnerTRPCContextOptions,
): Promise<AppInnerContext> {
return {
prisma,
};
}

type CreateTRPCContextOptions = CreateInnerTRPCContextOptions &
trpcExpress.CreateExpressContextOptions;

export type AppContext = AppInnerContext &
trpcExpress.CreateExpressContextOptions;

export async function createTRPCContext(
opts: CreateTRPCContextOptions,
): Promise<AppContext> {
const innerContext = await createInnerTRPCContext(opts);

return {
...innerContext,
req: opts.req,
res: opts.res,
};
}

const t = initTRPC.meta<OpenApiMeta>().context<AppInnerContext>().create({
transformer: superjson,
});

export const createTRPCRouter = t.router;

export const publicProcedure = t.procedure;
0 Replies
No replies yetBe the first to reply to this messageJoin