Created
January 26, 2020 02:53
-
-
Save mattgrill/e28f91a2616cf3fb019de91f6184fe5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { ApolloServer, gql } = require("apollo-server"); | |
const { RESTDataSource } = require("apollo-datasource-rest"); | |
class RandomCard extends RESTDataSource { | |
constructor() { | |
super(); | |
this.baseURL = "https://rws-cards-api.herokuapp.com/api/v1/cards"; | |
} | |
async getCard() { | |
const card = await this.get("/"); | |
return card.cards[0]; | |
} | |
async getRandomCards(num) { | |
const card = await this.get(`/random?n=${num}`); | |
return card.cards; | |
} | |
} | |
module.exports = RandomCard; | |
// Construct a schema, using GraphQL schema language | |
const typeDefs = gql` | |
type Card { | |
num: String | |
name: String | |
desc: String | |
meaning_up: String | |
meaning_down: String | |
suit: String | |
type: String | |
} | |
type Query { | |
getCard: Card | |
getRandomCards(num: String!): [Card] | |
} | |
`; | |
// Provide resolver functions for your schema fields | |
const resolvers = { | |
Query: { | |
getCard: async (_, __, { dataSources }) => dataSources.RandomCard.getCard(), | |
getRandomCards: async (_, { num }, { dataSources }) => { | |
return dataSources.RandomCard.getRandomCards(num); | |
} | |
} | |
}; | |
const server = new ApolloServer({ | |
typeDefs, | |
resolvers, | |
dataSources: () => ({ | |
RandomCard: new RandomCard() | |
}) | |
}); | |
server.listen().then(({ url }) => { | |
console.log(`🚀 Server ready at ${url}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment