honojs / middleware

monorepo for Hono third-party middleware/helpers/wrappers
https://hono.dev
478 stars 173 forks source link

Hono env context in @hono/trpc-server createContext does not have type bindings #694

Open tsatsujnr139 opened 3 months ago

tsatsujnr139 commented 3 months ago

Using the example from the trpc server middleware for hono docs, in the createContext example the env is typed as Context<any, any, {}> is there a way to get the type safe bindings same as when using the hono routes directly so that var1 in the example below is typesafe?

image

import { trpcServer } from "@hono/trpc-server";
import { initTRPC } from "@trpc/server";
import { Hono } from "hono";
import { z } from "zod";

type Bindings = {
    DB: D1Database;
};
type HonoContext = {
    env: Bindings;
};

const t = initTRPC.context<HonoContext>().create();

const publicProcedure = t.procedure;
const router = t.router;

const app = new Hono<{ Bindings: Bindings }>();

export const appRouter = router({
    usersCount: publicProcedure.query(async ({ input, ctx }) => {
        const result = await ctx.env.DB.prepare("SELECT count(*) from user;").all();
        return result?.results[0]?.count;
    }),
});

app.use(
    "/trpc/*",
    trpcServer({
        router: appRouter,
        createContext: (_opts, c) => ({
            // c is the hono context
            var1: c.env.DB, // This is not typesafe
            var2: c.req.header("X-VAR2"),
        }),
    }),
);

export type AppRouter = typeof appRouter;
limzykenneth commented 3 months ago

May be related but I'm seeing similar issue with @hono/zod-validator where the bindings defined on the app is not present in the hook callback's context parameter passed to the zValidator() function.