Last active
January 31, 2018 19:06
-
-
Save sastraxi/bce8f29c1728cb9c965171df88d11028 to your computer and use it in GitHub Desktop.
Hacky way to combine PostGraphile with another GraphQL schema
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 express from 'express'; | |
import bodyParser from 'body-parser'; | |
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express'; | |
import { postgraphile } from 'postgraphile'; | |
import { createApolloFetch } from 'apollo-fetch'; | |
import { | |
makeRemoteExecutableSchema, | |
introspectSchema, | |
mergeSchemas, | |
} from 'graphql-tools'; | |
import stripe from './stripe'; | |
export default async (app, knex) => { | |
const internalApp = express(); | |
internalApp.use(bodyParser.json()); | |
internalApp.use(postgraphile(process.env.DATABASE_URL, 'public', { | |
pgSettings: (req) => { | |
const userId = req.headers['user-id']; | |
return { | |
role: 'app_user', | |
...(userId | |
? { 'jwt.claims.user_id': String(userId) } | |
: {}), | |
}; | |
}, | |
})); | |
internalApp.listen(process.env.INTERNAL_PORT, () => { | |
console.log(`postgraphile server listening on port ${process.env.INTERNAL_PORT}`); | |
}); | |
const pgFetcher = createApolloFetch({ | |
uri: `http://localhost:${process.env.INTERNAL_PORT}/graphql`, | |
}); | |
pgFetcher.use(({ request, options }, next) => { | |
if (!options.headers) { | |
options.headers = {}; // eslint-disable-line | |
} | |
const { context } = request; | |
// eslint-disable-next-line | |
options.headers['user-id'] = context && | |
context.graphqlContext && | |
context.graphqlContext.userId; | |
next(); | |
}); | |
const pgSchema = makeRemoteExecutableSchema({ | |
schema: await introspectSchema(pgFetcher), | |
fetcher: pgFetcher, | |
}); | |
const schema = mergeSchemas({ | |
schemas: [pgSchema, stripe.schema, stripe.linkTypeDefs], | |
resolvers: stripe.linkResolvers, | |
}); | |
// The GraphQL endpoint | |
app.use('/graphql', graphqlExpress(req => ({ | |
schema, | |
context: { | |
userId: req.user && req.user.id, // to use in our resolvers + send to postgraphile | |
knex, // so we can make direct DB calls in our stripe resolvers | |
}, | |
}))); | |
// GraphiQL, a visual editor for queries | |
if (process.env.NODE_ENV === 'development') { | |
app.get('/graphiql', graphiqlExpress({ | |
endpointURL: '/graphql', | |
})); | |
} | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment