-
Notifications
You must be signed in to change notification settings - Fork 362
/
manipulation.test.js
2784 lines (2512 loc) · 92.3 KB
/
manipulation.test.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
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
// Copyright IBM Corp. 2013,2019. All Rights Reserved.
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
// This test written in mocha+should.js
'use strict';
/* global getSchema:false, connectorCapabilities:false */
const async = require('async');
const bdd = require('./helpers/bdd-if');
const should = require('./init.js');
const uid = require('./helpers/uid-generator');
let db, Person;
const ValidationError = require('..').ValidationError;
const UUID_REGEXP = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const throwingSetter = (value) => {
if (!value) return; // no-op
throw new Error('Intentional error triggered from a property setter');
};
describe('manipulation', function() {
before(function(done) {
db = getSchema();
Person = db.define('Person', {
name: String,
gender: String,
married: Boolean,
age: {type: Number, index: true},
dob: Date,
createdAt: {type: Date, default: Date},
throwingSetter: {type: String, default: null},
}, {forceId: true, strict: true});
Person.setter.throwingSetter = throwingSetter;
db.automigrate(['Person'], done);
});
// A simplified implementation of LoopBack's User model
// to reproduce problems related to properties with dynamic setters
// For the purpose of the tests, we use a counter instead of a hash fn.
let StubUser;
let stubPasswordCounter;
before(function setupStubUserModel(done) {
StubUser = db.createModel('StubUser', {password: String}, {forceId: true});
StubUser.setter.password = function(plain) {
if (plain.length === 0) throw new Error('password cannot be empty');
let hashed = false;
if (!plain) return;
const pos = plain.indexOf('-');
if (pos !== -1) {
const head = plain.substr(0, pos);
const tail = plain.substr(pos + 1, plain.length);
hashed = head.toUpperCase() === tail;
}
if (hashed) return;
this.$password = plain + '-' + plain.toUpperCase();
};
db.automigrate('StubUser', done);
});
beforeEach(function resetStubPasswordCounter() {
stubPasswordCounter = 0;
});
describe('create', function() {
before(function(done) {
Person.destroyAll(done);
});
describe('forceId', function() {
let TestForceId;
before(function(done) {
TestForceId = db.define('TestForceId');
db.automigrate('TestForceId', done);
});
it('it defaults to forceId:true for generated id property', function(done) {
TestForceId.create({id: 1}, function(err, t) {
should.exist(err);
err.message.should.match(/can\'t be set/);
done();
});
});
});
it('should create instance', function(done) {
Person.create({name: 'Anatoliy'}, function(err, p) {
if (err) return done(err);
should.exist(p);
p.name.should.equal('Anatoliy');
Person.findById(p.id, function(err, person) {
if (err) return done(err);
person.id.should.eql(p.id);
person.name.should.equal('Anatoliy');
done();
});
});
});
it('should create instance (promise variant)', function(done) {
Person.create({name: 'Anatoliy'})
.then(function(p) {
p.name.should.equal('Anatoliy');
should.exist(p);
return Person.findById(p.id)
.then(function(person) {
person.id.should.eql(p.id);
person.name.should.equal('Anatoliy');
done();
});
})
.catch(done);
});
it('should return rejected promise when model initialization failed', async () => {
await Person.create({name: 'Sad Fail', age: 25, throwingSetter: 'something'}).should
.be.rejectedWith('Intentional error triggered from a property setter');
});
it('should instantiate an object', function(done) {
const p = new Person({name: 'Anatoliy'});
p.name.should.equal('Anatoliy');
p.isNewRecord().should.be.true;
p.save(function(err, inst) {
if (err) return done(err);
inst.isNewRecord().should.be.false;
inst.should.equal(p);
done();
});
});
it('should instantiate an object (promise variant)', function(done) {
const p = new Person({name: 'Anatoliy'});
p.name.should.equal('Anatoliy');
p.isNewRecord().should.be.true;
p.save()
.then(function(inst) {
inst.isNewRecord().should.be.false;
inst.should.equal(p);
done();
})
.catch(done);
});
it('should not return instance of object', function(done) {
const person = Person.create(function(err, p) {
if (err) return done(err);
should.exist(p.id);
if (person) person.should.not.be.an.instanceOf(Person);
done();
});
});
it('should not allow user-defined value for the id of object - create', function(done) {
Person.create({id: 123456}, function(err, p) {
err.should.be.instanceof(ValidationError);
err.statusCode.should.equal(422);
err.details.messages.id.should.eql(['can\'t be set']);
p.should.be.instanceof(Person);
p.isNewRecord().should.be.true;
done();
});
});
it('should not allow user-defined value for the id of object - create (promise variant)', function(done) {
Person.create({id: 123456})
.then(function(p) {
done(new Error('Person.create should have failed.'));
}, function(err) {
err.should.be.instanceof(ValidationError);
err.statusCode.should.equal(422);
err.details.messages.id.should.eql(['can\'t be set']);
done();
})
.catch(done);
});
it('should not allow user-defined value for the id of object - save', function(done) {
const p = new Person({id: 123456});
p.isNewRecord().should.be.true;
p.save(function(err, inst) {
err.should.be.instanceof(ValidationError);
err.statusCode.should.equal(422);
err.details.messages.id.should.eql(['can\'t be set']);
inst.isNewRecord().should.be.true;
done();
});
});
it('should not allow user-defined value for the id of object - save (promise variant)', function(done) {
const p = new Person({id: 123456});
p.isNewRecord().should.be.true;
p.save()
.then(function(inst) {
done(new Error('save should have failed.'));
}, function(err) {
err.should.be.instanceof(ValidationError);
err.statusCode.should.equal(422);
err.details.messages.id.should.eql(['can\'t be set']);
done();
})
.catch(done);
});
it('should work when called without callback', function(done) {
Person.afterCreate = function(next) {
this.should.be.an.instanceOf(Person);
this.name.should.equal('Nickolay');
should.exist(this.id);
Person.afterCreate = null;
next();
setTimeout(done, 10);
};
Person.create({name: 'Nickolay'});
});
it('should create instance with blank data', function(done) {
Person.create(function(err, p) {
if (err) return done(err);
should.exist(p);
should.not.exists(p.name);
Person.findById(p.id, function(err, person) {
if (err) return done(err);
person.id.should.eql(p.id);
should.not.exists(person.name);
done();
});
});
});
it('should create instance with blank data (promise variant)', function(done) {
Person.create()
.then(function(p) {
should.exist(p);
should.not.exists(p.name);
return Person.findById(p.id)
.then(function(person) {
person.id.should.eql(p.id);
should.not.exists(person.name);
done();
});
}).catch(done);
});
it('should work when called with no data and callback', function(done) {
Person.afterCreate = function(next) {
this.should.be.an.instanceOf(Person);
should.not.exist(this.name);
should.exist(this.id);
Person.afterCreate = null;
next();
setTimeout(done, 30);
};
Person.create();
});
it('should create batch of objects', function(done) {
const batch = [
{name: 'Shaltay'},
{name: 'Boltay'},
{},
];
const res = Person.create(batch, function(e, ps) {
if (res) res.should.not.be.instanceOf(Array);
should.not.exist(e);
should.exist(ps);
ps.should.be.instanceOf(Array);
ps.should.have.lengthOf(batch.length);
Person.validatesPresenceOf('name');
Person.create(batch, function(errors, persons) {
delete Person.validations;
should.exist(errors);
errors.should.have.lengthOf(batch.length);
should.not.exist(errors[0]);
should.not.exist(errors[1]);
should.exist(errors[2]);
should.exist(persons);
persons.should.have.lengthOf(batch.length);
persons[0].errors.should.be.false;
done();
});
});
});
it('should create batch of objects (promise variant)', function(done) {
const batch = [
{name: 'ShaltayPromise'},
{name: 'BoltayPromise'},
{},
];
Person.create(batch).then(function(ps) {
should.exist(ps);
ps.should.be.instanceOf(Array);
ps.should.have.lengthOf(batch.length);
Person.validatesPresenceOf('name');
Person.create(batch, function(errors, persons) {
delete Person.validations;
should.exist(errors);
errors.should.have.lengthOf(batch.length);
should.not.exist(errors[0]);
should.not.exist(errors[1]);
should.exist(errors[2]);
should.exist(persons);
persons.should.have.lengthOf(batch.length);
persons[0].errors.should.be.false;
done();
});
});
});
it('should create batch of objects with beforeCreate', function(done) {
Person.beforeCreate = function(next, data) {
if (data && data.name === 'A') {
return next(null, {id: 'a', name: 'A'});
} else {
return next();
}
};
const batch = [
{name: 'A'},
{name: 'B'},
undefined,
];
Person.create(batch, function(e, ps) {
should.not.exist(e);
should.exist(ps);
ps.should.be.instanceOf(Array);
ps.should.have.lengthOf(batch.length);
ps[0].should.be.eql({id: 'a', name: 'A'});
done();
});
});
it('should preserve properties with "undefined" value', function(done) {
Person.create(
{name: 'a-name', gender: undefined},
function(err, created) {
if (err) return done(err);
created.toObject().should.have.properties({
id: created.id,
name: 'a-name',
gender: undefined,
});
Person.findById(created.id, function(err, found) {
if (err) return done(err);
const result = found.toObject();
result.should.containEql({
id: created.id,
name: 'a-name',
});
// The gender can be null from a RDB
should.equal(result.gender, null);
done();
});
},
);
});
bdd.itIf(connectorCapabilities.refuseDuplicateInsert !== false, 'should refuse to create ' +
'object with duplicate id', function(done) {
// NOTE(bajtos) We cannot reuse Person model here,
// `settings.forceId` aborts the CREATE request at the validation step.
const Product = db.define('ProductTest', {name: String}, {forceId: false});
db.automigrate('ProductTest', function(err) {
if (err) return done(err);
Product.create({name: 'a-name'}, function(err, p) {
if (err) return done(err);
Product.create({id: p.id, name: 'duplicate'}, function(err, result) {
if (!err) {
return done(new Error('Create should have rejected duplicate id.'));
}
err.message.should.match(/duplicate/i);
done();
});
});
});
});
});
describe('save', function() {
it('should save new object', function(done) {
const p = new Person;
should.not.exist(p.id);
p.save(function(err) {
if (err) return done(err);
should.exist(p.id);
done();
});
});
it('should save new object (promise variant)', function(done) {
const p = new Person;
should.not.exist(p.id);
p.save()
.then(function() {
should.exist(p.id);
done();
})
.catch(done);
});
bdd.itIf(connectorCapabilities.cloudantCompatible !== false,
'should save existing object', function(done) {
// Cloudant could not guarantee findOne always return the same item
Person.findOne(function(err, p) {
if (err) return done(err);
p.name = 'Hans';
p.save(function(err) {
if (err) return done(err);
p.name.should.equal('Hans');
Person.findOne(function(err, p) {
if (err) return done(err);
p.name.should.equal('Hans');
done();
});
});
});
});
bdd.itIf(connectorCapabilities.cloudantCompatible !== false,
'should save existing object (promise variant)', function(done) {
// Cloudant could not guarantee findOne always return the same item
Person.findOne()
.then(function(p) {
p.name = 'Fritz';
return p.save()
.then(function() {
return Person.findOne()
.then(function(p) {
p.name.should.equal('Fritz');
done();
});
});
})
.catch(done);
});
it('should save invalid object (skipping validation)', function(done) {
Person.findOne(function(err, p) {
if (err) return done(err);
p.isValid = function(done) {
process.nextTick(done);
return false;
};
p.name = 'Nana';
p.save(function(err) {
should.exist(err);
p.save({validate: false}, function(err) {
if (err) return done(err);
done();
});
});
});
});
it('should save invalid object (skipping validation - promise variant)', function(done) {
Person.findOne()
.then(function(p) {
p.isValid = function(done) {
process.nextTick(done);
return false;
};
p.name = 'Nana';
return p.save()
.then(function(d) {
done(new Error('save should have failed.'));
}, function(err) {
should.exist(err);
p.save({validate: false})
.then(function(d) {
should.exist(d);
done();
});
});
})
.catch(done);
});
it('should save throw error on validation', function(done) {
Person.findOne(function(err, p) {
if (err) return done(err);
p.isValid = function(cb) {
cb(false);
return false;
};
(function() {
p.save({
'throws': true,
});
}).should.throw(ValidationError);
done();
});
});
it('should preserve properties with dynamic setters', function(done) {
// This test reproduces a problem discovered by LoopBack unit-test
// "User.hasPassword() should match a password after it is changed"
StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err);
created.password.should.equal('foo-FOO');
created.password = 'bar';
created.save(function(err, saved) {
if (err) return done(err);
created.id.should.eql(saved.id);
saved.password.should.equal('bar-BAR');
StubUser.findById(created.id, function(err, found) {
if (err) return done(err);
created.id.should.eql(found.id);
found.password.should.equal('bar-BAR');
done();
});
});
});
});
});
describe('updateAttributes', function() {
let person;
before(function(done) {
Person.destroyAll(function(err) {
if (err) return done(err);
Person.create({name: 'Mary', age: 15}, function(err, p) {
if (err) return done(err);
person = p;
done();
});
});
});
it('should have updated password hashed with updateAttribute',
function(done) {
StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err);
created.updateAttribute('password', 'test', function(err, created) {
if (err) return done(err);
created.password.should.equal('test-TEST');
StubUser.findById(created.id, function(err, found) {
if (err) return done(err);
found.password.should.equal('test-TEST');
done();
});
});
});
});
it('should reject created StubUser with empty password', function(done) {
StubUser.create({email: '[email protected]', password: ''}, function(err, createdUser) {
(err.message).should.match(/password cannot be empty/);
done();
});
});
it('should reject updated empty password with updateAttribute', function(done) {
StubUser.create({password: 'abc123'}, function(err, createdUser) {
if (err) return done(err);
createdUser.updateAttribute('password', '', function(err, updatedUser) {
(err.message).should.match(/password cannot be empty/);
done();
});
});
});
it('should update one attribute', function(done) {
person.updateAttribute('name', 'Paul Graham', function(err, p) {
if (err) return done(err);
Person.all(function(e, ps) {
if (e) return done(e);
ps.should.have.lengthOf(1);
ps.pop().name.should.equal('Paul Graham');
done();
});
});
});
it('should update one attribute (promise variant)', function(done) {
person.updateAttribute('name', 'Teddy Graham')
.then(function(p) {
return Person.all()
.then(function(ps) {
ps.should.have.lengthOf(1);
ps.pop().name.should.equal('Teddy Graham');
done();
});
}).catch(done);
});
it('should ignore undefined values on updateAttributes', function(done) {
person.updateAttributes({'name': 'John', age: undefined},
function(err, p) {
if (err) return done(err);
Person.findById(p.id, function(e, p) {
if (e) return done(e);
p.name.should.equal('John');
p.age.should.equal(15);
done();
});
});
});
bdd.itIf(connectorCapabilities.cloudantCompatible !== false,
'should discard undefined values before strict validation',
function(done) {
Person.definition.settings.strict = true;
Person.findById(person.id, function(err, p) {
if (err) return done(err);
p.updateAttributes({name: 'John', unknownVar: undefined},
function(err, p) {
// if uknownVar was defined, it would return validationError
if (err) return done(err);
person.id.should.eql(p.id);
Person.findById(p.id, function(e, p) {
if (e) return done(e);
p.name.should.equal('John');
p.should.not.have.property('unknownVar');
done();
});
});
});
});
it('should allow unknown attributes when strict: false',
function(done) {
Person.definition.settings.strict = false;
Person.findById(person.id, function(err, p) {
if (err) return done(err);
p.updateAttributes({name: 'John', foo: 'bar'},
function(err, p) {
if (err) return done(err);
p.should.have.property('foo');
done();
});
});
});
it('should remove unknown attributes when strict: filter',
function(done) {
Person.definition.settings.strict = 'filter';
Person.findById(person.id, function(err, p) {
if (err) return done(err);
p.updateAttributes({name: 'John', foo: 'bar'},
function(err, p) {
if (err) return done(err);
p.should.not.have.property('foo');
done();
});
});
});
// Prior to version 3.0 `strict: true` used to silently remove unknown properties,
// now return validationError upon unknown properties
it('should return error on unknown attributes when strict: true',
function(done) {
// Using {foo: 'bar'} only causes dependent test failures due to the
// stripping of object properties when in strict mode (ie. {foo: 'bar'}
// changes to '{}' and breaks other tests
Person.definition.settings.strict = true;
Person.findById(person.id, function(err, p) {
if (err) return done(err);
p.updateAttributes({name: 'John', foo: 'bar'},
function(err, p) {
should.exist(err);
err.name.should.equal('ValidationError');
err.message.should.containEql('`foo` is not defined in the model');
p.should.not.have.property('foo');
Person.findById(p.id, function(e, p) {
if (e) return done(e);
p.should.not.have.property('foo');
done();
});
});
});
});
// strict: throw is deprecated, use strict: true instead
// which returns Validation Error for unknown properties
it('should fallback to strict:true when using strict: throw', function(done) {
Person.definition.settings.strict = 'throw';
Person.findById(person.id, function(err, p) {
if (err) return done(err);
p.updateAttributes({foo: 'bar'},
function(err, p) {
should.exist(err);
err.name.should.equal('ValidationError');
err.message.should.containEql('`foo` is not defined in the model');
Person.findById(person.id, function(e, p) {
if (e) return done(e);
p.should.not.have.property('foo');
done();
});
});
});
});
// strict: validate is deprecated, use strict: true instead
// behavior remains the same as before, because validate is now default behavior
it('should fallback to strict:true when using strict:validate', function(done) {
Person.definition.settings.strict = 'validate';
Person.findById(person.id, function(err, p) {
if (err) return done(err);
p.updateAttributes({foo: 'bar'},
function(err, p) {
should.exist(err);
err.name.should.equal('ValidationError');
err.message.should.containEql('`foo` is not defined in the model');
Person.findById(person.id, function(e, p) {
if (e) return done(e);
p.should.not.have.property('foo');
done();
});
});
});
});
it('should allow same id value on updateAttributes', function(done) {
person.updateAttributes({id: person.id, name: 'John'},
function(err, p) {
if (err) return done(err);
Person.findById(p.id, function(e, p) {
if (e) return done(e);
p.name.should.equal('John');
p.age.should.equal(15);
done();
});
});
});
it('should allow same stringified id value on updateAttributes',
function(done) {
let pid = person.id;
if (typeof person.id === 'object' || typeof person.id === 'number') {
// For example MongoDB ObjectId
pid = person.id.toString();
}
person.updateAttributes({id: pid, name: 'John'},
function(err, p) {
if (err) return done(err);
Person.findById(p.id, function(e, p) {
if (e) return done(e);
p.name.should.equal('John');
p.age.should.equal(15);
done();
});
});
});
it('should fail if an id value is to be changed on updateAttributes',
function(done) {
person.updateAttributes({id: person.id + 1, name: 'John'},
function(err, p) {
should.exist(err);
done();
});
});
it('has an alias "patchAttributes"', function(done) {
person.updateAttributes.should.equal(person.patchAttributes);
done();
});
it('should allow model instance on updateAttributes', function(done) {
person.updateAttributes(new Person({'name': 'John', age: undefined}),
function(err, p) {
if (err) return done(err);
Person.findById(p.id, function(e, p) {
if (e) return done(e);
p.name.should.equal('John');
p.age.should.equal(15);
done();
});
});
});
it('should allow model instance on updateAttributes (promise variant)', function(done) {
person.updateAttributes(new Person({'name': 'Jane', age: undefined}))
.then(function(p) {
return Person.findById(p.id)
.then(function(p) {
p.name.should.equal('Jane');
p.age.should.equal(15);
done();
});
})
.catch(done);
});
it('should raises on connector error', function(done) {
const fakeConnector = {
updateAttributes: function(model, id, data, options, cb) {
cb(new Error('Database Error'));
},
};
person.getConnector = function() { return fakeConnector; };
person.updateAttributes({name: 'John'}, function(err, p) {
should.exist(err);
done();
});
});
});
describe('updateOrCreate', function() {
let Post, Todo;
before('prepare "Post" and "Todo" models', function(done) {
Post = db.define('Post', {
title: {type: String, id: true},
content: {type: String},
});
Todo = db.define('Todo', {
content: String,
});
// Here `Person` model overrides the one outside 'updataOrCreate'
// with forceId: false. Related test cleanup see issue:
// https://github.com/strongloop/loopback-datasource-juggler/issues/1317
Person = db.define('Person', {
name: String,
gender: String,
married: Boolean,
age: {type: Number, index: true},
dob: Date,
createdAt: {type: Date, default: Date},
}, {forceId: false});
db.automigrate(['Post', 'Todo', 'Person'], done);
});
beforeEach(function deleteModelsInstances(done) {
Todo.deleteAll(done);
});
it('has an alias "patchOrCreate"', function() {
StubUser.updateOrCreate.should.equal(StubUser.patchOrCreate);
});
it('creates a model when one does not exist', function(done) {
Todo.updateOrCreate({content: 'a'}, function(err, data) {
if (err) return done(err);
Todo.findById(data.id, function(err, todo) {
should.exist(todo);
should.exist(todo.content);
todo.content.should.equal('a');
done();
});
});
});
it('updates a model if it exists', function(done) {
Todo.create({content: 'a'}, function(err, todo) {
Todo.updateOrCreate({id: todo.id, content: 'b'}, function(err, data) {
if (err) return done(err);
should.exist(data);
should.exist(data.id);
data.id.should.eql(todo.id);
should.exist(data.content);
data.content.should.equal('b');
done();
});
});
});
it('should reject updated empty password with updateOrCreate', function(done) {
StubUser.create({password: 'abc123'}, function(err, createdUser) {
if (err) return done(err);
StubUser.updateOrCreate({id: createdUser.id, 'password': ''}, function(err, updatedUser) {
(err.message).should.match(/password cannot be empty/);
done();
});
});
});
it('throws error for queries with array input', function(done) {
Todo.updateOrCreate([{content: 'a'}], function(err, data) {
should.exist(err);
err.message.should.containEql('bulk');
should.not.exist(data);
done();
});
});
it('should preserve properties with dynamic setters on create', function(done) {
StubUser.updateOrCreate({password: 'foo'}, function(err, created) {
if (err) return done(err);
created.password.should.equal('foo-FOO');
StubUser.findById(created.id, function(err, found) {
if (err) return done(err);
found.password.should.equal('foo-FOO');
done();
});
});
});
it('should preserve properties with dynamic setters on update', function(done) {
StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err);
const data = {id: created.id, password: 'bar'};
StubUser.updateOrCreate(data, function(err, updated) {
if (err) return done(err);
updated.password.should.equal('bar-BAR');
StubUser.findById(created.id, function(err, found) {
if (err) return done(err);
found.password.should.equal('bar-BAR');
done();
});
});
});
});
it('should preserve properties with "undefined" value', function(done) {
Person.create(
{name: 'a-name', gender: undefined},
function(err, instance) {
if (err) return done(err);
const result = instance.toObject();
result.id.should.eql(instance.id);
should.equal(result.name, 'a-name');
should.equal(result.gender, undefined);
Person.updateOrCreate(
{id: instance.id, name: 'updated name'},
function(err, updated) {
if (err) return done(err);
const result = updated.toObject();
result.id.should.eql(instance.id);
should.equal(result.name, 'updated name');
should.equal(result.gender, null);
done();
},
);
},
);
});
it('updates specific instances when PK is not an auto-generated id', function(done) {
// skip the test if the connector is mssql
// https://github.com/strongloop/loopback-connector-mssql/pull/92#r72853474
const dsName = Post.dataSource.name;
if (dsName === 'mssql') return done();
Post.create([
{title: 'postA', content: 'contentA'},
{title: 'postB', content: 'contentB'},
], function(err, instance) {
if (err) return done(err);
Post.updateOrCreate({
title: 'postA', content: 'newContent',
}, function(err, instance) {
if (err) return done(err);
const result = instance.toObject();
result.should.have.properties({
title: 'postA',
content: 'newContent',
});
Post.find(function(err, posts) {
if (err) return done(err);
posts.should.have.length(2);
posts[0].title.should.equal('postA');
posts[0].content.should.equal('newContent');
posts[1].title.should.equal('postB');
posts[1].content.should.equal('contentB');
done();
});
});
});
});
it('should allow save() of the created instance', function(done) {
const unknownId = uid.fromConnector(db) || 999;
Person.updateOrCreate(
{id: unknownId, name: 'a-name'},
function(err, inst) {
if (err) return done(err);
inst.save(done);
},
);
});
it('preserves empty values from the database', async () => {
// https://github.com/strongloop/loopback-datasource-juggler/issues/1692