Debian Codegraph @

lib/route-handlers/shorthands/get.js

raw
1 import assert from "../../assert";
2 import BaseShorthandRouteHandler from "./base";
3 import Response from "../../response";
4 import { camelize } from "../../utils/inflector";
5
6 /**
7 * @hide
8 */
9 export default class GetShorthandRouteHandler extends BaseShorthandRouteHandler {
10 /*
11 Retrieve a model/collection from the db.
12
13 Examples:
14 this.get('/contacts', 'contact');
15 this.get('/contacts/:id', 'contact');
16 */
17 handleStringShorthand(request, modelClass) {
18 let modelName = this.shorthand;
19 let camelizedModelName = camelize(modelName);
20
21 assert(
22 modelClass,
23 `The route handler for ${request.url} is trying to access the ${camelizedModelName} model, but that model doesn't exist.`
24 );
25
26 let id = this._getIdForRequest(request);
27 if (id) {
28 let model = modelClass.find(id);
29 if (!model) {
30 return new Response(404);
31 } else {
32 return model;
33 }
34 } else if (this.options.coalesce) {
35 let ids = this.serializerOrRegistry.getCoalescedIds(
36 request,
37 camelizedModelName
38 );
39 if (ids) {
40 return modelClass.find(ids);
41 }
42 }
43 return modelClass.all();
44 }
45
46 /*
47 Retrieve an array of collections from the db.
48
49 Ex: this.get('/home', ['contacts', 'pictures']);
50 */
51 handleArrayShorthand(request, modelClasses) {
52 let keys = this.shorthand;
53 let id = this._getIdForRequest(request);
54
55 /*
56 If the first key is singular and we have an id param in
57 the request, we're dealing with the version of the shorthand
58 that has a parent model and several has-many relationships.
59 We throw an error, because the serializer is the appropriate
60 place for this now.
61 */
62 assert(
63 !id || this._container.inflector.singularize(keys[0]) !== keys[0],
64 `It looks like you're using the "Single record with
65 related records" version of the array shorthand, in addition to opting
66 in to the model layer. This shorthand was made when there was no
67 serializer layer. Now that you're using models, please ensure your
68 relationships are defined, and create a serializer for the parent
69 model, adding the relationships there.`
70 );
71
72 return modelClasses.map((modelClass) => modelClass.all());
73 }
74 }