-
Notifications
You must be signed in to change notification settings - Fork 52
/
query.js
344 lines (289 loc) · 7.44 KB
/
query.js
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import { forEach, isArray, isString } from 'lodash';
import { fromGlobalId, toGlobalId } from 'graphql-relay';
import getFieldList from './projection';
import viewer from '../model/viewer';
function processId({ id, _id = id }) {
// global or mongo id
if (isString(_id) && !/^[a-fA-F0-9]{24}$/.test(_id)) {
const { type, id } = fromGlobalId(_id);
if (type && /^[a-zA-Z]*$/.test(type)) {
return id;
}
}
return _id;
}
function getCount(Collection, selector) {
if (selector && (isArray(selector.id) || isArray(selector._id))) {
const { id, _id = id } = selector;
delete selector.id;
selector._id = {
$in: _id.map((id) => processId({ id }))
};
}
return Collection.count(selector);
}
function getOne(Collection, args, context, info) {
const id = processId(args);
const projection = getFieldList(info);
return Collection.findById(id, projection).then((result) => {
if (result) {
return {
...result.toObject(),
_type: Collection.modelName
};
}
return null;
});
}
function addOne(Collection, args) {
forEach(args, (arg, key) => {
if (isArray(arg)) {
args[key] = arg.map((id) => processId({ id }));
} else {
args[key] = processId({ id: arg });
}
});
const instance = new Collection(args);
return instance.save().then((result) => {
if (result) {
return {
...result.toObject(),
_type: Collection.modelName
};
}
return null;
});
}
function updateOne(Collection, { id, _id, ...args }, context, info) {
_id = processId({ id, _id });
forEach(args, (arg, key) => {
if (isArray(arg)) {
args[key] = arg.map((id) => processId({ id }));
} else {
args[key] = processId({ id: arg });
}
if (key.endsWith('_add')) {
const values = args[key];
args.$push = {
[key.slice(0, -'_add'.length)]: { $each: values }
};
delete args[key];
}
});
return Collection.update({ _id }, args).then((res) => {
if (res.ok) {
return getOne(Collection, { _id }, context, info);
}
return null;
});
}
function deleteOne(Collection, args) {
const _id = processId(args);
return Collection.remove({ _id }).then(({ result }) => ({
id: toGlobalId(Collection.modelName, _id),
ok: !!result.ok
}));
}
function getList(Collection, selector, options = {}, context, info = null) {
if (selector && (isArray(selector.id) || isArray(selector._id))) {
const { id, _id = id } = selector;
delete selector.id;
selector._id = {
$in: _id.map((id) => processId({ id }))
};
}
const projection = getFieldList(info);
return Collection.find(selector, projection, options).then((result) => (
result.map((value) => ({
...value.toObject(),
_type: Collection.modelName
}))
));
}
function getOneResolver(graffitiModel) {
return (root, args, context, info) => {
const Collection = graffitiModel.model;
if (Collection) {
return getOne(Collection, args, context, info);
}
return null;
};
}
function getAddOneMutateHandler(graffitiModel) {
// eslint-disable-next-line no-unused-vars
return ({ clientMutationId, ...args }) => {
const Collection = graffitiModel.model;
if (Collection) {
return addOne(Collection, args);
}
return null;
};
}
function getUpdateOneMutateHandler(graffitiModel) {
// eslint-disable-next-line no-unused-vars
return ({ clientMutationId, ...args }) => {
const Collection = graffitiModel.model;
if (Collection) {
return updateOne(Collection, args);
}
return null;
};
}
function getDeleteOneMutateHandler(graffitiModel) {
// eslint-disable-next-line no-unused-vars
return ({ clientMutationId, ...args }) => {
const Collection = graffitiModel.model;
if (Collection) {
return deleteOne(Collection, args);
}
return null;
};
}
function getListResolver(graffitiModel) {
return (root, { ids, ...args } = {}, context, info) => {
if (ids) {
args.id = ids;
}
const { orderBy: sort } = args;
delete args.orderBy;
const Collection = graffitiModel.model;
if (Collection) {
return getList(Collection, args, { sort }, context, info);
}
return null;
};
}
/**
* Returns the first element in a Collection
*/
function getFirst(Collection) {
return Collection.findOne({}, {}, { sort: { _id: 1 } });
}
/**
* Returns an idFetcher function, that can resolve
* an object based on a global id
*/
function getIdFetcher(graffitiModels) {
return function idFetcher(obj, { id: globalId }, context, info) {
const { type, id } = fromGlobalId(globalId);
if (type === 'Viewer') {
return viewer;
} else if (graffitiModels[type]) {
const Collection = graffitiModels[type].model;
return getOne(Collection, { id }, context, info);
}
return null;
};
}
/**
* Helper to get an empty connection.
*/
function emptyConnection() {
return {
count: 0,
edges: [],
pageInfo: {
startCursor: null,
endCursor: null,
hasPreviousPage: false,
hasNextPage: false
}
};
}
const PREFIX = 'connection.';
function base64(i) {
return ((new Buffer(i, 'ascii')).toString('base64'));
}
function unbase64(i) {
return ((new Buffer(i, 'base64')).toString('ascii'));
}
/**
* Creates the cursor string from an offset.
*/
function idToCursor(id) {
return base64(PREFIX + id);
}
/**
* Rederives the offset from the cursor string.
*/
function cursorToId(cursor) {
return unbase64(cursor).substring(PREFIX.length);
}
/**
* Given an optional cursor and a default offset, returns the offset
* to use; if the cursor contains a valid offset, that will be used,
* otherwise it will be the default.
*/
function getId(cursor) {
if (cursor === undefined || cursor === null) {
return null;
}
return cursorToId(cursor);
}
/**
* Returns a connection based on a graffitiModel
*/
async function connectionFromModel(graffitiModel, args, context, info) {
const Collection = graffitiModel.model;
if (!Collection) {
return emptyConnection();
}
const { before, after, first, last, id, orderBy = { _id: 1 }, ...selector } = args;
const begin = getId(after);
const end = getId(before);
const offset = (first - last) || 0;
const limit = last || first;
if (id) {
selector.id = id;
}
if (begin) {
selector._id = selector._id || {};
selector._id.$gt = begin;
}
if (end) {
selector._id = selector._id || {};
selector._id.$lt = end;
}
const result = await getList(Collection, selector, {
limit,
skip: offset,
sort: orderBy
}, context, info);
const count = await getCount(Collection, selector);
if (result.length === 0) {
return emptyConnection();
}
const edges = result.map((value) => ({
cursor: idToCursor(value._id),
node: value
}));
const firstElement = await getFirst(Collection);
return {
count,
edges,
pageInfo: {
startCursor: edges[0].cursor,
endCursor: edges[edges.length - 1].cursor,
hasPreviousPage: cursorToId(edges[0].cursor) !== firstElement._id.toString(),
hasNextPage: result.length === limit
}
};
}
export default {
getOneResolver,
getListResolver,
getAddOneMutateHandler,
getUpdateOneMutateHandler,
getDeleteOneMutateHandler
};
export {
idToCursor as _idToCursor,
idToCursor,
getIdFetcher,
getOneResolver,
getAddOneMutateHandler,
getUpdateOneMutateHandler,
getDeleteOneMutateHandler,
getListResolver,
connectionFromModel
};