-
Notifications
You must be signed in to change notification settings - Fork 165
/
server.js
1348 lines (1123 loc) · 38.2 KB
/
server.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
/* eslint no-console: 0 */
import "@miragejs/pretender-node-polyfill/before";
import Pretender from "pretender";
import "@miragejs/pretender-node-polyfill/after";
import { camelize } from "./utils/inflector";
import isAssociation from "./utils/is-association";
import assert from "./assert";
import BelongsTo from "./orm/associations/belongs-to";
import Container from "./container";
import { singularize, pluralize } from "inflected";
import pick from "lodash.pick";
import assign from "lodash.assign";
import find from "lodash.find";
import isPlainObject from "lodash.isplainobject";
import isInteger from "lodash.isinteger";
const isPluralForModelCache = {};
/**
* Creates a new Pretender instance.
*
* @method createPretender
* @param {Server} server
* @return {Object} A new Pretender instance.
* @public
*/
function createPretender(server) {
if (typeof window !== "undefined") {
return new Pretender(
function () {
this.passthroughRequest = function (verb, path, request) {
if (server.shouldLog()) {
console.log(
`Mirage: Passthrough request for ${verb.toUpperCase()} ${
request.url
}`
);
}
};
this.handledRequest = function (verb, path, request) {
if (server.shouldLog()) {
console.groupCollapsed(
`Mirage: [${request.status}] ${verb.toUpperCase()} ${request.url}`
);
let { requestBody, responseText } = request;
let loggedRequest, loggedResponse;
try {
loggedRequest = JSON.parse(requestBody);
} catch (e) {
loggedRequest = requestBody;
}
try {
loggedResponse = JSON.parse(responseText);
} catch (e) {
loggedResponse = responseText;
}
console.groupCollapsed("Response");
console.log(loggedResponse);
console.groupEnd();
console.groupCollapsed("Request (data)");
console.log(loggedRequest);
console.groupEnd();
console.groupCollapsed("Request (raw)");
console.log(request);
console.groupEnd();
console.groupEnd();
}
};
let originalCheckPassthrough = this.checkPassthrough;
this.checkPassthrough = function (request) {
let shouldPassthrough = server.passthroughChecks.some(
(passthroughCheck) => passthroughCheck(request)
);
if (shouldPassthrough) {
let url = request.url.includes("?")
? request.url.substr(0, request.url.indexOf("?"))
: request.url;
this[request.method.toLowerCase()](url, this.passthrough);
}
return originalCheckPassthrough.apply(this, arguments);
};
this.unhandledRequest = function (verb, path) {
path = decodeURI(path);
assert(
`Your app tried to ${verb} '${path}', but there was no route defined to handle this request. Define a route for this endpoint in your routes() config. Did you forget to define a namespace?`
);
};
},
{ trackRequests: server.shouldTrackRequests() }
);
}
}
const defaultRouteOptions = {
coalesce: false,
timing: undefined,
};
const defaultInflector = { singularize, pluralize };
/**
@hide
*/
const defaultPassthroughs = [
"http://localhost:0/chromecheckurl", // mobile chrome
"http://localhost:30820/socket.io", // electron
(request) => {
return /.+\.hot-update.json$/.test(request.url);
},
];
/**
@hide
*/
export { defaultPassthroughs };
/**
* Determine if the object contains a valid option.
*
* @method isOption
* @param {Object} option An object with one option value pair.
* @return {Boolean} True if option is a valid option, false otherwise.
* @private
*/
function isOption(option) {
if (!option || typeof option !== "object") {
return false;
}
let allOptions = Object.keys(defaultRouteOptions);
let optionKeys = Object.keys(option);
for (let i = 0; i < optionKeys.length; i++) {
let key = optionKeys[i];
if (allOptions.indexOf(key) > -1) {
return true;
}
}
return false;
}
/**
* Extract arguments for a route.
*
* @method extractRouteArguments
* @param {Array} args Of the form [options], [object, code], [function, code]
* [shorthand, options], [shorthand, code, options]
* @return {Array} [handler (i.e. the function, object or shorthand), code,
* options].
* @private
*/
function extractRouteArguments(args) {
let [lastArg] = args.splice(-1);
if (isOption(lastArg)) {
lastArg = assign({}, defaultRouteOptions, lastArg);
} else {
args.push(lastArg);
lastArg = defaultRouteOptions;
}
let t = 2 - args.length;
while (t-- > 0) {
args.push(undefined);
}
args.push(lastArg);
return args;
}
/**
The Mirage server.
Note that `this` within your `routes` function refers to the server instance, which is the same instance that `server` refers to in your tests.
@class Server
@public
*/
export default class Server {
/**
* Creates a Server
* @param {Object} options Server's configuration object
* @param {String} options.urlPrefix The base URL for the routes. Example: `http://miragejs.com`.
* @param {String} options.namespace The default namespace for the `Server`. Example: `/api/v1`.
* @param {Number} options.timing Default latency for the routes to respond to a request.
* @param {String} options.environment Defines the environment of the `Server`.
* @param {Boolean} options.trackRequests Pretender `trackRequests`.
* @param {Boolean} options.useDefaultPassthroughs True to use mirage provided passthroughs
* @param {Boolean} options.logging Set to true or false to explicitly specify logging behavior.
* @param {Function} options.seeds Called on the seed phase. Should be used to seed the database.
* @param {Function} options.scenarios Alias for seeds.
* @param {Function} options.routes Should be used to define server routes.
* @param {Function} options.baseConfig Alias for routes.
* @param {Object} options.inflector Default inflector (used for pluralization and singularization).
* @param {Object} options.identityManagers Database identity managers.
* @param {Object} options.models Server models
* @param {Object} options.serializers Server serializers
* @param {Object} options.factories Server factories
* @param {Object} options.pretender Pretender instance
*/
constructor(options = {}) {
this._container = new Container();
this.config(options);
/**
Returns the Mirage Db instance.
@property db
@return Db
*/
this.db = this.db || undefined;
/**
Returns the Mirage Schema (ORM) instance.
@property schema
@return Schema
*/
this.schema = this.schema || undefined;
}
config(config = {}) {
this.passthroughChecks = this.passthroughChecks || [];
let didOverrideConfig =
config.environment &&
this.environment &&
this.environment !== config.environment;
assert(
!didOverrideConfig,
"You cannot modify Mirage's environment once the server is created"
);
this.environment = config.environment || this.environment || "development";
if (config.routes) {
assert(
!config.baseConfig,
"The routes option is an alias for the baseConfig option. You can't pass both options into your server definition."
);
config.baseConfig = config.routes;
}
if (config.seeds) {
assert(
!config.scenarios,
"The seeds option is an alias for the scenarios.default option. You can't pass both options into your server definition."
);
config.scenarios = { default: config.seeds };
}
this._config = config;
/**
Set the base namespace used for all routes defined with `get`, `post`, `put` or `del`.
For example,
```js
new Server({
routes() {
this.namespace = '/api';
// this route will handle the URL '/api/contacts'
this.get('/contacts', 'contacts');
}
})
```
Note that only routes defined after `this.namespace` are affected. This is useful if you have a few one-off routes that you don't want under your namespace:
```js
new Server({
routes() {
// this route handles /auth
this.get('/auth', function() { ...});
this.namespace = '/api';
// this route will handle the URL '/api/contacts'
this.get('/contacts', 'contacts');
};
})
```
If your app is loaded from the filesystem vs. a server (e.g. via Cordova or Electron vs. `localhost` or `https://yourhost.com/`), you will need to explicitly define a namespace. Likely values are `/` (if requests are made with relative paths) or `https://yourhost.com/api/...` (if requests are made to a defined server).
For a sample implementation leveraging a configured API host & namespace, check out [this issue comment](https://github.com/miragejs/ember-cli-mirage/issues/497#issuecomment-183458721).
@property namespace
@type String
@public
*/
this.namespace = this.namespace || config.namespace || "";
/**
Mirage needs know the singular and plural versions of certain words for some of its APIs to work.
For example, whenever you define a model
```js
new Server({
models: {
post: Model
}
})
```
Mirage will pluralize the word "post" and use it to create a `db.posts` database collection.
To accomplish this, Mirage uses an object called an Inflector. An Inflector is an object with two methods, `singularize` and `pluralize`, that Mirage will call whenever it needs to inflect a word.
Mirage has a default inflector, so if you write
```js
new Server()
```
you'll be using the node [inflected](https://github.com/martinandert/inflected#readme) package. This can be customized if you have irregular words or need to change the defaults. You can wead more in [the guide on customizing inflections](/docs/advanced/customizing-inflections).
You typically should be able to make your customizations using the provided inflector. It's good to match any custom inflections your backend uses, as this will keep your Mirage code more consistent and simpler.
You can also override the inflector completely and provide your own `pluralize` and `singularize` methods:
```js
new Server({
inflector: {
pluralize(word) {
// your logic
},
singularize(word) {
// your logic
}
}
})
```
*/
this.inflector = config.inflector || defaultInflector;
this._container.register("inflector", this.inflector);
/**
Sets a string to prefix all route handler URLs with.
Useful if your app makes API requests to a different port.
```js
new Server({
routes() {
this.urlPrefix = 'http://localhost:8080'
}
})
```
*/
this.urlPrefix = this.urlPrefix || config.urlPrefix || "";
/**
Set the number of milliseconds for the the Server's response time.
By default there's a 400ms delay during development, and 0 delay in testing (so your tests run fast).
```js
new Server({
routes() {
this.timing = 400; // default
}
})
```
To set the timing for individual routes, see the `timing` option for route handlers.
@property timing
@type Number
@public
*/
this.timing = this.timing || config.timing || 400;
/**
Set to `true` or `false` to explicitly specify logging behavior.
By default, server responses are logged in non-testing environments. Logging is disabled by default in testing, so as not to clutter CI test runner output.
For example, to enable logging in tests, write the following:
```js
test('I can view all users', function() {
server.logging = true;
server.create('user');
visit('/users');
// ...
});
```
You can also write a custom log message using the [Pretender server's `handledRequest` hook](https://github.com/pretenderjs/pretender#handled-requests). (You can access the pretender server from your Mirage server via `server.pretender`.)
To override,
```js
new Server({
routes() {
this.pretender.handledRequest = function(verb, path, request) {
let { responseText } = request;
// log request and response data
}
}
})
```
@property logging
@return {Boolean}
@public
*/
this.logging = this.logging !== undefined ? this.logging : undefined;
this.testConfig = this.testConfig || undefined;
this.trackRequests = config.trackRequests;
this._defineRouteHandlerHelpers();
if (this.db) {
this.db.registerIdentityManagers(config.identityManagers);
} else {
this.db = this._container.create(
"Db",
undefined,
config.identityManagers
);
}
if (this.schema) {
this.schema.registerModels(config.models);
this.serializerOrRegistry.registerSerializers(config.serializers || {});
} else {
this.schema = this._container.create("Schema", this.db, config.models);
this.serializerOrRegistry = this._container.create(
"SerializerRegistry",
this.schema,
config.serializers
);
}
let hasFactories = this._hasModulesOfType(config, "factories");
let hasDefaultScenario =
config.scenarios &&
Object.prototype.hasOwnProperty.call(config.scenarios, "default");
let didOverridePretenderConfig =
config.trackRequests !== undefined && this.pretender;
assert(
!didOverridePretenderConfig,
"You cannot modify Pretender's request tracking once the server is created"
);
/**
Mirage uses [pretender.js](https://github.com/trek/pretender) as its xhttp interceptor. In your Mirage config, `this.pretender` refers to the actual Pretender instance, so any config options that work there will work here as well.
```js
new Server({
routes() {
this.pretender.handledRequest = (verb, path, request) => {
console.log(`Your server responded to ${path}`);
}
}
})
```
Refer to [Pretender's docs](https://github.com/pretenderjs/pretender) if you want to change any options on your Pretender instance.
@property pretender
@return {Object} The Pretender instance
@public
*/
this.pretender =
this.pretender || config.pretender || createPretender(this);
if (config.baseConfig) {
this.loadConfig(config.baseConfig);
}
if (this.isTest()) {
if (config.testConfig) {
this.loadConfig(config.testConfig);
}
if (typeof window !== "undefined") {
window.server = this; // TODO: Better way to inject server into test env
}
}
if (this.isTest() && hasFactories) {
this.loadFactories(config.factories);
} else if (!this.isTest() && hasDefaultScenario) {
this.loadFactories(config.factories);
config.scenarios.default(this);
} else {
this.loadFixtures();
}
let useDefaultPassthroughs =
typeof config.useDefaultPassthroughs !== "undefined"
? config.useDefaultPassthroughs
: true;
if (useDefaultPassthroughs) {
this._configureDefaultPassthroughs();
}
}
/**
* Determines if the current environment is the testing environment.
*
* @method isTest
* @return {Boolean} True if the environment is 'test', false otherwise.
* @public
* @hide
*/
isTest() {
return this.environment === "test";
}
/**
Determines if the server should log.
@method shouldLog
@return The value of this.logging if defined, or false if in the testing environment,
true otherwise.
@public
@hide
*/
shouldLog() {
return typeof this.logging !== "undefined" ? this.logging : !this.isTest();
}
/**
* Determines if the server should track requests.
*
* @method shouldTrackRequests
* @return The value of this.trackRequests if defined, false otherwise.
* @public
* @hide
*/
shouldTrackRequests() {
return Boolean(this.trackRequests);
}
/**
* Load the configuration given, setting timing to 0 if in the test
* environment.
*
* @method loadConfig
* @param {Object} config The configuration to load.
* @public
* @hide
*/
loadConfig(config) {
config.call(this);
this.timing = this.isTest() ? 0 : this.timing || 0;
}
/**
By default, if your app makes a request that is not defined in your server config, Mirage will throw an error. You can use `passthrough` to whitelist requests, and allow them to pass through your Mirage server to the actual network layer.
Note: Put all passthrough config at the bottom of your routes, to give your route handlers precedence.
To ignore paths on your current host (as well as configured `namespace`), use a leading `/`:
```js
this.passthrough('/addresses');
```
You can also pass a list of paths, or call `passthrough` multiple times:
```js
this.passthrough('/addresses', '/contacts');
this.passthrough('/something');
this.passthrough('/else');
```
These lines will allow all HTTP verbs to pass through. If you want only certain verbs to pass through, pass an array as the last argument with the specified verbs:
```js
this.passthrough('/addresses', ['post']);
this.passthrough('/contacts', '/photos', ['get']);
```
You can pass a function to `passthrough` to do a runtime check on whether or not the request should be handled by Mirage. If the function returns `true` Mirage will not handle the request and let it pass through.
```js
this.passthrough(request => {
return request.queryParams.skipMirage;
});
```
If you want all requests on the current domain to pass through, simply invoke the method with no arguments:
```js
this.passthrough();
```
Note again that the current namespace (i.e. any `namespace` property defined above this call) will be applied.
You can also allow other-origin hosts to passthrough. If you use a fully-qualified domain name, the `namespace` property will be ignored. Use two * wildcards to match all requests under a path:
```js
this.passthrough('http://api.foo.bar/**');
this.passthrough('http://api.twitter.com/v1/cards/**');
```
In versions of Pretender prior to 0.12, `passthrough` only worked with jQuery >= 2.x. As long as you're on Pretender@0.12 or higher, you should be all set.
@method passthrough
@param {String} [...paths] Any number of paths to whitelist
@param {Array} options Unused
@public
*/
passthrough(...paths) {
// this only works in browser-like environments for now. in node users will have to configure
// their own interceptor if they are using one.
if (typeof window !== "undefined") {
let verbs = ["get", "post", "put", "delete", "patch", "options", "head"];
let lastArg = paths[paths.length - 1];
if (paths.length === 0) {
paths = ["/**", "/"];
} else if (Array.isArray(lastArg)) {
verbs = paths.pop();
}
paths.forEach((path) => {
if (typeof path === "function") {
this.passthroughChecks.push(path);
} else {
verbs.forEach((verb) => {
let fullPath = this._getFullPath(path);
this.pretender[verb](fullPath, this.pretender.passthrough);
});
}
});
}
}
/**
By default, `fixtures` will be loaded during testing if you don't have factories defined, and during development if you don't have `seeds` defined. You can use `loadFixtures()` to also load fixture files in either of these environments, in addition to using factories to seed your database.
`server.loadFixtures()` loads all the files, and `server.loadFixtures(file1, file2...)` loads selective fixture files.
For example, in a test you may want to start out with all your fixture data loaded:
```js
test('I can view the photos', function() {
server.loadFixtures();
server.createList('photo', 10);
visit('/');
andThen(() => {
equal( find('img').length, 10 );
});
});
```
or in development, you may want to load a few reference fixture files, and use factories to define the rest of your data:
```js
new Server({
...,
seeds(server) {
server.loadFixtures('countries', 'states');
let author = server.create('author');
server.createList('post', 10, {author_id: author.id});
}
})
```
@method loadFixtures
@param {String} [...args] The name of the fixture to load.
@public
*/
loadFixtures(...args) {
let { fixtures } = this._config;
if (args.length) {
let camelizedArgs = args.map(camelize);
let missingKeys = camelizedArgs.filter((key) => !fixtures[key]);
if (missingKeys.length) {
throw new Error(`Fixtures not found: ${missingKeys.join(", ")}`);
}
fixtures = pick(fixtures, ...camelizedArgs);
}
this.db.loadData(fixtures);
}
/*
Factory methods
*/
/**
* Load factories into Mirage's database.
*
* @method loadFactories
* @param {Object} factoryMap
* @public
* @hide
*/
loadFactories(factoryMap = {}) {
// Store a reference to the factories
let currentFactoryMap = this._factoryMap || {};
this._factoryMap = assign(currentFactoryMap, factoryMap);
// Create a collection for each factory
Object.keys(factoryMap).forEach((type) => {
let collectionName = this.schema.toCollectionName(type);
this.db.createCollection(collectionName);
});
}
/**
* Get the factory for a given type.
*
* @method factoryFor
* @param {String} type
* @private
* @hide
*/
factoryFor(type) {
let camelizedType = camelize(type);
if (this._factoryMap && this._factoryMap[camelizedType]) {
return this._factoryMap[camelizedType];
}
}
build(type, ...traitsAndOverrides) {
let traits = traitsAndOverrides.filter(
(arg) => arg && typeof arg === "string"
);
let overrides = find(traitsAndOverrides, (arg) => isPlainObject(arg));
let camelizedType = camelize(type);
// Store sequence for factory type as instance variable
this.factorySequences = this.factorySequences || {};
this.factorySequences[camelizedType] =
this.factorySequences[camelizedType] + 1 || 0;
let OriginalFactory = this.factoryFor(type);
if (OriginalFactory) {
OriginalFactory = OriginalFactory.extend({});
let attrs = OriginalFactory.attrs || {};
this._validateTraits(traits, OriginalFactory, type);
let mergedExtensions = this._mergeExtensions(attrs, traits, overrides);
this._mapAssociationsFromAttributes(type, attrs, overrides);
this._mapAssociationsFromAttributes(type, mergedExtensions);
let Factory = OriginalFactory.extend(mergedExtensions);
let factory = new Factory();
let sequence = this.factorySequences[camelizedType];
return factory.build(sequence);
} else {
return overrides;
}
}
buildList(type, amount, ...traitsAndOverrides) {
assert(
isInteger(amount),
`second argument has to be an integer, you passed: ${typeof amount}`
);
let list = [];
const buildArgs = [type, ...traitsAndOverrides];
for (let i = 0; i < amount; i++) {
list.push(this.build.apply(this, buildArgs));
}
return list;
}
/**
Generates a single model of type *type*, inserts it into the database (giving it an id), and returns the data that was
added.
```js
test("I can view a contact's details", function() {
let contact = server.create('contact');
visit('/contacts/' + contact.id);
andThen(() => {
equal( find('h1').text(), 'The contact is Link');
});
});
```
You can override the attributes from the factory definition with a
hash passed in as the second parameter. For example, if we had this factory
```js
export default Factory.extend({
name: 'Link'
});
```
we could override the name like this:
```js
test("I can view the contacts", function() {
server.create('contact', {name: 'Zelda'});
visit('/');
andThen(() => {
equal( find('p').text(), 'Zelda' );
});
});
```
@method create
@param type the singularized type of the model
@param traitsAndOverrides
@public
*/
create(type, ...options) {
assert(
this._modelOrFactoryExistsForType(type),
`You called server.create('${type}') but no model or factory was found. Make sure you're passing in the singularized version of the model or factory name.`
);
// When there is a Model defined, we should return an instance
// of it instead of returning the bare attributes.
let traits = options.filter((arg) => arg && typeof arg === "string");
let overrides = find(options, (arg) => isPlainObject(arg));
let collectionFromCreateList = find(
options,
(arg) => arg && Array.isArray(arg)
);
let attrs = this.build(type, ...traits, overrides);
let modelOrRecord;
if (this.schema && this.schema[this.schema.toCollectionName(type)]) {
let modelClass = this.schema[this.schema.toCollectionName(type)];
modelOrRecord = modelClass.create(attrs);
} else {
let collection, collectionName;
if (collectionFromCreateList) {
collection = collectionFromCreateList;
} else {
collectionName = this.schema
? this.schema.toInternalCollectionName(type)
: `_${this.inflector.pluralize(type)}`;
collection = this.db[collectionName];
}
assert(
collection,
`You called server.create('${type}') but no model or factory was found.`
);
modelOrRecord = collection.insert(attrs);
}
let OriginalFactory = this.factoryFor(type);
if (OriginalFactory) {
OriginalFactory.extractAfterCreateCallbacks({ traits }).forEach(
(afterCreate) => {
afterCreate(modelOrRecord, this);
}
);
}
return modelOrRecord;
}
/**
Creates *amount* models of type *type*, optionally overriding the attributes from the factory with *attrs*.
Returns the array of records that were added to the database.
Here's an example from a test:
```js
test("I can view the contacts", function() {
server.createList('contact', 5);
let youngContacts = server.createList('contact', 5, {age: 15});
visit('/');
andThen(function() {
equal(currentRouteName(), 'index');
equal( find('p').length, 10 );
});
});
```
And one from setting up your development database:
```js
new Server({
seeds(server) {
let contact = server.create('contact')
server.createList('address', 5, { contact })
}
})
```
@method createList
@param type
@param amount
@param traitsAndOverrides
@public
*/
createList(type, amount, ...traitsAndOverrides) {
assert(
this._modelOrFactoryExistsForType(type),
`You called server.createList('${type}') but no model or factory was found. Make sure you're passing in the singularized version of the model or factory name.`
);
assert(
isInteger(amount),
`second argument has to be an integer, you passed: ${typeof amount}`
);
let list = [];
let collectionName = this.schema
? this.schema.toInternalCollectionName(type)
: `_${this.inflector.pluralize(type)}`;
let collection = this.db[collectionName];
const createArguments = [type, ...traitsAndOverrides, collection];
for (let i = 0; i < amount; i++) {
list.push(this.create.apply(this, createArguments));
}
return list;
}
/**
Shutdown the server and stop intercepting network requests.
@method shutdown
@public
*/
shutdown() {
if (typeof window !== "undefined") {
this.pretender.shutdown();
}
if (typeof window !== "undefined" && this.environment === "test") {
window.server = undefined;
}
}
resource(resourceName, { only, except, path } = {}) {
resourceName = this.inflector.pluralize(resourceName);
path = path || `/${resourceName}`;
only = only || [];
except = except || [];
if (only.length > 0 && except.length > 0) {
throw "cannot use both :only and :except options";
}
let actionsMethodsAndsPathsMappings = {
index: { methods: ["get"], path: `${path}` },
show: { methods: ["get"], path: `${path}/:id` },
create: { methods: ["post"], path: `${path}` },
update: { methods: ["put", "patch"], path: `${path}/:id` },
delete: { methods: ["del"], path: `${path}/:id` },
};
let allActions = Object.keys(actionsMethodsAndsPathsMappings);
let actions =
(only.length > 0 && only) ||
(except.length > 0 &&
allActions.filter((action) => except.indexOf(action) === -1)) ||
allActions;
actions.forEach((action) => {
let methodsWithPath = actionsMethodsAndsPathsMappings[action];
methodsWithPath.methods.forEach((method) => {
return path === resourceName
? this[method](methodsWithPath.path)
: this[method](methodsWithPath.path, resourceName);