UNPKG

decorator-x

Version:

decorator for entity instantiation & validation, auto-generate swagger docs & graphql schema

71 lines (66 loc) 1.62 kB
// @flow import { find, filter } from 'lodash'; import { makeExecutableSchema } from 'graphql-tools'; const typeDefs = ` type User { id: Int! firstName: String lastName: String posts: [Post] # the list of Posts by this author } type Post { id: Int! title: String author: User votes: Int } # the schema allows the following query: type Query { posts: [Post] user(id: Int!): User } # this schema allows the following mutation: type Mutation { upvotePost ( postId: Int! ): Post } `; // example data const authors = [ { id: 1, firstName: 'Tom', lastName: 'Coleman' }, { id: 2, firstName: 'Sashko', lastName: 'Stubailo' }, { id: 3, firstName: 'Mikhail', lastName: 'Novikov' } ]; const posts = [ { id: 1, authorId: 1, title: 'Introduction to GraphQL', votes: 2 }, { id: 2, authorId: 2, title: 'Welcome to Meteor', votes: 3 }, { id: 3, authorId: 2, title: 'Advanced GraphQL', votes: 1 }, { id: 4, authorId: 3, title: 'Launchpad is Cool', votes: 7 } ]; const resolvers = { Query: { posts: () => posts, user: (_, { id }) => find(authors, { id: id }) }, Mutation: { upvotePost: (_, { postId }) => { const post = find(posts, { id: postId }); if (!post) { throw new Error(`Couldn't find post with id ${postId}`); } post.votes += 1; return post; } }, User: { posts: author => filter(posts, { authorId: author.id }) }, Post: { author: post => find(authors, { id: post.authorId }) } }; export const graphqlSchema = makeExecutableSchema({ typeDefs, resolvers });