Skip to content

Instantly share code, notes, and snippets.

@Mefistophell
Created November 4, 2018 13:27
Show Gist options
  • Save Mefistophell/310ed6554d562d9199075f4cf3b275b9 to your computer and use it in GitHub Desktop.
Save Mefistophell/310ed6554d562d9199075f4cf3b275b9 to your computer and use it in GitHub Desktop.
Apollo-GraphQL-Books
const { ApolloServer, gql } = require('apollo-server');
// Type definitions define the "shape" of your data and specify
// which ways the data can be fetched from the GraphQL server.
const typeDefs = gql`
# Comments in GraphQL are defined with the hash (#) symbol.
# This "Book" type can be used in other type declarations.
type Book {
title: String!
author: String
createdAt: String
}
type BookInfo {
totalBooks: Int
recentlyAdded: Int
}
# The "Query" type is the root of all GraphQL queries.
type Query {
books: [Book!]!
}
# The "input" type used when you want to pass in a whole object to be created
input BookInput {
title: String!
author: String!
}
# The "Mutation" type is one of the root GraphQL types.
type Mutation {
addBook(book: BookInput!): BookInfo!
}
`;
// This is a (sample) collection of books we'll be able to query
// the GraphQL server for. A more complete example might fetch
// from an existing data source like a REST API or database.
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
createdAt: 'Sun, 28 Oct 2018 18:53:25 GMT'
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
createdAt: 'Sun, 28 Oct 2018 18:53:25 GMT'
},
];
// This function returns a predicate
const predicate = currentDate => (counter, { createdAt }) => new
Date(createdAt).getTime() + 3000 > currentDate.getTime() && counter + 1
// Resolvers define the technique for fetching the types in the
// schema. We'll retrieve books from the "books" array above.
const resolvers = {
Query: {
books: () => books,
},
Mutation: {
addBook: (obj, { book: { title, author } }) => {
const date = new Date();
const reducer = predicate(date)
books.push({ title, author, createdAt: date.toUTCString() })
const recentlyAdded = books.reduce(reducer, 0)
return {
totalBooks: books.length,
recentlyAdded: recentlyAdded
}
},
}
};
// In the most basic sense, the ApolloServer can be started
// by passing type definitions (typeDefs) and the resolvers
// responsible for fetching the data for those types.
const server = new ApolloServer({ typeDefs, resolvers });
// This `listen` method launches a web-server. Existing apps
// can utilize middleware options, which we'll discuss later.
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