1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| const { buildSchema } = require('graphql');
exports.schema = buildSchema(` type User { id: ID! name: String! posts: [Post!]! }
type Post { id: ID! user: User! title: String! }
type Query { users: [User!]! posts: [Post!]! } `);
const users = { 1: { id: 1, name: 'Memo Chou', }, };
const posts = { 1: { id: 1, user_id: 1, title: 'Post 1', }, 2: { id: 2, user_id: 1, title: 'Post 2', }, };
class GraphQLUser { constructor({ id, name }) { this.id = id; this.name = name; }
posts() { return Object.keys(posts) .map(id => new GraphQLPost(posts[id])) .filter(post => post.user_id === this.id); } }
class GraphQLPost { constructor({ id, user_id, title }) { this.id = id; this.user_id = user_id; this.title = title; }
user() { return new GraphQLUser(users[this.user_id]); } }
exports.rootValue = { users: () => Object.keys(users).map(id => new GraphQLUser(users[id])), posts: () => Object.keys(posts).map(id => new GraphQLPost(posts[id])), };
|