Skip to content

Instantly share code, notes, and snippets.

@TheMagoo73
Created March 31, 2020 10:16
Show Gist options
  • Save TheMagoo73/7ca73f1d2ac4befe3b85bb93968ff6c5 to your computer and use it in GitHub Desktop.
Save TheMagoo73/7ca73f1d2ac4befe3b85bb93968ff6c5 to your computer and use it in GitHub Desktop.
Get a quote of the day using Apollo and node-fetch
const express = require ('express')
const { ApolloServer, gql } = require('apollo-server-express')
const fetch = require('node-fetch')
const typeDefs = gql`
type Query {
quote: String
}
`
const resolvers = {
Query: {
quote: (root, args, context) => {
logger.log("info: Getting a quote")
return context.getQuote()
}
}
}
const getQuote = async () => {
const res = await fetch('https://type.fit/api/quotes')
const quotes = await res.json()
const quoteNumber = Math.floor( Math.random() * (quotes.length - 1))
return quotes[quoteNumber].text
}
const logger = {
log: msg => console.log(msg)
}
const server = new ApolloServer({typeDefs, resolvers, context: { getQuote, logger }})
const app = express()
server.applyMiddleware( {app} )
app.listen({port: 4000}, () => {
console.log('Server is running')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment