Context
Baeta allows you to define a shared context that's available throughout your resolvers and middlewares.
Define Context Type
First, define your context type:
// src/context.ts
import type { PubSub } from "graphql-yoga";
import type { PubSubMap } from "../lib/pubsub";
import type { PrismaClient } from "../lib/db/prisma";
export type Context = {
db: PrismaClient;
pubsub: PubSub<PubSubMap>;
};
Configuration
Add the context type path to your baeta.ts
configuration:
import { defineConfig } from "@baeta/cli";
import { autoloadPlugin } from "@baeta/plugin-autoload";
export default defineConfig({
graphql: {
schemas: ["src/**/*.gql"],
contextType: "src/context#Context", // Path to context type
},
// ... rest of config
});
Usage in Resolvers
The context is automatically typed in your resolvers:
const { Query } = getUserModule();
Query.user(({ args, ctx }) => {
// ctx is typed as Context
return ctx.db.user.findUnique({
where: args.where,
});
});
Usage in Middlewares
Middlewares also get the typed context:
Mutation.updateUser.$use(async ({ ctx }, next) => {
// ctx is typed as Context
const result = await next();
ctx.pubsub.publish("user-updated", result);
return result;
});