Skip to content

Instantly share code, notes, and snippets.

@nicolasdao
Last active March 6, 2018 07:46
Show Gist options
  • Save nicolasdao/6d69c84ada886570b39650694a212c4e to your computer and use it in GitHub Desktop.
Save nicolasdao/6d69c84ada886570b39650694a212c4e to your computer and use it in GitHub Desktop.
// src/graphql/product/schema.graphql
type Product {
id: ID!
name: String!
shortDescription: String
}
type Query {
# ### GET products
#
# _Arguments_
# - **id**: Product id (optional)
products(id: Int): [Product]
}
// src/graphql/product/resolver.js
const productMocks = [{ id: 1, name: 'Product A', shortDescription: 'First product.' }, { id: 2, name: 'Product B', shortDescription: 'Second product.' }]
exports.resolver = {
Query: {
products(root, { id }, context) {
const results = id ? productMocks.filter(p => p.id == id) : productMocks
if (results.length > 0)
return results
else
throw new Error(`Product with id ${id} does not exist.`)
}
}
}
// src/graphql/variant/schema.graphql
type Variant {
id: ID!
name: String!
shortDescription: String
}
type Query {
# ### GET variants
#
# _Arguments_
# - **id**: Variant id (optional)
variants(id: Int): [Variant]
}
// src/graphql/variant/resolver.js
const variantMocks = [{ id: 1, name: 'Variant A', shortDescription: 'First variant.' }, { id: 2, name: 'Variant B', shortDescription: 'Second variant.' }]
exports.resolver = {
Query: {
variants(root, { id }, context) {
const results = id ? variantMocks.filter(p => p.id == id) : variantMocks
if (results.length > 0)
return results
else
throw new Error(`Variant with id ${id} does not exist.`)
}
}
}
// index.js
const { app } = require('webfunc')
const { graphqlHandler } = require('graphql-serverless')
const { makeExecutableSchema } = require('graphql-tools')
const glue = require('schemaglue')
const { schema, resolver } = glue('src/graphql')
const executableSchema = makeExecutableSchema({
typeDefs: schema,
resolvers: resolver
})
const graphqlOptions = {
schema: executableSchema,
graphiql: {
endpoint: '/graphiql'
}
}
app.all(['/', '/graphiql'], graphqlHandler(graphqlOptions))
app.listen(4000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment