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

import Service from "app/db/service/base";
import * as pivotMethods from "app/db/service/pivot/methods";
import { loadColumns } from "app/db/helpers";

/**
 * Create a relational API service to access models via a pivot table.
 * All options are the same as on a normal service, but with a few changes:
 * @param {Model|string}  options.Model                    the Bookshelf pivot model
 * @param {string}        options.ChildModel               the Bookshelf model inheriting from the pivot
 * @param {string}        options.parentPivotRelation      relation method on the parent that will access the pivot
 * @param {string}        options.pivotChildRelation       relation method on the pivot that will access the child
 * @param {string}        options.childRelation            relation method on the parent that will access the children
 * @return {Service} the service object
 */
export default async function PivotTableService(options) {
  const { ChildModel, bookshelf } = options;

  /** Locate the Model specified in the configuration */
  options.ChildModel =
    ChildModel && typeof ChildModel === "string"
      ? bookshelf.model(ChildModel)
      : ChildModel;

  /** Due to the way English is inflected, sometimes these are the same and only one needs to be specified */
  options.pivotChildRelation =
    options.pivotChildRelation || options.childRelation;

  options.pivotColumns =
    ChildModel && (await loadColumns(bookshelf, ChildModel));

  // /** Use the model to identify the service's resource name */
  // options.parentResource = options.name || service.Model?.prototype.tableName;
  // if (!service.resource) {
  //   throw new Error("No name or model defined for resource");
  // }

  const service = await Service(options, pivotMethods);
  service.type = "pivot";
  service.ChildModel = options.ChildModel;

  return service;
}