-
-
Notifications
You must be signed in to change notification settings - Fork 595
/
Copy pathtests.ts
2256 lines (1871 loc) · 66.3 KB
/
tests.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
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Parse from 'parse';
import ParseNode from 'parse/node';
import ParseRN from 'parse/react-native';
class GameScore extends Parse.Object {
constructor() {
super('GameScore');
}
}
class Game extends Parse.Object {
constructor() {
super('Game');
}
}
async function test_config() {
await Parse.Config.save({ foo: 'bar' }, { foo: true });
await Parse.Config.get({ useMasterKey: true });
}
async function test_object() {
const game = new Game();
game
.save(null, {
useMasterKey: true,
sessionToken: 'sometoken',
cascadeSave: false,
})
.then(result => result)
.catch(error => error);
// $ExpectType boolean
game.isNew();
// $ExpectType Pointer
game.toPointer();
// $ExpectType string
game.toPointer().className;
await game.fetch({});
// Create a new instance of that class.
const gameScore = new GameScore();
gameScore.set('score', 1337);
gameScore.set('playerName', 'Sean Plott');
gameScore.set('cheatMode', false);
// Setting attrs using object
gameScore.set({
level: '10',
difficult: 15,
});
gameScore.get('score');
gameScore.get('playerName');
gameScore.get('cheatMode');
gameScore.increment('score');
gameScore.addUnique('skills', 'flying');
gameScore.addUnique('skills', 'kungfu');
gameScore.addAll('skills', ['kungfu']);
gameScore.addAllUnique('skills', ['kungfu']);
gameScore.remove('skills', 'flying');
gameScore.removeAll('skills', ['kungFu']);
game.set('gameScore', gameScore);
// $ExpectType ParseObject<Attributes>
Game.fromJSON(JSON.parse(JSON.stringify(game)), true);
const object = new Parse.Object('TestObject');
object.equals(gameScore);
await object.fetchWithInclude(['key1', 'key2']);
}
function test_errors() {
const error = new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'sdfds');
// $ExpectType number
error.code;
// $ExpectType string
error.message;
}
async function test_query() {
const gameScore = new GameScore();
const query = new Parse.Query(GameScore);
query.equalTo('playerName', 'Dan Stemkoski');
query.notEqualTo('playerName', 'Michael Yabuti');
query.fullText('playerName', 'dan', {
language: 'en',
caseSensitive: false,
diacriticSensitive: true,
});
query.greaterThan('playerAge', 18);
await query.eachBatch(objs => {}, { batchSize: 10 });
await query.each(score => {});
query.hint('_id_');
query.explain(true);
query.limit(10);
query.skip(10);
// Sorts the results in ascending order by the score field
query.ascending('score');
// Sorts the results in descending order by the score field
query.descending('score');
// Restricts to wins < 50
query.lessThan('wins', 50);
// Restricts to wins <= 50
query.lessThanOrEqualTo('wins', 50);
// Restricts to wins > 50
query.greaterThan('wins', 50);
// Restricts to wins >= 50
query.greaterThanOrEqualTo('wins', 50);
query.containedBy('place', ['1', '2']);
// Finds scores from any of Jonathan, Dario, or Shawn
query.containedIn('playerName', ['Jonathan Walsh', 'Dario Wunsch', 'Shawn Simon']);
// Finds scores from anyone who is neither Jonathan, Dario, nor Shawn
query.notContainedIn('playerName', ['Jonathan Walsh', 'Dario Wunsch', 'Shawn Simon']);
// Finds objects that have the score set
query.exists('score');
// Finds objects that don't have the score set
query.doesNotExist('score');
query.matchesKeyInQuery('hometown', 'city', query);
query.doesNotMatchKeyInQuery('hometown', 'city', query);
query.select('score', 'playerName');
// Find objects where the array in arrayKey contains 2.
query.equalTo('arrayKey', 2);
// Find objects where the array in arrayKey contains all of the elements 2, 3, and 4.
query.containsAll('arrayKey', [2, 3, 4]);
query.containsAllStartingWith('arrayKey', ['2', '3', '4']);
query.startsWith('name', "Big Daddy's");
query.equalTo('score', gameScore);
query.exists('score');
query.include('score');
query.include('score', 'team');
query.include(['score.team']);
query.include('*');
query.includeAll();
query.sortByTextScore();
// Find objects that match the aggregation pipeline
await query.aggregate({
group: {
objectId: '$name',
},
});
await query.aggregate({
count: 'total',
});
await query.aggregate({
lookup: {
from: 'Collection',
foreignField: 'id',
localField: 'id',
as: 'result',
},
});
await query.aggregate({
lookup: {
from: 'Target',
let: { foo: 'bar', baz: 123 },
pipeline: [],
as: 'result',
},
});
await query.aggregate({
graphLookup: {
from: 'Target',
connectFromField: 'objectId',
connectToField: 'newId',
as: 'result',
},
});
await query.aggregate({
facet: {
foo: [
{
count: 'total',
},
],
bar: [
{
group: {
objectId: '$name',
},
},
],
},
});
await query.aggregate({
unwind: '$field',
});
await query.aggregate({
unwind: {
path: '$field',
includeArrayIndex: 'newIndex',
preserveNullAndEmptyArrays: true,
},
});
// Find objects with distinct key
await query.distinct('name');
const testQuery = Parse.Query.or(query, query);
}
function test_query_exclude() {
const gameScore = new GameScore();
const query = new Parse.Query(GameScore);
// Show all keys, except the specified key.
query.exclude('place');
const testQuery = Parse.Query.or(query, query);
}
async function test_query_promise() {
// Test promise with a query
const findQuery = new Parse.Query('Test');
findQuery
.find()
.then(() => {
// success
})
.catch(() => {
// error
});
const getQuery = new Parse.Query('Test');
try {
await getQuery.get('objectId');
} catch (error) {
// noop
}
await getQuery.map((score, index) => score.increment('score', index));
await getQuery.reduce((accum, score, index) => (accum += score.get('score')), 0);
await getQuery.reduce((accum, score, index) => (accum += score.get('score')), 0, {
batchSize: 200,
});
await getQuery.filter(scores => scores.get('score') > 0);
await getQuery.filter(scores => scores.get('score') > 0, { batchSize: 10 });
}
async function test_live_query() {
const subscription = await new Parse.Query('Test').subscribe();
subscription.on('close', (object: Parse.Object) => {
// $ExpectType ParseObject<Attributes>
object;
});
subscription.on('create', (object: Parse.Object) => {
// $ExpectType ParseObject<Attributes>
object;
});
subscription.on('delete', (object: Parse.Object) => {
// $ExpectType ParseObject<Attributes>
object;
});
subscription.on('enter', (object: Parse.Object) => {
// $ExpectType ParseObject<Attributes>
object;
});
subscription.on('leave', (object: Parse.Object) => {
// $ExpectType ParseObject<Attributes>
object;
});
subscription.on('open', (object: Parse.Object) => {
// $ExpectType ParseObject<Attributes>
object;
});
subscription.on('update', (object: Parse.Object) => {
// $ExpectType ParseObject<Attributes>
object;
});
}
async function test_anonymous_utils() {
// $ExpectType boolean
Parse.AnonymousUtils.isLinked(new Parse.User());
// $ExpectType ParseUser<Attributes>
await Parse.AnonymousUtils.link(new Parse.User(), { useMasterKey: true, sessionToken: '' });
// $ExpectType ParseUser<Attributes>
await Parse.AnonymousUtils.logIn({ useMasterKey: true, sessionToken: '' });
}
function return_a_query(): Parse.Query {
return new Parse.Query(Game);
}
async function test_each() {
await new Parse.Query(Game).each(game => {
// $ExpectType Game
game;
});
}
async function test_file() {
const base64 = 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=';
let file = new Parse.File('myfile.txt', { base64 });
file = new Parse.File('nana', { uri: 'http://example.com/image.jps' });
const bytes = [0xbe, 0xef, 0xca, 0xfe];
file = new Parse.File('myfile.txt', bytes);
file = new Parse.File('myfile.zzz', new Blob(), 'image/png');
const src = file.url();
const secure = file.url({ forceSecure: true });
await file.save();
file.cancel();
await file.destroy();
}
function test_file_tags_and_metadata() {
const base64 = 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=';
const file = new Parse.File('myfile.txt', { base64 });
file.setTags({ ownerId: 42, status: 'okay' });
file.addTag('labes', 'one');
file.setMetadata({ contentType: 'plain/text', contentLength: 579 });
file.addMetadata('author', 'John Doe');
// $ExpectType Record<string, any>
file.tags();
// $ExpectType Record<string, any>
file.metadata();
}
async function test_analytics() {
const dimensions = {
// Define ranges to bucket data points into meaningful segments
priceRange: '1000-1500',
// Did the user filter the query?
source: 'craigslist',
// Do searches happen more often on weekdays or weekends?
dayType: 'weekday',
};
// Send the dimensions to Parse along with the 'search' event
await Parse.Analytics.track('search', dimensions);
const codeString = '404';
await Parse.Analytics.track('error', { code: codeString });
}
function test_relation() {
const game1 = new Game();
const game2 = new Game();
new Parse.User()
.relation<Game>('games')
.query()
.find()
.then((g: Game[]) => {})
.catch(error => error);
new Parse.User().relation('games').add(game1);
new Parse.User().relation('games').add([game1, game2]);
new Parse.User().relation('games').remove(game1);
new Parse.User().relation('games').remove([game1, game2]);
}
async function test_user() {
const user = new Parse.User();
user.set('username', 'my name');
user.set('password', 'my pass');
user.set('email', '[email protected]');
await user.signUp(null, { useMasterKey: true });
const anotherUser: Parse.User = Parse.User.fromJSON({});
anotherUser.set('email', '[email protected]');
}
async function test_user_currentAsync() {
const asyncUser = await Parse.User.currentAsync();
if (asyncUser) {
asyncUser.set('email', '[email protected]');
} else if (asyncUser === null) {
await Parse.User.logIn('[email protected]', 'my pass');
}
}
async function test_user_acl_roles() {
const user = new Parse.User();
user.set('username', 'my name');
user.set('password', 'my pass');
user.set('email', '[email protected]');
// other fields can be set just like with Parse.Object
user.set('phone', '415-392-0202');
const currentUser = Parse.User.current();
if (currentUser) {
// do stuff with the user
} else {
// show the signup or login page
}
Parse.User.become('session-token-here')
.then(
user => {
// The current user is now set to user.
},
error => {
// The token could not be validated.
}
)
.catch(error => error);
Parse.User.hydrate({})
.then(
user => {
// The current user is now set to user.
},
error => {
// The token could not be validated.
}
)
.catch(error => error);
const game = new Game();
game.set('gameScore', new GameScore());
game.setACL(new Parse.ACL(Parse.User.current()));
game
.save()
.then((game: Game) => {})
.catch(error => error);
await game.save(null, { useMasterKey: true });
game
.save({ score: '10' }, { useMasterKey: true })
.then(
game => {
// Update game then revert it to the last saved state.
game.set('score', '20');
game.revert('score');
game.revert('score', 'ACL');
game.revert();
},
error => {
// The save failed
}
)
.catch(error => error);
const groupACL = new Parse.ACL();
const userList: Parse.User[] = [Parse.User.current()!];
// userList is an array with the users we are sending this message to.
for (const userListItem of userList) {
groupACL.setReadAccess(userListItem, true);
groupACL.setWriteAccess(userListItem, true);
}
groupACL.setPublicReadAccess(true);
game.setACL(groupACL);
Parse.User.requestPasswordReset('[email protected]')
.then(
data => {
// The current user is now set to user.
},
error => {
// The token could not be validated.
}
)
.catch(error => error);
Parse.User.requestEmailVerification('[email protected]')
.then(
data => {
// The current user is now set to user.
},
error => {
// The token could not be validated.
}
)
.catch(error => error);
// By specifying no write privileges for the ACL, we can ensure the role cannot be altered.
const role = new Parse.Role('Administrator', groupACL);
role.getUsers().add(userList[0]);
role.getRoles().add(role);
await role.save();
await Parse.User.logOut()
.then(data => {
// logged out
})
.catch(error => error);
}
async function test_facebook_util() {
Parse.FacebookUtils.init({
appId: 'YOUR_APP_ID', // Facebook App ID
channelUrl: '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
cookie: true, // enable cookies to allow Parse to access the session
xfbml: true, // parse XFBML
});
await Parse.FacebookUtils.logIn(null, {
success: (user: Parse.User) => {
if (!user.existed()) {
alert('User signed up and logged in through Facebook!');
} else {
alert('User logged in through Facebook!');
}
},
error: (user: Parse.User, error: any) => {
alert('User cancelled the Facebook login or did not fully authorize.');
},
});
const user = Parse.User.current()!;
if (!Parse.FacebookUtils.isLinked(user)) {
await Parse.FacebookUtils.link(user, null, {
success: (user: any) => {
alert('Woohoo, user logged in with Facebook!');
},
error: (user: any, error: any) => {
alert('User cancelled the Facebook login or did not fully authorize.');
},
});
}
await Parse.FacebookUtils.unlink(user, {
success: (user: Parse.User) => {
alert('The user is no longer associated with their Facebook account.');
},
});
}
async function test_cloud_functions() {
// $ExpectType any
await Parse.Cloud.run('SomeFunction');
// $ExpectType any
await Parse.Cloud.run('SomeFunction', { something: 'whatever' });
// $ExpectType any
await Parse.Cloud.run('SomeFunction', null, { useMasterKey: true });
// ExpectType boolean
await Parse.Cloud.run<() => boolean>('SomeFunction');
// $ExpectType boolean
await Parse.Cloud.run<() => boolean>('SomeFunction', null);
// $ExpectType boolean
await Parse.Cloud.run<() => boolean>('SomeFunction', null, { useMasterKey: true });
// $ExpectType number
await Parse.Cloud.run<(params: { paramA: string }) => number>('SomeFunction', {
paramA: 'hello',
});
// $ExpectError
await Parse.Cloud.run<(params: { paramA: string }) => number>('SomeFunction');
await Parse.Cloud.run<(params: { paramA: string }) => number>('SomeFunction', {
// $ExpectError
paramZ: 'hello',
});
// $ExpectError
await Parse.Cloud.run<(params: { paramA: string }) => number>('SomeFunction', null, {
useMasterKey: true,
});
// $ExpectError
await Parse.Cloud.run<(params: string) => any>('SomeFunction', 'hello');
// Parse.Cloud.afterDelete('MyCustomClass', (request: Parse.Cloud.AfterDeleteRequest) => {
// // result
// });
// Parse.Cloud.afterSave('MyCustomClass', (request: Parse.Cloud.AfterSaveRequest) => {
// if (!request.context) {
// throw new Error('Request context should be defined');
// }
// // result
// });
// Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest) => {
// // result
// });
// Parse.Cloud.beforeDelete('MyCustomClass', async (request: Parse.Cloud.BeforeDeleteRequest) => {
// // result
// });
// interface BeforeSaveObject {
// immutable: boolean;
// }
// Parse.Cloud.beforeSave('MyCustomClass', request => {
// if (request.object.isNew()) {
// if (!request.object.has('immutable')) throw new Error('Field immutable is required');
// } else {
// const original = request.original;
// if (original == null) {
// // When the object is not new, request.original must be defined
// throw new Error('Original must me defined for an existing object');
// }
// if (original.get('immutable') !== request.object.get('immutable')) {
// throw new Error('This field cannot be changed');
// }
// }
// if (!request.context) {
// throw new Error('Request context should be defined');
// }
// });
// Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => {
// const query = request.query; // the Parse.Query
// const user = request.user; // the user
// const isMaster = request.master; // if the query is run with masterKey
// const isCount = request.count; // if the query is a count operation (available on parse-server 2.4.0 or up)
// const isGet = request.isGet; // if the query is a get operation
// // All possible read preferences
// request.readPreference = Parse.Cloud.ReadPreferenceOption.Primary;
// request.readPreference = Parse.Cloud.ReadPreferenceOption.PrimaryPreferred;
// request.readPreference = Parse.Cloud.ReadPreferenceOption.Secondary;
// request.readPreference = Parse.Cloud.ReadPreferenceOption.SecondaryPreferred;
// request.readPreference = Parse.Cloud.ReadPreferenceOption.Nearest;
// });
// Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => {
// const query = request.query; // the Parse.Query
// return new Parse.Query('QueryMe!');
// });
// Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => {
// const query = request.query; // the Parse.Query
// return new Parse.Query('QueryMe, IN THE FUTURE!');
// });
// Parse.Cloud.afterFind('MyCustomClass', (request: Parse.Cloud.AfterFindRequest) => {
// return new Parse.Object('MyCustomClass');
// });
// Parse.Cloud.beforeLogin((request: Parse.Cloud.TriggerRequest) => {
// return Promise.resolve();
// });
// Parse.Cloud.afterLogin((request: Parse.Cloud.TriggerRequest) => {
// return Promise.resolve();
// });
// Parse.Cloud.afterLogout((request: Parse.Cloud.TriggerRequest) => {
// return Promise.resolve();
// });
// Parse.Cloud.beforeSaveFile((request: Parse.Cloud.FileTriggerRequest) => {
// return Promise.resolve(new Parse.File('myFile.txt', { base64: '' }));
// });
// Parse.Cloud.beforeSaveFile((request: Parse.Cloud.FileTriggerRequest) => {});
// Parse.Cloud.beforeDeleteFile((request: Parse.Cloud.FileTriggerRequest) => {});
// Parse.Cloud.afterDeleteFile((request: Parse.Cloud.FileTriggerRequest) => {});
// Parse.Cloud.define('AFunc', (request: Parse.Cloud.FunctionRequest) => {
// return 'Some result';
// });
// Parse.Cloud.define(
// 'AFunc',
// (request: Parse.Cloud.FunctionRequest) => {
// return 'Some result';
// },
// {
// requireUser: true,
// requireMaster: true,
// validateMasterKey: true,
// skipWithMasterKey: true,
// requireAnyUserRoles: ['a'],
// requireAllUserRoles: ['a'],
// fields: {
// name: {
// type: String,
// constant: true,
// default: true,
// options: [],
// error: 'invalid field.',
// },
// },
// requireUserKeys: {
// name: {
// type: String,
// constant: true,
// default: true,
// options: [],
// error: 'invalid field.',
// },
// },
// }
// );
// Parse.Cloud.define('AFunc', request => {
// // $ExpectType Params
// request.params;
// // $ExpectType any
// request.params.anything;
// });
// Parse.Cloud.define<() => void>('AFunc', request => {
// // $ExpectType {}
// request.params;
// });
// Parse.Cloud.define<(params: { something: string }) => number>('AFunc', request => {
// // $ExpectType { something: string; }
// request.params;
// // $ExpectError
// request.params.somethingElse;
// return 123;
// });
// // $ExpectError
// Parse.Cloud.define('AFunc');
// // $ExpectError
// Parse.Cloud.define<() => string>('AFunc', () => 123);
// // $ExpectError
// Parse.Cloud.define<(params: string) => number>('AFunc', () => 123);
// Parse.Cloud.job('AJob', (request: Parse.Cloud.JobRequest) => {
// request.message('Message to associate with this job run');
// });
await Parse.Cloud.startJob('AJob', {}).then(v => v);
await Parse.Cloud.getJobStatus('AJob').then(v => v);
await Parse.Cloud.getJobsData().then(v => v);
}
class PlaceObject extends Parse.Object {}
function test_geo_points() {
let point = new Parse.GeoPoint();
// $ExpectError
point = new Parse.GeoPoint('40.0');
// $ExpectType ParseGeoPoint
point = new Parse.GeoPoint(40.0);
// $ExpectError
point = new Parse.GeoPoint([40.0, -30.0, 20.0]);
point = new Parse.GeoPoint([40.0, -30.0]);
point = new Parse.GeoPoint(40.0, -30.0);
point = new Parse.GeoPoint({ latitude: 40.0, longitude: -30.0 });
const userObject = Parse.User.current<Parse.User<{ location: Parse.GeoPoint }>>()!;
// User's location
const userGeoPoint = userObject.get('location');
// Create a query for places
const query = new Parse.Query(Parse.User);
// Interested in locations near user.
query.near('location', userGeoPoint);
// Limit what could be a lot of points.
query.limit(10);
const southwestOfSF = new Parse.GeoPoint(37.708813, -122.526398);
const northeastOfSF = new Parse.GeoPoint(37.822802, -122.373962);
const query2 = new Parse.Query(PlaceObject);
query2.withinGeoBox('location', southwestOfSF, northeastOfSF);
const query3 = new Parse.Query('PlaceObject')
.find()
.then((o: Parse.Object[]) => {})
.catch(error => error);
}
async function test_push() {
await Parse.Push.send(
{
channels: ['Gia nts', 'Mets'],
data: {
alert: 'The Giants won against the Mets 2-3.',
},
},
{
success: () => {
// Push was successful
},
error: (error: any) => {
// Handle error
},
}
);
const query = new Parse.Query(Parse.Installation);
query.equalTo('injuryReports', true);
await Parse.Push.send(
{
where: query, // Set our Installation query
data: {
alert: 'Willie Hayes injured by own pop fly.',
},
},
{
success() {
// Push was successful
},
error(error: any) {
// Handle error
},
}
);
}
async function test_batch_operations() {
const game1 = new Game();
const game2 = new Game();
const games = [game1, game2];
// Master key
await Parse.Object.saveAll(games, { useMasterKey: true });
await Parse.Object.destroyAll(games, { useMasterKey: true });
await Parse.Object.fetchAll(games, { useMasterKey: true });
await Parse.Object.fetchAllIfNeeded(games, { useMasterKey: true });
// Session token
await Parse.Object.saveAll(games, { sessionToken: '' });
await Parse.Object.destroyAll(games, { sessionToken: '' });
await Parse.Object.fetchAll(games, { sessionToken: '' });
await Parse.Object.fetchAllIfNeeded(games, { sessionToken: '' });
}
async function test_query_subscribe() {
// create new query from Game object type
const query = new Parse.Query(Game);
// create subscription to Game object
// Without a token
// $ExpectType LiveQuerySubscription
let subscription = await query.subscribe();
// With a session token
// $ExpectType LiveQuerySubscription
subscription = await query.subscribe(new Parse.User().getSessionToken());
// listen for new Game objects created on Parse server
subscription.on('create', (game: any) => {
console.log(game);
});
// unsubscribe
await subscription.unsubscribe();
}
function test_serverURL() {
Parse.serverURL = 'http://localhost:1337/parse';
}
function test_polygon() {
const point = new Parse.GeoPoint(1, 2);
const polygon1 = new Parse.Polygon([
[0, 0],
[1, 0],
[1, 1],
[0, 1],
]);
const polygon2 = new Parse.Polygon([point, point, point]);
polygon1.equals(polygon2);
polygon1.containsPoint(point);
const query = new Parse.Query('TestObject');
query.polygonContains('key', point);
query.withinPolygon('key', [
[0, 0],
[1, 0],
[1, 1],
[0, 1],
]);
}
async function test_local_datastore() {
Parse.enableLocalDatastore();
const name = 'test_pin';
const obj = new Parse.Object('TestObject');
await obj.pin();
await obj.unPin();
await obj.isPinned();
await obj.pinWithName(name);
await obj.unPinWithName(name);
await obj.fetchFromLocalDatastore();
await Parse.Object.pinAll([obj]);
await Parse.Object.unPinAll([obj]);
await Parse.Object.pinAllWithName(name, [obj]);
await Parse.Object.unPinAllWithName(name, [obj]);
await Parse.Object.unPinAllObjects();
await Parse.Object.unPinAllObjectsWithName(name);
// $ExpectType boolean
Parse.isLocalDatastoreEnabled();
// $ExpectType any
await Parse.dumpLocalDatastore();
const query = new Parse.Query('TestObject');
query.fromPin();
query.fromPinWithName(name);
query.fromLocalDatastore();
Parse.setLocalDatastoreController({});
}
async function test_from_network() {
const obj = new Parse.Object('TestObject');
await obj.save();
const query = new Parse.Query('TestObject');
query.fromNetwork();
}
async function test_cancel_query() {
const obj = new Parse.Object('TestObject');
await obj.save();
const query = new Parse.Query('TestObject');
await query.fromNetwork().find();
query.cancel();
}
type FieldType =
| string
| number
| boolean
| Date
| Parse.File
| Parse.GeoPoint
| any[]
| object
| Parse.Pointer
| Parse.Polygon
| Parse.Relation;
async function test_schema(
anyField: FieldType,
notString: Exclude<FieldType, string>,
notNumber: Exclude<FieldType, number>,
notboolean: Exclude<FieldType, boolean>,
notDate: Exclude<FieldType, Date>,
notFile: Exclude<FieldType, Parse.File>,
notGeopoint: Exclude<FieldType, Parse.GeoPoint[]>,
notArray: Exclude<FieldType, any[]>,
notObject: Exclude<FieldType, object>,
notPointer: Exclude<FieldType, Parse.Pointer>,
notPolygon: Exclude<FieldType, Parse.Polygon>
) {
// $ExpectType RestSchema[]
await Parse.Schema.all();
const schema = new Parse.Schema('TestSchema');
schema.addArray('arrayField');
schema.addArray('arrayField', { defaultValue: [1, 2, 3, 4] });
// $ExpectError
schema.addArray('arrayField', { defaultValue: notArray });
/**
* @todo Enable type check for default value
*/
schema.addField('defaultFieldString');
schema.addField('defaultFieldString', 'String', { defaultValue: anyField });
schema.addField('defaultFieldString', 'Number');
schema.addField('defaultFieldString', 'Relation');
// $ExpectError
schema.addField('defaultFieldString', 'String', 'Invalid Options');
schema.addString('field');
schema.addString('field', { defaultValue: 'some string', required: true });
// $ExpectError
schema.addString('field', { defaultValue: notString });
schema.addNumber('field');
schema.addNumber('field', { defaultValue: 0, required: true });
// $ExpectError
schema.addNumber('field', { defaultValue: notNumber });
schema.addBoolean('field');
schema.addBoolean('field', { defaultValue: true, required: true });
// $ExpectError
schema.addBoolean('field', { defaultValue: notboolean });
schema.addDate('field');
schema.addDate('field', { defaultValue: new Date(), required: true });
// $ExpectError
schema.addDate('field', { defaultValue: notDate });
schema.addFile('field');
schema.addFile('field', { defaultValue: new Parse.File('myfile', []), required: true });
// $ExpectError
schema.addFile('field', { defaultValue: notFile });
schema.addGeoPoint('field');
schema.addGeoPoint('field', { defaultValue: new Parse.GeoPoint(), required: true });
// $ExpectError
schema.addGeoPoint('field', { defaultValue: notGeopoint });
schema.addPolygon('field');
schema.addPolygon('field', { defaultValue: new Parse.Polygon([]), required: true });
// $ExpectError
schema.addPolygon('field', { defaultValue: notPolygon });
schema.addObject('field');
schema.addObject('field', { defaultValue: {}, required: true });
schema.addObject('field', { defaultValue: { abc: 'def' } });
// $ExpectError
schema.addObject('field', { defaultValue: notObject });
schema.addPointer('field', 'SomeClass');
// $ExpectError
schema.addPointer('field');
/**
* @todo Infer defaultValue type from targetClass
*/
schema.addPointer('field', '_User', {
defaultValue: new Parse.User().toPointer(),