-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
triggers.js
971 lines (912 loc) · 27.8 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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
// triggers.js
import Parse from 'parse/node';
import { logger } from './logger';
export const Types = {
beforeLogin: 'beforeLogin',
afterLogin: 'afterLogin',
afterLogout: 'afterLogout',
beforeSave: 'beforeSave',
afterSave: 'afterSave',
beforeDelete: 'beforeDelete',
afterDelete: 'afterDelete',
beforeFind: 'beforeFind',
afterFind: 'afterFind',
beforeSaveFile: 'beforeSaveFile',
afterSaveFile: 'afterSaveFile',
beforeDeleteFile: 'beforeDeleteFile',
afterDeleteFile: 'afterDeleteFile',
beforeConnect: 'beforeConnect',
beforeSubscribe: 'beforeSubscribe',
afterEvent: 'afterEvent',
};
const FileClassName = '@File';
const ConnectClassName = '@Connect';
const baseStore = function () {
const Validators = Object.keys(Types).reduce(function (base, key) {
base[key] = {};
return base;
}, {});
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.beforeLogin || type === Types.afterLogin) && className !== '_User') {
// TODO: check if upstream code will handle `Error` instance rather
// than this anti-pattern of throwing strings
throw 'Only the _User class is allowed for the beforeLogin and afterLogin triggers';
}
if (type === Types.afterLogout && className !== '_Session') {
// TODO: check if upstream code will handle `Error` instance rather
// than this anti-pattern of throwing strings
throw 'Only the _Session class is allowed for the afterLogout trigger.';
}
if (className === '_Session' && type !== Types.afterLogout) {
// TODO: check if upstream code will handle `Error` instance rather
// than this anti-pattern of throwing strings
throw 'Only the afterLogout trigger is allowed for the _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);
if (store[lastComponent]) {
logger.warn(
`Warning: Duplicate cloud functions exist for ${lastComponent}. Only the last one will be used and the others will be ignored.`
);
}
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, validationHandler) {
validateClassNameForTriggers(className, type);
add(Category.Triggers, `${type}.${className}`, handler, applicationId);
add(Category.Validators, `${type}.${className}`, validationHandler, applicationId);
}
export function addFileTrigger(type, handler, applicationId, validationHandler) {
add(Category.Triggers, `${type}.${FileClassName}`, handler, applicationId);
add(Category.Validators, `${type}.${FileClassName}`, validationHandler, applicationId);
}
export function addConnectTrigger(type, handler, applicationId, validationHandler) {
add(Category.Triggers, `${type}.${ConnectClassName}`, handler, applicationId);
add(Category.Validators, `${type}.${ConnectClassName}`, validationHandler, 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 async function runTrigger(trigger, name, request, auth) {
if (!trigger) {
return;
}
await maybeRunValidator(request, name, auth);
if (request.skipWithMasterKey) {
return;
}
return await trigger(request);
}
export function getFileTrigger(type, applicationId) {
return getTrigger(FileClassName, type, 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 getFunctionNames(applicationId) {
const store =
(_triggerStore[applicationId] && _triggerStore[applicationId][Category.Functions]) || {};
const functionNames = [];
const extractFunctionNames = (namespace, store) => {
Object.keys(store).forEach(name => {
const value = store[name];
if (namespace) {
name = `${namespace}.${name}`;
}
if (typeof value === 'function') {
functionNames.push(name);
} else {
extractFunctionNames(name, value);
}
});
};
extractFunctionNames(null, store);
return functionNames;
}
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 ||
triggerType === Types.beforeDelete ||
triggerType === Types.afterDelete ||
triggerType === Types.afterFind
) {
// 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, context, isGet) {
isGet = !!isGet;
var request = {
triggerName: triggerType,
query,
master: false,
count,
log: config.loggerController,
isGet,
headers: config.headers,
ip: config.ip,
context: 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;
}
// 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) {
return {
success: function (response) {
if (request.triggerName === Types.afterFind) {
if (!response) {
response = request.objects;
}
response = response.map(object => {
return object.toJSON();
});
return resolve(response);
}
// Use the JSON response
if (
response &&
typeof response === 'object' &&
!request.object.equals(response) &&
request.triggerName === Types.beforeSave
) {
return resolve(response);
}
if (response && typeof response === 'object' && request.triggerName === Types.afterSave) {
return resolve(response);
}
if (request.triggerName === Types.afterSave) {
return resolve();
}
response = {};
if (request.triggerName === Types.beforeSave) {
response['object'] = request.object._getSaveJSON();
response['object']['objectId'] = request.object.id;
}
return resolve(response);
},
error: function (error) {
const e = resolveError(error, {
code: Parse.Error.SCRIPT_FAILED,
message: 'Script failed. Unknown error.',
});
reject(e);
},
};
}
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),
}
);
}
export function maybeRunAfterFindTrigger(
triggerType,
auth,
className,
objects,
config,
query,
context
) {
return new Promise((resolve, reject) => {
const trigger = getTrigger(className, triggerType, config.applicationId);
if (!trigger) {
return resolve();
}
const request = getRequestObject(triggerType, auth, null, null, config, context);
if (query) {
request.query = query;
}
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(() => {
return maybeRunValidator(request, `${triggerType}.${className}`, auth);
})
.then(() => {
if (request.skipWithMasterKey) {
return request.objects;
}
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,
context,
isGet
) {
const trigger = getTrigger(className, triggerType, config.applicationId);
if (!trigger) {
return Promise.resolve({
restWhere,
restOptions,
});
}
const json = Object.assign({}, restOptions);
json.where = restWhere;
const parseQuery = new Parse.Query(className);
parseQuery.withJSON(json);
let count = false;
if (restOptions) {
count = !!restOptions.count;
}
const requestObject = getRequestQueryObject(
triggerType,
auth,
parseQuery,
count,
config,
context,
isGet
);
return Promise.resolve()
.then(() => {
return maybeRunValidator(requestObject, `${triggerType}.${className}`, auth);
})
.then(() => {
if (requestObject.skipWithMasterKey) {
return requestObject.query;
}
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.excludeKeys) {
restOptions = restOptions || {};
restOptions.excludeKeys = jsonQuery.excludeKeys;
}
if (jsonQuery.explain) {
restOptions = restOptions || {};
restOptions.explain = jsonQuery.explain;
}
if (jsonQuery.keys) {
restOptions = restOptions || {};
restOptions.keys = jsonQuery.keys;
}
if (jsonQuery.order) {
restOptions = restOptions || {};
restOptions.order = jsonQuery.order;
}
if (jsonQuery.hint) {
restOptions = restOptions || {};
restOptions.hint = jsonQuery.hint;
}
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 => {
const error = resolveError(err, {
code: Parse.Error.SCRIPT_FAILED,
message: 'Script failed. Unknown error.',
});
throw error;
}
);
}
export function resolveError(message, defaultOpts) {
if (!defaultOpts) {
defaultOpts = {};
}
if (!message) {
return new Parse.Error(
defaultOpts.code || Parse.Error.SCRIPT_FAILED,
defaultOpts.message || 'Script failed.'
);
}
if (message instanceof Parse.Error) {
return message;
}
const code = defaultOpts.code || Parse.Error.SCRIPT_FAILED;
// If it's an error, mark it as a script failed
if (typeof message === 'string') {
return new Parse.Error(code, message);
}
const error = new Parse.Error(code, message.message || message);
if (message instanceof Error) {
error.stack = message.stack;
}
return error;
}
export function maybeRunValidator(request, functionName, auth) {
const theValidator = getValidator(functionName, Parse.applicationId);
if (!theValidator) {
return;
}
if (typeof theValidator === 'object' && theValidator.skipWithMasterKey && request.master) {
request.skipWithMasterKey = true;
}
return new Promise((resolve, reject) => {
return Promise.resolve()
.then(() => {
return typeof theValidator === 'object'
? builtInTriggerValidator(theValidator, request, auth)
: theValidator(request);
})
.then(() => {
resolve();
})
.catch(e => {
const error = resolveError(e, {
code: Parse.Error.VALIDATION_ERROR,
message: 'Validation failed.',
});
reject(error);
});
});
}
async function builtInTriggerValidator(options, request, auth) {
if (request.master && !options.validateMasterKey) {
return;
}
let reqUser = request.user;
if (
!reqUser &&
request.object &&
request.object.className === '_User' &&
!request.object.existed()
) {
reqUser = request.object;
}
if (
(options.requireUser || options.requireAnyUserRoles || options.requireAllUserRoles) &&
!reqUser
) {
throw 'Validation failed. Please login to continue.';
}
if (options.requireMaster && !request.master) {
throw 'Validation failed. Master key is required to complete this request.';
}
let params = request.params || {};
if (request.object) {
params = request.object.toJSON();
}
const requiredParam = key => {
const value = params[key];
if (value == null) {
throw `Validation failed. Please specify data for ${key}.`;
}
};
const validateOptions = async (opt, key, val) => {
let opts = opt.options;
if (typeof opts === 'function') {
try {
const result = await opts(val);
if (!result && result != null) {
throw opt.error || `Validation failed. Invalid value for ${key}.`;
}
} catch (e) {
if (!e) {
throw opt.error || `Validation failed. Invalid value for ${key}.`;
}
throw opt.error || e.message || e;
}
return;
}
if (!Array.isArray(opts)) {
opts = [opt.options];
}
if (!opts.includes(val)) {
throw (
opt.error || `Validation failed. Invalid option for ${key}. Expected: ${opts.join(', ')}`
);
}
};
const getType = fn => {
const match = fn && fn.toString().match(/^\s*function (\w+)/);
return (match ? match[1] : '').toLowerCase();
};
if (Array.isArray(options.fields)) {
for (const key of options.fields) {
requiredParam(key);
}
} else {
const optionPromises = [];
for (const key in options.fields) {
const opt = options.fields[key];
let val = params[key];
if (typeof opt === 'string') {
requiredParam(opt);
}
if (typeof opt === 'object') {
if (opt.default != null && val == null) {
val = opt.default;
params[key] = val;
if (request.object) {
request.object.set(key, val);
}
}
if (opt.constant && request.object) {
if (request.original) {
request.object.set(key, request.original.get(key));
} else if (opt.default != null) {
request.object.set(key, opt.default);
}
}
if (opt.required) {
requiredParam(key);
}
const optional = !opt.required && val === undefined;
if (!optional) {
if (opt.type) {
const type = getType(opt.type);
const valType = Array.isArray(val) ? 'array' : typeof val;
if (valType !== type) {
throw `Validation failed. Invalid type for ${key}. Expected: ${type}`;
}
}
if (opt.options) {
optionPromises.push(validateOptions(opt, key, val));
}
}
}
}
await Promise.all(optionPromises);
}
let userRoles = options.requireAnyUserRoles;
let requireAllRoles = options.requireAllUserRoles;
const promises = [Promise.resolve(), Promise.resolve(), Promise.resolve()];
if (userRoles || requireAllRoles) {
promises[0] = auth.getUserRoles();
}
if (typeof userRoles === 'function') {
promises[1] = userRoles();
}
if (typeof requireAllRoles === 'function') {
promises[2] = requireAllRoles();
}
const [roles, resolvedUserRoles, resolvedRequireAll] = await Promise.all(promises);
if (resolvedUserRoles && Array.isArray(resolvedUserRoles)) {
userRoles = resolvedUserRoles;
}
if (resolvedRequireAll && Array.isArray(resolvedRequireAll)) {
requireAllRoles = resolvedRequireAll;
}
if (userRoles) {
const hasRole = userRoles.some(requiredRole => roles.includes(`role:${requiredRole}`));
if (!hasRole) {
throw `Validation failed. User does not match the required roles.`;
}
}
if (requireAllRoles) {
for (const requiredRole of requireAllRoles) {
if (!roles.includes(`role:${requiredRole}`)) {
throw `Validation failed. User does not match all the required roles.`;
}
}
}
const userKeys = options.requireUserKeys || [];
if (Array.isArray(userKeys)) {
for (const key of userKeys) {
if (!reqUser) {
throw 'Please login to make this request.';
}
if (reqUser.get(key) == null) {
throw `Validation failed. Please set data for ${key} on your account.`;
}
}
} else if (typeof userKeys === 'object') {
const optionPromises = [];
for (const key in options.requireUserKeys) {
const opt = options.requireUserKeys[key];
if (opt.options) {
optionPromises.push(validateOptions(opt, key, reqUser.get(key)));
}
}
await Promise.all(optionPromises);
}
}
// 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 => {
logTriggerSuccessBeforeHook(
triggerType,
parseObject.className,
parseObject.toJSON(),
object,
auth
);
if (
triggerType === Types.beforeSave ||
triggerType === Types.afterSave ||
triggerType === Types.beforeDelete ||
triggerType === Types.afterDelete
) {
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(() => {
return maybeRunValidator(request, `${triggerType}.${parseObject.className}`, auth);
})
.then(() => {
if (request.skipWithMasterKey) {
return Promise.resolve();
}
const promise = trigger(request);
if (
triggerType === Types.afterSave ||
triggerType === Types.afterDelete ||
triggerType === Types.afterLogin
) {
logTriggerAfterHook(triggerType, parseObject.className, parseObject.toJSON(), auth);
}
// beforeSave is expected to return null (nothing)
if (triggerType === Types.beforeSave) {
if (promise && typeof promise.then === 'function') {
return promise.then(response => {
// response.object may come from express routing before hook
if (response && response.object) {
return response;
}
return null;
});
}
return null;
}
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));
}
export function getRequestFileObject(triggerType, auth, fileObject, config) {
const request = {
...fileObject,
triggerName: triggerType,
master: false,
log: config.loggerController,
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;
}
export async function maybeRunFileTrigger(triggerType, fileObject, config, auth) {
const fileTrigger = getFileTrigger(triggerType, config.applicationId);
if (typeof fileTrigger === 'function') {
try {
const request = getRequestFileObject(triggerType, auth, fileObject, config);
await maybeRunValidator(request, `${triggerType}.${FileClassName}`, auth);
if (request.skipWithMasterKey) {
return fileObject;
}
const result = await fileTrigger(request);
logTriggerSuccessBeforeHook(
triggerType,
'Parse.File',
{ ...fileObject.file.toJSON(), fileSize: fileObject.fileSize },
result,
auth
);
return result || fileObject;
} catch (error) {
logTriggerErrorBeforeHook(
triggerType,
'Parse.File',
{ ...fileObject.file.toJSON(), fileSize: fileObject.fileSize },
auth,
error
);
throw error;
}
}
return fileObject;
}