Created
August 19, 2024 14:03
-
-
Save christopher-caldwell/16cdb098f8ec2c2805b6ea3038e396bb to your computer and use it in GitHub Desktop.
GraphQL Yoga in Lambda with DB connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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