Skip to content

Instantly share code, notes, and snippets.

@mechmillan
Created February 13, 2019 13:51
Show Gist options
  • Save mechmillan/4d5fea77316b31764d01196cd9f1bbf1 to your computer and use it in GitHub Desktop.
Save mechmillan/4d5fea77316b31764d01196cd9f1bbf1 to your computer and use it in GitHub Desktop.
Setup for MB
// in basic server.js
// mount express-graphql on '/graphql' as a route-handler
app.use(
GRAPHQL_ENDPOINT,
graphqlHTTP(req => {
// STEP 5: define your resolvers
// batch loading functions
// accepting an array of keys and returning
// promises that resolve to an array of values
const companyLoader = new DataLoader(keys =>
Promise.all(keys.map(IEXApi.getCompanyInfo))
);
const quoteLoader = new DataLoader(keys =>
Promise.all(keys.map(IEXApi.getQuote))
);
const topsLoader = new DataLoader(keys =>
Promise.all(keys.map(IEX.getTopsBySymbol))
);
return {
schema,
context: {
companyLoader,
quoteLoader,
topsLoader
},
graphiql: true // interactive IDE enabled
};
})
);
// in basic schema.js
const CompanyType = new GraphQLObjectType({
name: "Company",
description: "Basic Company Object",
fields: () => ({
CEO: {
type: GraphQLString,
resolve: json => json.CEO
},
companyName: {
type: GraphQLString,
resolve: json => json.companyName
},
description: {
type: GraphQLString,
resolve: json => json.description
},
exchange: {
type: GraphQLString,
resolve: json => json.exchange
}
})
});
const QuoteType = new GraphQLObjectType({
name: "Quote",
description: "Basic Quote Object",
fields: () => ({
open: {
type: GraphQLFloat,
resolve: json => json.open
},
close: {
type: GraphQLFloat,
resolve: json => json.close
},
high: {
type: GraphQLFloat,
resolve: json => json.high
},
low: {
type: GraphQLFloat,
resolve: json => json.low
},
week52High: {
type: GraphQLFloat,
resolve: json => json.week52High
}
})
});
// in module.exports
// instance of GraphQLSchema Constructor
// which takes a configuration object
module.exports = new GraphQLSchema({
// root query operation
// STEP 2, 3, 4: define queries, mutations, subscriptions
query: new GraphQLObjectType({
name: "Query",
description: "Query for information about a company, by symbol",
fields: () => ({
Company: {
type: CompanyType,
args: {
symbol: { type: GraphQLString } // define structure of accepted arg(s)
},
resolve: (root, args, context) =>
context.companyLoader.load(args.symbol)
},
Quote: {
type: QuoteType,
args: {
symbol: { type: GraphQLString }
},
resolve: (root, args, context) => context.quoteLoader.load(args.symbol)
}
})
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment