UNPKG

2.69 kBJavaScriptView Raw
1/*
2 * Copyright (c) 2018 One Hill Technologies, LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17const assert = require ('assert');
18const { computed } = require ('base-object');
19
20const Action = require ('./action');
21const Controller = require ('./controller');
22const NotFoundError = require ('./not-found-error');
23
24/**
25 * @class NotFound
26 */
27const NotFound = Action.extend ({
28 execute () {
29 return Promise.reject (new NotFoundError ('not_found', 'Not found'));
30 }
31});
32
33/**
34 * @class ResourceController
35 *
36 * The base class for all resource controllers. The resource controller provide a
37 * common interface that defines the expected CRUD operations for a resource:
38 *
39 * = create
40 * = retrieve: getOne, getAll
41 * = update
42 * = delete
43 */
44module.exports = Controller.extend ({
45 /// Name of the resource managed by the resource controller.
46 name: null,
47
48 /// The namespace for the resource controller. The namespace is used to
49 /// assist with scoping the resource and preventing collisions with like
50 /// named resources.
51 namespace: null,
52
53 /// Id for the resource. If the id is not provided, it is generated from
54 /// the name of the resource.
55 id: null,
56
57 mergedProperties: ['_actions'],
58
59 _actions: {
60 // CRUD operations
61 create: {verb: 'post', method: 'create'},
62 getAll: {verb: 'get', method: 'getAll'},
63 getOne: {verb: 'get', path: '/:rcId', method: 'getOne'},
64 update: {verb: 'put', path: '/:rcId', method: 'update'},
65 delete: {verb: 'delete', path: '/:rcId', method: 'delete'},
66
67 // support operations
68 count: {verb: 'get', path: '/count', method: 'count'}
69 },
70
71 resourceId: computed ({
72 get () { return this.id; }
73 }),
74
75 actions: computed ({
76 get () { return this._actions; }
77 }),
78
79 init () {
80 this._super.call (this, ...arguments);
81
82 assert (!!this.name, 'You must provide a \'name\' property.');
83
84 if (!this.id)
85 this.id = `${this.name}Id`;
86 },
87
88 create () {
89 return NotFound;
90 },
91
92 getAll () {
93 return NotFound;
94 },
95
96 getOne () {
97 return NotFound;
98 },
99
100 update () {
101 return NotFound;
102 },
103
104 delete () {
105 return NotFound;
106 },
107
108 count () {
109 return NotFound;
110 }
111});