Skip to content

Instantly share code, notes, and snippets.

@matthewmueller
Last active July 6, 2016 09:41
Show Gist options
  • Save matthewmueller/1f92b88c074f0248edca8ff973373ba8 to your computer and use it in GitHub Desktop.
Save matthewmueller/1f92b88c074f0248edca8ff973373ba8 to your computer and use it in GitHub Desktop.
Simple Graph.ql server for tying in the Stripe + Diffbot services
let Graph = require('graph.ql')
module.exports = Graph(`
scalar Date
enum Size {
small
medium
large
}
type Feed {
# Feed ID
id: ID!
# Name of the author
author: String!
# Get the thumbnail of the author
# @param {Size} size - specify a thumbnail size
# @return {String} a URL of the string
thumbnail(size: Size): String
# Description
# @param {Int} length - specify a length
# @return {String} a description
description(length: Int): String
# Content of the article
content: String!
# Published
date_published: Date!
}
type User {
id: ID!
customer: Customer
}
type Customer {
stripe_id: ID!
delinquent: Boolean!
plan: String!
quantity: Int!
}
type Query {
# Fetch the contents of an article
# @param {String} token - Diffbot token
# @param {String} source - Source of the article as a URL
# @return {Feed} object containing the feed
feed(token: String!, source: String!): Feed
user(id: ID!): User
}
`, {
// Scalar resolvers
Date: {
serialize (v) {
return v.toISOString()
},
parse (v) {
return new Date(v)
}
},
// Feed model
//
// Note: I envision each one of these computed properties to be lambda functions.
Feed: {
thumbnail (feed, { size = 'medium' }) {
// assumes the diffbot object returns
// a shape like this: { thumbnails: { small: url, medium: url, large: url }}
return feed.thumbnails[size]
},
// assumes the diffbot object returns
// a shape like this: { thumbnails: { small: url, medium: url, large: url }}
description (feed, { length = 100 }) {
return feed.description.slice(0, length) + '...'
}
},
User: {
// fetch the user from stripe
* customer({ stripe_id }) {
// user.stripe_id is returned from the user's table,
// but isn't exposed by the GraphQL server
if (!stripe_id) return null
return yield stripe.customers.retrieve(stripe_id)
}
},
Query: {
// query diffbot
* feed (query, { url, token }) {
let response = yield request
.get(url)
.send('token', token)
.end()
if (!response.ok) throw new Error(response.text)
// big data object from Diffbot
return response.body
},
* user (query, { id }) {
// implicitly assumed state is bound and connected on this
return yield this.postgres.query(`
SELECT * FROM users WHERE id = :id
`, { id: id })
}
}
})
@matthewmueller
Copy link
Author

matthewmueller commented Jul 6, 2016

Implementation notes:

• First argument is the GraphQL schema, second argument are the custom resolvers
• Anything that doesn't have a custom resolver is assumed to: return instance[key]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment