Skip to content

Instantly share code, notes, and snippets.

@cazzer
Last active November 12, 2018 00:52
Show Gist options
  • Save cazzer/b16c16be8695b5bc49dcd433a508235e to your computer and use it in GitHub Desktop.
Save cazzer/b16c16be8695b5bc49dcd433a508235e to your computer and use it in GitHub Desktop.
A Lambda which serves GraphQL requests using Postgraphile
import get from 'lodash/get'
import { graphql } from 'graphql'
import Pool from 'pg-pool'
import {
createPostGraphileSchema,
withPostGraphileContext
} from 'postgraphile'
import config from './config'
const postgraphileSchemaPromise = createPostGraphileSchema(
config.DB_ENDPOINT,
'public'
)
const pool = new Pool({
user: config.DB_USER,
password: config.DB_PASSWORD,
host: config.DB_HOST,
port: config.DB_PORT,
database: config.DB_NAME,
// this ensures the pool can drop a connection if it has gone bad
min: 0,
// no need for more since we are in Lambda-land
max: 1
})
export default async function graphQLambda(event) {
// grab the user ID from the request, this example assumes you're using Cognito
const userId = get(event, 'requestContext.authorizer.claims.sub')
const graphqlInput = JSON.parse(event.body)
try {
const postgraphileSchema = await postgraphileSchemaPromise
const result = await withPostGraphileContext(
{
pgPool: pool,
pgDefaultRole: 'application_user',
pgSettings: {
// the same setting we are using in our policies
'user_id': userId
}
},
async context => {
return await graphql(
postgraphileSchema,
graphqlInput.query,
null,
{ ...context },
graphqlInput.variables,
graphqlInput.operationName
)
}
)
return {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
},
body: JSON.stringify(result),
statusCode: 200
}
} catch (error) {
return {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
},
body: JSON.stringify(error),
statusCode: 500
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment