Skip to content

Instantly share code, notes, and snippets.

@christopher-caldwell
Created August 19, 2024 14:03
Show Gist options
  • Save christopher-caldwell/16cdb098f8ec2c2805b6ea3038e396bb to your computer and use it in GitHub Desktop.
Save christopher-caldwell/16cdb098f8ec2c2805b6ea3038e396bb to your computer and use it in GitHub Desktop.
GraphQL Yoga in Lambda with DB connection
import { APIGatewayEvent, APIGatewayProxyResult, Context } from 'aws-lambda'
import { createYoga } from 'graphql-yoga'
import { getDb, dbSchema } from '@_models'
import { schema } from './schema'
import { ResolverContext } from './types'
import { NodePgDatabase } from 'drizzle-orm/node-postgres'
const yoga = createYoga<ResolverContext>({
schema,
})
let hotDb: NodePgDatabase<typeof dbSchema>
export const handler = async (event: APIGatewayEvent, lambdaContext: Context): Promise<APIGatewayProxyResult> => {
if (!hotDb) {
const { db } = await getDb()
hotDb = db
}
const response = await yoga.fetch(
'/graphql',
{
method: 'POST',
headers: event.headers as HeadersInit,
body: event.body ? Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8') : undefined,
},
{
event,
lambdaContext,
db: hotDb,
me: {
id: '1',
token: '123',
},
},
)
const responseHeaders = Object.fromEntries(response.headers.entries())
return {
statusCode: response.status,
headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' },
body: await response.text(),
isBase64Encoded: false,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment