-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.ts
131 lines (116 loc) · 2.63 KB
/
server.ts
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import { buildSchema } from 'graphql';
import * as Koa from 'koa';
import * as mount from 'koa-mount';
import * as convert from 'koa-convert';
import * as graphqlHTTP from 'koa-graphql';
import './connect';
import { User, Post, Album } from './models';
import { UserModel, PostModel, AlbumModel } from './interfaces';
const HTTP_PORT = 3000;
const app = new Koa();
const mySchema = buildSchema(`
type Geo {
lat: String
lng: String
}
type Address {
street: String
suite: String
city: String
zipcode: String
geo: Geo
}
type Company {
name: String
catchPhrase: String
bs: String
}
type Todo {
title: String
completed: Boolean
}
type Comment {
name: String
email: String
body: String
}
type Post {
_id: Int
_creator: User
title: String
body: String
comments: [Comment]
}
type Photo {
title: String
url: String
thumbnailUrl: String
}
type Album {
_id: Int
_creator: User
title: String
photos: [Photo]
}
type User {
_id: Int!
name: String
username: String
email: String
phone: String
website: String
company: Company
address: Address
todos: [Todo]
posts: [Post]
albums: [Album]
}
type Query {
user(_id: Int, username: String, email: String): User
users(name: String): [User]
todos(_id: Int): [Todo]
posts: [Post]
comments: [Comment]
albums: [Album]
photos: [Photo]
}
`);
const root = {
user: (args) => User.findOne(args).populate('posts albums'),
users: ({name}) => {
const regex = new RegExp(name, 'i');
return User.find({ name: regex }).populate('posts albums');
},
todos: (args) => {
return User.find({}, {_id: 0, todos: 1})
.then((users: UserModel[]) => {
return users.reduce((todos, user) => {
return [...todos, ...user.todos];
}, []);
});
},
posts: () => Post.find().populate('_creator'),
comments: () => {
return Post.find({}, {_id: 0, comments: 1})
.then((posts: PostModel[]) => {
return posts.reduce((comments, post) => {
return [...comments, ...post.comments];
}, []);
});
},
albums: () => Album.find().populate('_creator'),
photos: () => {
return Album.find({}, {_id: 0, photos: 1})
.then((albums: AlbumModel[]) => {
return albums.reduce((photos, album) => {
return [...photos, ...album.photos];
}, []);
});
}
};
app.use(mount('/graphql', convert(graphqlHTTP({
schema: mySchema,
rootValue: root,
graphiql: true
}))));
app.listen(HTTP_PORT, () => console.log(`Running in port ${HTTP_PORT}`));