summaryrefslogtreecommitdiff
path: root/src/app/db/service/pivot/methods.js
blob: 1f54345ae0852e85072073fb9bf39ac2851e6940 (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
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
/**
 * Pivot Table Service API Methods
 * @module app/db/service/pivot/methods
 */

import * as db from "app/db/query";
import {
  buildPaginationResponse,
  getOffsetAndLimit,
  getSort,
  getQueryFilters,
  reduceValidColumns,
  tableNameToModelName,
} from "app/db/helpers";
import {
  indexPivotTable,
  getPivotModels,
  handleCreateOne,
  handleCreateMany,
} from "app/db/service/pivot/helpers";
import { PERMISSIONS } from "app/constants";
import debugModule from "debug";

/**
 * Debug logger
 */
const debug = debugModule("shoebox:service:pivot");

/**
 * API to index a model via a pivot table.  Allows pagination, filtering.
 */
export function index(service) {
  const { queryBuilder } = service;
  const { pivotColumns, paginate } = service.options;
  const {
    parent,
    Model,
    ChildModel,
    pivotTableName,
    childTableName,
    parentIdAttribute,
    childIdAttribute,
    parentPivotRelation,
    childRelation,
  } = getPivotModels(service);

  const pivotAttribute = Model.prototype.idAttribute.replace(/_id$/, "");
  // console.log(pivotIdAttribute, pivotAttribute);

  return async function indexPivotMiddleware(request, response, next) {
    const { query } = request;
    const withRelated = query.related ? query.related.split(",") : [];

    const filters = getQueryFilters(query);
    const hasFilters = Object.keys(filters).length > 0;
    const { offset, limit } = getOffsetAndLimit(query, paginate);
    const { sortField, sortDirection, sortCount } = getSort(query, ChildModel);

    // Fetch the immediate parent of the pivot table based on the name of the parent resource.
    // This instance is added to the `request.parents` object when performing the permissions check.
    const parentInstance = request.parents[parent.resource];

    // Fetch the children of the pivot table.
    let childData;

    if (sortCount) {
      // Sort by the count of a secondary pivot relation on the child
      const sortTableName = childTableName + "_" + sortField;
      const sortOrderName = sortField + "_count";
      const sortTableModel = request.bookshelf.model(
        tableNameToModelName(childTableName + "_" + sortField)
      );
      if (!sortTableModel) {
        return next(new Error("No such pivot table"));
      }
      let query = request.bookshelf.knex
        .from(childTableName)
        .select(
          childTableName + ".*",
          request.bookshelf
            .knex(sortTableName)
            .count("*")
            .whereRaw("?? = ??", [
              sortTableName + "." + childIdAttribute,
              childTableName + "." + childIdAttribute,
            ])
            .as(sortOrderName)
        )
        .leftJoin(
          pivotTableName,
          pivotTableName + "." + childIdAttribute,
          childTableName + "." + childIdAttribute
        )
        .where(
          pivotTableName + "." + parentIdAttribute,
          "=",
          parentInstance.id
        );

      if (hasFilters) {
        query.andWhere((builder) =>
          queryBuilder(builder, pivotColumns, filters)
        );
      }

      childData = await query
        .orderBy(sortOrderName, sortDirection)
        .offset(offset)
        .limit(limit);
    } else {
      // Typical sort
      childData = await parentInstance
        .related(childRelation)
        .query((builder) => {
          if (hasFilters) {
            builder.where((builder) =>
              queryBuilder(builder, pivotColumns, filters)
            );
          }
          builder.orderBy(sortField, sortDirection);
          if (limit) {
            builder.limit(limit);
          }
          if (offset) {
            builder.offset(offset);
          }
          return builder;
        })
        .fetch({ withRelated });

      // Fetch the pivot table in case there are any necessary values on it
      await Promise.all(
        childData.map(async (item) => {
          item.set(pivotAttribute, await item.pivot.fetch());
        })
      );
    }

    // Count the pivot table and generate pagination
    let rowCount;
    if (hasFilters) {
      rowCount = await parentInstance
        .related(childRelation)
        .where((builder) => queryBuilder(builder, pivotColumns, filters))
        .count();
    } else {
      rowCount = await parentInstance.related(parentPivotRelation).count();
    }
    const pagination = buildPaginationResponse({ rowCount, query, paginate });

    response.locals = { data: childData, pagination, query };
    next();
  };
}

/**
 * API to fetch a single relation via the pivot table.
 */
export function show(service) {
  const {
    parent,
    Model,
    parentIdAttribute,
    childIdAttribute,
    pivotChildRelation,
  } = getPivotModels(service);

  return async function showPivotMiddleware(request, response, next) {
    const { query, parents } = request;
    const parentInstance = parents[parent.resource];
    const withRelated = query.related ? query.related.split(",") : [];

    let child, data;

    try {
      data = await db.show({
        Model: Model,
        field: childIdAttribute,
        objectID: parseInt(request.params.id),
        criteria: {
          [parentIdAttribute]: parentInstance.get(parentIdAttribute),
        },
        withRelated,
      });
    } catch (error) {
      debug(`${service.resource} Error fetching pivot`);
      debug(error);
      return next(error);
    }

    if (!data) {
      response.locals = {};
      next();
    }

    try {
      child = await data.related(pivotChildRelation).fetch();
    } catch (error) {
      debug(`${service.resource} Error fetching child`);
      debug(error);
      return next(error);
    }

    response.locals = { child, data };
    next();
  };
}

/**
 * API to insert a new record
 */
export function create(service) {
  const { Model, parentIdAttribute, childIdAttribute } = getPivotModels(
    service
  );
  return async function createPivotMiddleware(request, response, next) {
    const { params } = request;
    let data;
    const body = reduceValidColumns(
      request.body,
      service.columns,
      service.options.privateFields
    );
    if (service.options.parent) {
      service.idAttributes.forEach((idAttribute) => {
        if (idAttribute in params && idAttribute in service.columns) {
          body[idAttribute] = parseInt(params[idAttribute]);
        }
      });
    }
    try {
      const instances = await indexPivotTable({
        Model,
        parentIdAttribute,
        parentId: body[parentIdAttribute],
        childIdAttribute,
        childId: body[childIdAttribute],
      });
      if (Array.isArray(body[childIdAttribute])) {
        data = await handleCreateMany({
          Model: service.Model,
          data: body,
          childIdAttribute,
          instances,
        });
      } else {
        data = await handleCreateOne({
          Model: service.Model,
          data: body,
          instances,
        });
      }
    } catch (error) {
      debug(`${service.resource} create error`);
      console.error(error);
      return next(error);
    }
    response.locals = { data };
    next();
  };
}

/**
 * API to update a single record
 */
export function update(service) {
  return async function updatePivotMiddleware(request, response, next) {
    const { data: instance } = response.locals;
    const { user, permission } = request;
    if (
      permission === PERMISSIONS.ALLOW_FOR_OWNER &&
      instance.get("user_id") !== user.user_id
    ) {
      return next(new Error("PermissionsError"));
    }
    const body = reduceValidColumns(
      request.body,
      service.columns,
      service.options.privateFields
    );
    let data;
    try {
      data = await db.update({
        instance,
        data: body,
      });
    } catch (error) {
      debug(`${service.resource} update error`);
      debug(error);
      next(new Error(error));
    }
    response.locals = { data };
    next();
  };
}

/**
 * API to destroy a pivot table relation.
 */
export function destroy(service) {
  const { Model, parentIdAttribute, childIdAttribute } = getPivotModels(
    service
  );
  return async function destroyPivotMiddleware(request, response, next) {
    const idsToDelete = request.params.id || request.body[childIdAttribute];
    try {
      const instances = await indexPivotTable({
        Model,
        parentIdAttribute,
        parentId: request.params[parentIdAttribute],
        childIdAttribute,
        childId: idsToDelete,
      });
      await Promise.all(instances.map((instance) => instance.destroy()));
    } catch (error) {
      debug(`${service.resource} destroy error`);
      debug(error);
      return next(new Error(error));
    }
    response.locals.success = true;
    response.locals.id = idsToDelete;
    next();
  };
}

/**
 * API to destroy many records. Note that the normal destroy API accomplishes this.
 * @type {Function}
 */
export const destroyMany = destroy;