-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
triggers.js
640 lines (596 loc) · 16.3 KB
/
triggers.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// triggers.js
import Parse from 'parse/node';
import {
logger
} from './logger';
export const Types = {
beforeSave: 'beforeSave',
afterSave: 'afterSave',
beforeDelete: 'beforeDelete',
afterDelete: 'afterDelete',
beforeFind: 'beforeFind',
afterFind: 'afterFind',
};
const baseStore = function () {
const Validators = {};
const Functions = {};
const Jobs = {};
const LiveQuery = [];
const Triggers = Object.keys(Types).reduce(function (base, key) {
base[key] = {};
return base;
}, {});
return Object.freeze({
Functions,
Jobs,
Validators,
Triggers,
LiveQuery,
});
};
function validateClassNameForTriggers(className, type) {
if (type == Types.beforeSave && className === '_PushStatus') {
// _PushStatus uses undocumented nested key increment ops
// allowing beforeSave would mess up the objects big time
// TODO: Allow proper documented way of using nested increment ops
throw 'Only afterSave is allowed on _PushStatus';
}
if (
(type == Types.beforeFind || type == Types.afterFind) &&
className === '_Session'
) {
throw 'beforeFind/afterFind is not allowed on _Session class.';
}
return className;
}
const _triggerStore = {};
const Category = {
Functions: 'Functions',
Validators: 'Validators',
Jobs: 'Jobs',
Triggers: 'Triggers',
};
function getStore(category, name, applicationId) {
const path = name.split('.');
path.splice(-1); // remove last component
applicationId = applicationId || Parse.applicationId;
_triggerStore[applicationId] = _triggerStore[applicationId] || baseStore();
let store = _triggerStore[applicationId][category];
for (const component of path) {
store = store[component];
if (!store) {
return undefined;
}
}
return store;
}
function add(category, name, handler, applicationId) {
const lastComponent = name.split('.').splice(-1);
const store = getStore(category, name, applicationId);
store[lastComponent] = handler;
}
function remove(category, name, applicationId) {
const lastComponent = name.split('.').splice(-1);
const store = getStore(category, name, applicationId);
delete store[lastComponent];
}
function get(category, name, applicationId) {
const lastComponent = name.split('.').splice(-1);
const store = getStore(category, name, applicationId);
return store[lastComponent];
}
export function addFunction(
functionName,
handler,
validationHandler,
applicationId
) {
add(Category.Functions, functionName, handler, applicationId);
add(Category.Validators, functionName, validationHandler, applicationId);
}
export function addJob(jobName, handler, applicationId) {
add(Category.Jobs, jobName, handler, applicationId);
}
export function addTrigger(type, className, handler, applicationId) {
validateClassNameForTriggers(className, type);
add(Category.Triggers, `${type}.${className}`, handler, applicationId);
}
export function addLiveQueryEventHandler(handler, applicationId) {
applicationId = applicationId || Parse.applicationId;
_triggerStore[applicationId] = _triggerStore[applicationId] || baseStore();
_triggerStore[applicationId].LiveQuery.push(handler);
}
export function removeFunction(functionName, applicationId) {
remove(Category.Functions, functionName, applicationId);
}
export function removeTrigger(type, className, applicationId) {
remove(Category.Triggers, `${type}.${className}`, applicationId);
}
export function _unregisterAll() {
Object.keys(_triggerStore).forEach(appId => delete _triggerStore[appId]);
}
export function getTrigger(className, triggerType, applicationId) {
if (!applicationId) {
throw 'Missing ApplicationID';
}
return get(Category.Triggers, `${triggerType}.${className}`, applicationId);
}
export function triggerExists(
className: string,
type: string,
applicationId: string
): boolean {
return getTrigger(className, type, applicationId) != undefined;
}
export function getFunction(functionName, applicationId) {
return get(Category.Functions, functionName, applicationId);
}
export function getJob(jobName, applicationId) {
return get(Category.Jobs, jobName, applicationId);
}
export function getJobs(applicationId) {
var manager = _triggerStore[applicationId];
if (manager && manager.Jobs) {
return manager.Jobs;
}
return undefined;
}
export function getValidator(functionName, applicationId) {
return get(Category.Validators, functionName, applicationId);
}
export function getRequestObject(
triggerType,
auth,
parseObject,
originalParseObject,
config,
context
) {
const request = {
triggerName: triggerType,
object: parseObject,
master: false,
log: config.loggerController,
headers: config.headers,
ip: config.ip,
};
if (originalParseObject) {
request.original = originalParseObject;
}
if (triggerType === Types.beforeSave || triggerType === Types.afterSave) {
// Set a copy of the context on the request object.
request.context = Object.assign({}, context);
}
if (!auth) {
return request;
}
if (auth.isMaster) {
request['master'] = true;
}
if (auth.user) {
request['user'] = auth.user;
}
if (auth.installationId) {
request['installationId'] = auth.installationId;
}
return request;
}
export function getRequestQueryObject(
triggerType,
auth,
query,
count,
config,
isGet
) {
isGet = !!isGet;
var request = {
triggerName: triggerType,
query,
master: false,
count,
log: config.loggerController,
isGet,
headers: config.headers,
ip: config.ip,
};
if (!auth) {
return request;
}
if (auth.isMaster) {
request['master'] = true;
}
if (auth.user) {
request['user'] = auth.user;
}
if (auth.installationId) {
request['installationId'] = auth.installationId;
}
return request;
}
// Creates the response object, and uses the request object to pass data
// The API will call this with REST API formatted objects, this will
// transform them to Parse.Object instances expected by Cloud Code.
// Any changes made to the object in a beforeSave will be included.
export function getResponseObject(request, resolve, reject) {
const className = request.object ? request.object.className : null;
const isSessionTrigger = className === '_Session';
return {
success: function (response) {
if (request.triggerName === Types.afterFind) {
if (!response) {
response = request.objects;
}
response = response.map(object => {
return object.toJSON();
});
return resolve(response);
}
// ignore edited object in session triggers
if (isSessionTrigger) {
return resolve();
}
// Use the JSON response
if (
response &&
!request.object.equals(response) &&
request.triggerName === Types.beforeSave
) {
return resolve(response);
}
response = {};
if (request.triggerName === Types.beforeSave) {
response['object'] = request.object._getSaveJSON();
}
return resolve(response);
},
error: function (error) {
// ignore errors thrown in before-delete (during logout for example)
if (isSessionTrigger && request.triggerName === Types.beforeDelete) {
return resolve(undefined, error);
}
if (error instanceof Parse.Error) {
reject(error);
} else if (error instanceof Error) {
reject(new Parse.Error(Parse.Error.SCRIPT_FAILED, error.message));
} else {
reject(new Parse.Error(Parse.Error.SCRIPT_FAILED, error));
}
},
};
}
function userIdForLog(auth) {
return auth && auth.user ? auth.user.id : undefined;
}
function logTriggerAfterHook(triggerType, className, input, auth) {
const cleanInput = logger.truncateLogMessage(JSON.stringify(input));
logger.info(
`${triggerType} triggered for ${className} for user ${userIdForLog(
auth
)}:\n Input: ${cleanInput}`, {
className,
triggerType,
user: userIdForLog(auth),
}
);
}
function logTriggerSuccessBeforeHook(
triggerType,
className,
input,
result,
auth
) {
const cleanInput = logger.truncateLogMessage(JSON.stringify(input));
const cleanResult = logger.truncateLogMessage(JSON.stringify(result));
logger.info(
`${triggerType} triggered for ${className} for user ${userIdForLog(
auth
)}:\n Input: ${cleanInput}\n Result: ${cleanResult}`, {
className,
triggerType,
user: userIdForLog(auth),
}
);
}
function logTriggerErrorBeforeHook(triggerType, className, input, auth, error) {
const cleanInput = logger.truncateLogMessage(JSON.stringify(input));
logger.error(
`${triggerType} failed for ${className} for user ${userIdForLog(
auth
)}:\n Input: ${cleanInput}\n Error: ${JSON.stringify(error)}`, {
className,
triggerType,
error,
user: userIdForLog(auth),
}
);
}
function logWarningWhenErrorIsIgnored(triggerType, className, auth, error) {
logger.warn(
`Error ignored in ${triggerType} for ${className} for user ${userIdForLog(
auth
)}:\n Error: ${JSON.stringify(error)}`, {
className,
triggerType,
error,
user: userIdForLog(auth),
}
);
}
export function maybeRunAfterFindTrigger(
triggerType,
auth,
className,
objects,
config
) {
return new Promise((resolve, reject) => {
const trigger = getTrigger(className, triggerType, config.applicationId);
if (!trigger) {
return resolve();
}
const request = getRequestObject(triggerType, auth, null, null, config);
const {
success,
error
} = getResponseObject(
request,
object => {
resolve(object);
},
error => {
reject(error);
}
);
logTriggerSuccessBeforeHook(
triggerType,
className,
'AfterFind',
JSON.stringify(objects),
auth
);
request.objects = objects.map(object => {
//setting the class name to transform into parse object
object.className = className;
return Parse.Object.fromJSON(object);
});
return Promise.resolve()
.then(() => {
const response = trigger(request);
if (response && typeof response.then === 'function') {
return response.then(results => {
if (!results) {
throw new Parse.Error(
Parse.Error.SCRIPT_FAILED,
'AfterFind expect results to be returned in the promise'
);
}
return results;
});
}
return response;
})
.then(success, error);
}).then(results => {
logTriggerAfterHook(triggerType, className, JSON.stringify(results), auth);
return results;
});
}
export function maybeRunQueryTrigger(
triggerType,
className,
restWhere,
restOptions,
config,
auth,
isGet
) {
const trigger = getTrigger(className, triggerType, config.applicationId);
if (!trigger) {
return Promise.resolve({
restWhere,
restOptions,
});
}
const parseQuery = new Parse.Query(className);
if (restWhere) {
parseQuery._where = restWhere;
}
let count = false;
if (restOptions) {
if (restOptions.include && restOptions.include.length > 0) {
parseQuery._include = restOptions.include.split(',');
}
if (restOptions.skip) {
parseQuery._skip = restOptions.skip;
}
if (restOptions.limit) {
parseQuery._limit = restOptions.limit;
}
count = !!restOptions.count;
}
const requestObject = getRequestQueryObject(
triggerType,
auth,
parseQuery,
count,
config,
isGet
);
return Promise.resolve()
.then(() => {
return trigger(requestObject);
})
.then(
result => {
let queryResult = parseQuery;
if (result && result instanceof Parse.Query) {
queryResult = result;
}
const jsonQuery = queryResult.toJSON();
if (jsonQuery.where) {
restWhere = jsonQuery.where;
}
if (jsonQuery.limit) {
restOptions = restOptions || {};
restOptions.limit = jsonQuery.limit;
}
if (jsonQuery.skip) {
restOptions = restOptions || {};
restOptions.skip = jsonQuery.skip;
}
if (jsonQuery.include) {
restOptions = restOptions || {};
restOptions.include = jsonQuery.include;
}
if (jsonQuery.keys) {
restOptions = restOptions || {};
restOptions.keys = jsonQuery.keys;
}
if (jsonQuery.order) {
restOptions = restOptions || {};
restOptions.order = jsonQuery.order;
}
if (requestObject.readPreference) {
restOptions = restOptions || {};
restOptions.readPreference = requestObject.readPreference;
}
if (requestObject.includeReadPreference) {
restOptions = restOptions || {};
restOptions.includeReadPreference =
requestObject.includeReadPreference;
}
if (requestObject.subqueryReadPreference) {
restOptions = restOptions || {};
restOptions.subqueryReadPreference =
requestObject.subqueryReadPreference;
}
return {
restWhere,
restOptions,
};
},
err => {
if (typeof err === 'string') {
throw new Parse.Error(1, err);
} else {
throw err;
}
}
);
}
// To be used as part of the promise chain when saving/deleting an object
// Will resolve successfully if no trigger is configured
// Resolves to an object, empty or containing an object key. A beforeSave
// trigger will set the object key to the rest format object to save.
// originalParseObject is optional, we only need that for before/afterSave functions
export function maybeRunTrigger(
triggerType,
auth,
parseObject,
originalParseObject,
config,
context
) {
if (!parseObject) {
return Promise.resolve({});
}
return new Promise(function (resolve, reject) {
var trigger = getTrigger(
parseObject.className,
triggerType,
config.applicationId
);
if (!trigger) return resolve();
var request = getRequestObject(
triggerType,
auth,
parseObject,
originalParseObject,
config,
context
);
var {
success,
error
} = getResponseObject(
request,
(object, error) => {
if (error) {
logWarningWhenErrorIsIgnored(triggerType, parseObject.className, auth, error);
}
logTriggerSuccessBeforeHook(
triggerType,
parseObject.className,
parseObject.toJSON(),
object,
auth
);
if (
triggerType === Types.beforeSave ||
triggerType === Types.afterSave
) {
Object.assign(context, request.context);
}
resolve(object);
},
error => {
logTriggerErrorBeforeHook(
triggerType,
parseObject.className,
parseObject.toJSON(),
auth,
error
);
reject(error);
}
);
// AfterSave and afterDelete triggers can return a promise, which if they
// do, needs to be resolved before this promise is resolved,
// so trigger execution is synced with RestWrite.execute() call.
// If triggers do not return a promise, they can run async code parallel
// to the RestWrite.execute() call.
return Promise.resolve()
.then(() => {
const promise = trigger(request);
if (
triggerType === Types.afterSave ||
triggerType === Types.afterDelete
) {
logTriggerAfterHook(
triggerType,
parseObject.className,
parseObject.toJSON(),
auth
);
}
return promise;
})
.then(success, error);
});
}
// Converts a REST-format object to a Parse.Object
// data is either className or an object
export function inflate(data, restObject) {
var copy = typeof data == 'object' ? data : {
className: data
};
for (var key in restObject) {
copy[key] = restObject[key];
}
return Parse.Object.fromJSON(copy);
}
export function runLiveQueryEventHandlers(
data,
applicationId = Parse.applicationId
) {
if (
!_triggerStore ||
!_triggerStore[applicationId] ||
!_triggerStore[applicationId].LiveQuery
) {
return;
}
_triggerStore[applicationId].LiveQuery.forEach(handler => handler(data));
}