[TS] Passing object/data from CF Functions middleware to function handlers

I would like to setup Prisma in a functions _middleware.ts like:
import { PrismaClient } from '@prisma/client';
import { PrismaD1 } from '@prisma/adapter-d1';

export const onRequest: PagesFunction<Env> = async (context) => {
const adapter = new PrismaD1(context.env.DB);
const prisma = new PrismaClient({ adapter });

// now store prisma so it's available in function hadlers!
context.env.prisma = prisma;
// or
context.data.prisma = prisma;

return await context.next();
}
import { PrismaClient } from '@prisma/client';
import { PrismaD1 } from '@prisma/adapter-d1';

export const onRequest: PagesFunction<Env> = async (context) => {
const adapter = new PrismaD1(context.env.DB);
const prisma = new PrismaClient({ adapter });

// now store prisma so it's available in function hadlers!
context.env.prisma = prisma;
// or
context.data.prisma = prisma;

return await context.next();
}
I have a wrangler types functions/worker-configuration.d.ts generated file that looks like:
// Generated by Wrangler on Fri Apr 05 2024 23:40:46 GMT+0200 (Central European Summer Time)
// by running `wrangler types functions/worker-configuration.d.ts`

interface Env {
DB: D1Database;
}
// Generated by Wrangler on Fri Apr 05 2024 23:40:46 GMT+0200 (Central European Summer Time)
// by running `wrangler types functions/worker-configuration.d.ts`

interface Env {
DB: D1Database;
}
In my function handler I would like to use prisma client (type-safe) like:
export const onRequestGet: PagesFunction<Env> = async (context) => {
// TODO: get typed prisma client
const pets = await prisma.pet.findMany();
return Response.json(pets);
};
export const onRequestGet: PagesFunction<Env> = async (context) => {
// TODO: get typed prisma client
const pets = await prisma.pet.findMany();
return Response.json(pets);
};
How should I pass the prisma client best? Via context.env or context.data ? And how to type it?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server