Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
87 lines (72 loc) · 1.68 KB
/
Copy pathindex.js
File metadata and controls
87 lines (72 loc) · 1.68 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const express = require("express")
const graphqlHTTP = require('express-graphql')
const cors = require('cors')
const { buildSchema } = require('graphql')
const schema = buildSchema(`
type Query {
posts: [Post]
post(id: ID): Post
authors: [Person]
author(id: ID): Person
}
type Post {
id: ID
author: Person
body: String
}
type Person {
id: ID
posts: [Post]
firstName: String
lastName: String
}
`)
const rootValue = {
posts: () => POSTS.values(),
post: ({ id }) => POSTS.get(id),
authors: () => PEOPLE.values(),
author: ({ id }) => PEOPLE.get(id)
}
const PEOPLE = new Map()
const POSTS = new Map()
class Post
{
constructor (data) {Object.assign(this, data)}
get author ()
{
return PEOPLE.get(this.authorID)
}
}
class Person
{
constructor (data) {Object.assign(this, data)}
get posts ()
{
return [...POSTS.values()].filter(post => post.authorID === this.id)
}
}
// fake data for testing
const initializeData = () => {
const fakePeople = [
{ id: '1', firstName: 'John', lastName: 'Doe' },
{ id: '2', firstName: 'Jane', lastName: 'Doe' }
]
fakePeople.forEach(person => PEOPLE.set(person.id, new Person(person)))
const fakePosts = [
{ id: '1', authorID: '1', body: 'Hello, world' },
{ id: '2', authorID: '2', body: 'Hi, planet' }
]
fakePosts.forEach(post => POSTS.set(post.id, new Post(post)))
}
initializeData()
// end fake data
const app = express()
app.use(cors())
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: rootValue,
graphiql: true
}))
const port = process.env.PORT || 4000
app.listen(port)
console.log(`Running a GraphQL API server at localhost: ${port}/graphql`)