Skip to content

Instantly share code, notes, and snippets.

@alfari16
Last active September 7, 2020 06:59
Show Gist options
  • Select an option

  • Save alfari16/ac624767ece118b662283f5c135a5111 to your computer and use it in GitHub Desktop.

Select an option

Save alfari16/ac624767ece118b662283f5c135a5111 to your computer and use it in GitHub Desktop.
// graphql.ts
import 'graphql-import-node';
import {makeExecutableSchema} from 'graphql-tools';
import {ApolloServer} from 'apollo-server-express';
import Knex from 'knex';
import Dataloader from 'dataloader';
import config from 'config';
import resolvers from './resolvers';
import * as typeDefs from './typeDefs.graphql';
const loaders = () => ({
getLocationsByMerchantId: new Dataloader(async merchantIds => {
const locations = await Knex(config.get('database'))('locations')
.whereIn('merchantId', merchantIds);
return merchantIds.map(merchantId => locations.find(location => location.merchantId === merchantId));
}),
getProductsByMerchantId: new Dataloader(async merchantIds => {
const products = await Knex(config.get('database'))('products')
.whereIn('merchantId', merchantIds);
return merchantIds.map(merchantId => products.filter(product => product.merchantId === merchantId));
})
});
const graphQLServer = new ApolloServer({
schema: makeExecutableSchema({
typeDefs: [typeDefs],
resolvers
}),
context: ({req}) => ({
currentUser: req.currentUser, // handled by middleware
loaders: loaders()
})
});
export default graphQLServer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment