summaryrefslogtreecommitdiff
path: root/src/app/db/service/base/helpers.js
blob: 9ab1119f772469fdb46fffb89b1b882717fcb162 (plain)
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
/**
 * Service construction helpers
 * @module app/db/service/base/helpers
 */

import {
  checkPermission,
  checkParentPermission,
} from "app/services/permission/helpers";
import { sendResponse } from "app/db/service/base/response";

/**
 * Returns a helper function used by an iterator when creating custom routes.
 * @param {Service} service   the affected service
 * @param {Service} methods   the CRUD methods associated with the service
 * @returns {Function}        the method called on the iterable
 */
export function createCustomRoute(service, methods) {
  const { parent } = service.options;
  /**
   * Create a custom route.  If the route contains `/:id`, the record will be fetched before calling the handlers.
   * @param {string} method      the method name
   * @param {string} route       the route to mount on
   * @param {Array}  handlers    a list of middleware
   * @param {Object} permissions a permissions object
   */
  return function addCustomRouteHandler({
    method,
    route,
    handlers,
    permissions,
  }) {
    service.router[(method || "get").toLowerCase()](
      route,
      (parent ? [checkParentPermission(parent)] : [])
        .concat(permissions ? [checkPermission(permissions)] : [])
        .concat(route.match(/^\/:id/) ? methods.show(service) : [])
        .concat(handlers)
        .concat([sendResponse])
    );
  };
}

/**
 * Returns a helper function used by an iterator when creating CRUD routes.
 * @param {Service} service   the affected service
 * @param {Object}  methods   a set of methods to use
 * @returns {Function}        the method called on the iterable
 */
export function createCrudRoute(service, methods) {
  const { parent, permissions, hooks, logging } = service.options;
  const loggingHook = logging ? [logging] : [];
  /**
   * Create a CRUD route
   * @param {string} type  the type of route to create
   */
  return function addEnabledRoute(type) {
    const beforeHooks = hooks?.before[type] || [];
    const afterHooks = hooks?.after[type] || [];
    let verb, route, handlers;
    switch (type) {
      case "index":
        verb = "get";
        route = "/";
        handlers = [
          checkPermission(permissions, "read"),
          ...beforeHooks,
          methods.index(service),
        ];
        break;
      case "show":
        verb = "get";
        route = "/:id";
        handlers = [
          checkPermission(permissions, "read"),
          ...beforeHooks,
          methods.show(service),
        ];
        break;
      case "create":
        verb = "post";
        route = "/";
        handlers = [
          checkPermission(permissions, "create"),
          ...beforeHooks,
          methods.create(service),
          ...loggingHook,
        ];
        break;
      case "update":
        verb = "put";
        route = "/:id";
        handlers = [
          checkPermission(permissions, "read"),
          ...(hooks?.before?.show || []),
          methods.show(service),
          ...beforeHooks,
          checkPermission(permissions, "update"),
          methods.update(service),
          ...loggingHook,
        ];
        break;
      case "updateMany":
        verb = "put";
        route = "/";
        handlers = [
          checkPermission(permissions, "read"),
          methods.showMany(service),
          ...beforeHooks,
          checkPermission(permissions, "update"),
          methods.updateMany(service),
          ...loggingHook,
        ];
        break;
      case "sort":
        verb = "post";
        route = "/sort";
        handlers = [
          checkPermission(permissions, "read"),
          ...beforeHooks,
          checkPermission(permissions, "update"),
          methods.sort(service),
          // ...loggingHook,
        ];
        break;
      case "destroy":
        verb = "delete";
        route = "/:id";
        handlers = [
          checkPermission(permissions, "read"),
          methods.show(service),
          ...beforeHooks,
          checkPermission(permissions, "destroy"),
          methods.destroy(service),
          ...loggingHook,
        ];
        break;
      case "destroyMany":
        verb = "delete";
        route = "/";
        handlers = [
          checkPermission(permissions, "read"),
          ...beforeHooks,
          // above, i'm using show to see if the records exist before deleting them
          // but if deleting many, this is probably being done on the pivot table,
          // and where the check is accomplished implicitly by the destroy middleware.
          // if delete permission is ALLOW_FOR_OWNER, we still have to make the check.
          // methods.showMany(service),
          checkPermission(permissions, "destroy"),
          methods.destroyMany(service),
          ...loggingHook,
        ];
        break;
      default:
        console.error(`Unknown route: ${type}`);
        return;
    }
    let routeHandlers = []
      .concat(
        parent
          ? [formatParentParameters(service), checkParentPermission(parent)]
          : []
      )
      .concat(handlers)
      .concat(afterHooks)
      .concat(type === "destroy" ? [onDestroyCleanupResponse] : [])
      .concat([sendResponse]);
    service.router[verb](
      route,
      routeHandlers.filter((handler) => !!handler)
    );
  };
}

/**
 * Helper function to convert request.params to integers where appropriate
 */
export function formatParentParameters(service) {
  const parentIdAttributes = service.idAttributes.slice(1);
  return function formatParentParametersMiddleware(request, response, next) {
    const hasInvalidParams = parentIdAttributes.some((parentIdAttribute) => {
      const value = parseInt(request.params[parentIdAttribute]);
      if (!value) {
        return true;
      }
      request.params[parentIdAttribute] = value;
      return false;
    });
    if (hasInvalidParams) {
      return next(new Error("malformed parent ID"));
    }
    next();
  };
}

/**
 * Helper function to clean up local data.  We make the deleted object available to middleware, but not to the client.
 * @param  {express.request}  request  the request object
 * @param  {express.response} response the response object
 * @param  {function}         next     function to proceed to the next middleware
 */
export function onDestroyCleanupResponse(request, response, next) {
  delete response.locals.data;
  delete response.locals.child;
  next();
}

/**
 * For each returned object, fetch the count of a particular relation
 * @param  {string} relation   name of relation
 * @param  {string} valueName  (optional) name of the value to set on the output object, defaults to `{relation}_count``
 * @return {Function}          middleware function (`after` hook)
 */
export function getRelationCount(relation, as, where) {
  return async function getRelationCountMiddleware(request, response, next) {
    if (!response.locals.data) {
      return next();
    }
    const countField = relation + "_count";
    const items =
      "length" in response.locals.data
        ? response.locals.data
        : [response.locals.data];
    const getCountPromises = items.map(async (item) => {
      if (!item || !item.related || countField in item) return;
      const itemRelation = item.related(relation);
      if (where) {
        itemRelation.where(where);
      }
      const count = await itemRelation.count();
      item.set(as || countField, count);
    });
    try {
      await Promise.all(getCountPromises);
    } catch (error) {
      console.error(error);
    }
    next();
  };
}