@sdflc/backend-helpers 1.0.129 → 1.0.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,42 @@
1
1
  import { BaseController } from './BaseController';
2
2
  import { BaseRestApiCrudControllerPropsInterface } from './interfaces';
3
+ /**
4
+ * BaseRestApiCrudController
5
+ *
6
+ * Provides a standard REST CRUD surface that maps HTTP requests to core
7
+ * method calls using the same argument shapes as GraphQL resolvers. This
8
+ * means a core written for GraphQL works identically over REST with no
9
+ * changes.
10
+ *
11
+ * ── Argument shapes ───────────────────────────────────────────────────────────
12
+ * list → core.list({ filter, params })
13
+ * get → core.get({ id })
14
+ * getMany → core.getMany({ ids })
15
+ * create → core.create({ params }) body: { params: {...} }
16
+ * createMany → core.createMany({ params }) body: { params: [{...}] }
17
+ * update → core.update({ where, params }) body: { params: {...} }
18
+ * updateMany → core.updateMany({ params }) body: { params: [{...}] }
19
+ * remove → core.remove({ where })
20
+ * removeMany → core.removeMany({ where })
21
+ *
22
+ * ── Extension points ──────────────────────────────────────────────────────────
23
+ * buildWhere(req, ids) — override to add extra where conditions beyond id
24
+ * buildFilter(req) — override to customise filter extraction from QS
25
+ * buildParams(req) — override to customise pagination extraction from QS
26
+ *
27
+ * ── Route registration ────────────────────────────────────────────────────────
28
+ * Each subclass declares its own `root` path (e.g. '/api/v1/party-ticket-types').
29
+ * app.ts calls controller.init({ app, root: controller.root }) so no
30
+ * root needs to be passed at instantiation time.
31
+ *
32
+ * ── Context resolution ────────────────────────────────────────────────────────
33
+ * `getContext` defaults to (req) => req.context, which is set by the
34
+ * createContext middleware in app.ts before any REST handler runs.
35
+ * Override via props only when a controller needs a different context source.
36
+ */
3
37
  declare class BaseRestApiCrudController extends BaseController {
38
+ /** Mount path for this controller, e.g. '/api/v1/party-ticket-types' */
39
+ root: string;
4
40
  protected coreToUse: string;
5
41
  protected getContext: (req: any) => Promise<any> | any;
6
42
  protected disableList: boolean;
@@ -12,81 +48,103 @@ declare class BaseRestApiCrudController extends BaseController {
12
48
  protected disableUpdateMany: boolean;
13
49
  protected disableRemove: boolean;
14
50
  protected disableRemoveMany: boolean;
15
- constructor(props: BaseRestApiCrudControllerPropsInterface);
51
+ constructor(props?: BaseRestApiCrudControllerPropsInterface);
16
52
  /**
17
53
  * Builds the `where` object for update and remove operations.
18
54
  *
19
- * Base implementation uses the ids parsed from the `:id` route param.
20
- * Override in a subclass to add extra conditions from the request body
21
- * or query string while keeping the URL pattern intact.
55
+ * Base implementation returns { id: ids } where ids is the array parsed
56
+ * from the `:id` route param (single or comma-separated).
22
57
  *
23
- * @param req - the Express request
24
- * @param ids - ids parsed from req.params.id (always an array)
58
+ * Override in a subclass to add extra conditions from req.body or
59
+ * req.query while keeping the /:id URL pattern intact. Example:
60
+ *
61
+ * protected buildWhere(req: any, ids: string[]): Record<string, any> {
62
+ * return { id: ids, statusId: req.body?.where?.statusId };
63
+ * }
25
64
  */
26
65
  protected buildWhere(req: any, ids: string[]): Record<string, any>;
27
66
  /**
28
- * Builds the `filter` object for list operations.
29
- *
30
- * Base implementation treats every query string key that is NOT in
31
- * PAGINATION_KEYS as a filter field. Override to apply custom filtering
32
- * logic or to parse typed values (e.g. booleans, arrays).
67
+ * Builds the `filter` object passed to core.list().
33
68
  *
34
- * @param req - the Express request
69
+ * Base implementation treats every query string key that is NOT a known
70
+ * pagination key as a filter field. Override to apply custom parsing
71
+ * (e.g. typed booleans, array values, renamed fields).
35
72
  */
36
73
  protected buildFilter(req: any): Record<string, any>;
37
74
  /**
38
- * Builds the `params` object for list operations (pagination / sorting).
75
+ * Builds the `params` object passed to core.list() (pagination / sorting).
39
76
  *
40
77
  * Base implementation picks only the known PAGINATION_KEYS from the query
41
- * string. Override to support additional pagination conventions.
42
- *
43
- * @param req - the Express request
78
+ * string. Override to support additional or renamed pagination conventions.
44
79
  */
45
80
  protected buildParams(req: any): Record<string, any>;
46
81
  protected resolveCore(req: any): Promise<any>;
82
+ /**
83
+ * Registers all enabled routes on the Express app under `root`.
84
+ * Called once at startup by app.ts:
85
+ *
86
+ * controller.init({ app, root: controller.root })
87
+ *
88
+ * Routes are only registered for operations that are not disabled.
89
+ * /many routes are registered before /:id to avoid Express matching
90
+ * "many" as an id param.
91
+ */
47
92
  init(props: {
48
93
  app: any;
49
94
  root: string;
50
95
  }): void;
51
96
  /**
52
97
  * GET /
53
- * Splits the query string into filter and pagination params, consistent
54
- * with the GraphQL list resolver argument shape.
98
+ *
99
+ * Splits the query string into filter (non-pagination keys) and params
100
+ * (pagination keys) via buildFilter() and buildParams(). Shape matches
101
+ * the GraphQL list resolver: core.list({ filter, params }).
55
102
  */
56
103
  protected list(req: any): Promise<any>;
57
104
  /**
58
105
  * GET /:id
59
- * Routes to core.get() for a single id, or core.getMany() when the :id
60
- * param contains commas. Argument shape matches GraphQL resolver args.
106
+ *
107
+ * Routes to core.get({ id }) for a single id, or core.getMany({ ids })
108
+ * when the :id param contains comma-separated values.
61
109
  */
62
110
  protected getOrGetMany(req: any): Promise<any>;
63
111
  /**
64
112
  * POST /
65
- * Body must be { params: {...} } — consistent with GraphQL mutation args.
113
+ *
114
+ * Body must be { params: {...} }.
115
+ * Consistent with GraphQL mutation: partyTicketTypeCreate(params: Input).
66
116
  */
67
117
  protected create(req: any): Promise<any>;
68
118
  /**
69
119
  * POST /many
70
- * Body must be { params: [{...}, ...] } or { params: {...} } for a single item.
120
+ *
121
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
122
+ * item which is auto-wrapped in an array.
71
123
  */
72
124
  protected createMany(req: any): Promise<any>;
73
125
  /**
74
126
  * PUT /:id
75
- * Body must be { params: {...} }. The :id route param is parsed and merged
76
- * into the where object via buildWhere() — override buildWhere() to add
77
- * extra conditions while keeping the URL pattern.
127
+ *
128
+ * Body must be { params: {...} }. The :id route param is parsed into an
129
+ * array and passed to buildWhere() — override buildWhere() to add extra
130
+ * conditions beyond id while keeping the /:id URL pattern.
131
+ *
132
+ * Shape: core.update({ where: { id: [id] }, params: {...} })
78
133
  */
79
134
  protected update(req: any): Promise<any>;
80
135
  /**
81
136
  * PUT /many
82
- * Body must be { params: [{...}, ...] } or { params: {...} } for a single item.
137
+ *
138
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
139
+ * item which is auto-wrapped in an array.
83
140
  */
84
141
  protected updateMany(req: any): Promise<any>;
85
142
  /**
86
143
  * DELETE /:id
87
- * Routes to core.remove() for a single id, or core.removeMany() when the
88
- * :id param contains commas. where is built via buildWhere() — override
89
- * to add extra conditions while keeping the URL pattern.
144
+ *
145
+ * Routes to core.remove({ where }) for a single id, or
146
+ * core.removeMany({ where }) for comma-separated ids. where is built via
147
+ * buildWhere() — override to add extra conditions.
90
148
  */
91
149
  protected removeOrRemoveMany(req: any): Promise<any>;
92
150
  }
@@ -9,7 +9,43 @@ const parseIds_1 = require("./parseIds");
9
9
  * Everything else in the query string is treated as a filter field.
10
10
  */
11
11
  const PAGINATION_KEYS = new Set(['page', 'limit', 'offset', 'sortBy', 'sortDir', 'orderBy']);
12
+ /**
13
+ * BaseRestApiCrudController
14
+ *
15
+ * Provides a standard REST CRUD surface that maps HTTP requests to core
16
+ * method calls using the same argument shapes as GraphQL resolvers. This
17
+ * means a core written for GraphQL works identically over REST with no
18
+ * changes.
19
+ *
20
+ * ── Argument shapes ───────────────────────────────────────────────────────────
21
+ * list → core.list({ filter, params })
22
+ * get → core.get({ id })
23
+ * getMany → core.getMany({ ids })
24
+ * create → core.create({ params }) body: { params: {...} }
25
+ * createMany → core.createMany({ params }) body: { params: [{...}] }
26
+ * update → core.update({ where, params }) body: { params: {...} }
27
+ * updateMany → core.updateMany({ params }) body: { params: [{...}] }
28
+ * remove → core.remove({ where })
29
+ * removeMany → core.removeMany({ where })
30
+ *
31
+ * ── Extension points ──────────────────────────────────────────────────────────
32
+ * buildWhere(req, ids) — override to add extra where conditions beyond id
33
+ * buildFilter(req) — override to customise filter extraction from QS
34
+ * buildParams(req) — override to customise pagination extraction from QS
35
+ *
36
+ * ── Route registration ────────────────────────────────────────────────────────
37
+ * Each subclass declares its own `root` path (e.g. '/api/v1/party-ticket-types').
38
+ * app.ts calls controller.init({ app, root: controller.root }) so no
39
+ * root needs to be passed at instantiation time.
40
+ *
41
+ * ── Context resolution ────────────────────────────────────────────────────────
42
+ * `getContext` defaults to (req) => req.context, which is set by the
43
+ * createContext middleware in app.ts before any REST handler runs.
44
+ * Override via props only when a controller needs a different context source.
45
+ */
12
46
  class BaseRestApiCrudController extends BaseController_1.BaseController {
47
+ /** Mount path for this controller, e.g. '/api/v1/party-ticket-types' */
48
+ root;
13
49
  coreToUse;
14
50
  getContext;
15
51
  disableList;
@@ -22,45 +58,47 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
22
58
  disableRemove;
23
59
  disableRemoveMany;
24
60
  constructor(props) {
25
- super(props);
26
- const { prefix, core, getContext } = props || {};
27
- if (!getContext) {
28
- throw new Error('BaseRestApiCrudController: `getContext` is required');
29
- }
61
+ super(props ?? {});
62
+ const { prefix, core, getContext, root } = props || {};
63
+ this.root = root ?? '';
30
64
  this.coreToUse = core || `${prefix}Core`;
31
- this.getContext = getContext;
32
- this.disableList = props.disableList ?? false;
33
- this.disableGet = props.disableGet ?? false;
34
- this.disableGetMany = props.disableGetMany ?? false;
35
- this.disableCreate = props.disableCreate ?? false;
36
- this.disableCreateMany = props.disableCreateMany ?? false;
37
- this.disableUpdate = props.disableUpdate ?? false;
38
- this.disableUpdateMany = props.disableUpdateMany ?? false;
39
- this.disableRemove = props.disableRemove ?? false;
40
- this.disableRemoveMany = props.disableRemoveMany ?? false;
65
+ // Default: read the context that createContext middleware attached to req.
66
+ // Pass an explicit getContext in props only when a controller needs to
67
+ // resolve the context differently.
68
+ this.getContext = getContext ?? ((req) => req.context);
69
+ this.disableList = props?.disableList ?? false;
70
+ this.disableGet = props?.disableGet ?? false;
71
+ this.disableGetMany = props?.disableGetMany ?? false;
72
+ this.disableCreate = props?.disableCreate ?? false;
73
+ this.disableCreateMany = props?.disableCreateMany ?? false;
74
+ this.disableUpdate = props?.disableUpdate ?? false;
75
+ this.disableUpdateMany = props?.disableUpdateMany ?? false;
76
+ this.disableRemove = props?.disableRemove ?? false;
77
+ this.disableRemoveMany = props?.disableRemoveMany ?? false;
41
78
  }
42
79
  // ─── Extension points ───────────────────────────────────────────────────────
43
80
  /**
44
81
  * Builds the `where` object for update and remove operations.
45
82
  *
46
- * Base implementation uses the ids parsed from the `:id` route param.
47
- * Override in a subclass to add extra conditions from the request body
48
- * or query string while keeping the URL pattern intact.
83
+ * Base implementation returns { id: ids } where ids is the array parsed
84
+ * from the `:id` route param (single or comma-separated).
49
85
  *
50
- * @param req - the Express request
51
- * @param ids - ids parsed from req.params.id (always an array)
86
+ * Override in a subclass to add extra conditions from req.body or
87
+ * req.query while keeping the /:id URL pattern intact. Example:
88
+ *
89
+ * protected buildWhere(req: any, ids: string[]): Record<string, any> {
90
+ * return { id: ids, statusId: req.body?.where?.statusId };
91
+ * }
52
92
  */
53
93
  buildWhere(req, ids) {
54
94
  return { id: ids };
55
95
  }
56
96
  /**
57
- * Builds the `filter` object for list operations.
58
- *
59
- * Base implementation treats every query string key that is NOT in
60
- * PAGINATION_KEYS as a filter field. Override to apply custom filtering
61
- * logic or to parse typed values (e.g. booleans, arrays).
97
+ * Builds the `filter` object passed to core.list().
62
98
  *
63
- * @param req - the Express request
99
+ * Base implementation treats every query string key that is NOT a known
100
+ * pagination key as a filter field. Override to apply custom parsing
101
+ * (e.g. typed booleans, array values, renamed fields).
64
102
  */
65
103
  buildFilter(req) {
66
104
  const filter = {};
@@ -72,12 +110,10 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
72
110
  return filter;
73
111
  }
74
112
  /**
75
- * Builds the `params` object for list operations (pagination / sorting).
113
+ * Builds the `params` object passed to core.list() (pagination / sorting).
76
114
  *
77
115
  * Base implementation picks only the known PAGINATION_KEYS from the query
78
- * string. Override to support additional pagination conventions.
79
- *
80
- * @param req - the Express request
116
+ * string. Override to support additional or renamed pagination conventions.
81
117
  */
82
118
  buildParams(req) {
83
119
  const params = {};
@@ -98,6 +134,16 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
98
134
  return core;
99
135
  }
100
136
  // ─── Route registration ─────────────────────────────────────────────────────
137
+ /**
138
+ * Registers all enabled routes on the Express app under `root`.
139
+ * Called once at startup by app.ts:
140
+ *
141
+ * controller.init({ app, root: controller.root })
142
+ *
143
+ * Routes are only registered for operations that are not disabled.
144
+ * /many routes are registered before /:id to avoid Express matching
145
+ * "many" as an id param.
146
+ */
101
147
  init(props) {
102
148
  const { app, root } = props || {};
103
149
  if (!app || !root) {
@@ -106,22 +152,24 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
106
152
  if (!this.disableList) {
107
153
  app.get(root, this.json(this.list.bind(this)));
108
154
  }
109
- // GET /:id — branches to get() or getMany() based on comma presence
110
- if (!this.disableGet || !this.disableGetMany) {
111
- app.get(`${root}/:id`, this.json(this.getOrGetMany.bind(this)));
155
+ // /many must be registered before /:id so Express does not treat the
156
+ // literal string "many" as an id param value.
157
+ if (!this.disableCreateMany) {
158
+ app.post(`${root}/many`, this.json(this.createMany.bind(this)));
159
+ }
160
+ if (!this.disableUpdateMany) {
161
+ app.put(`${root}/many`, this.json(this.updateMany.bind(this)));
112
162
  }
113
163
  if (!this.disableCreate) {
114
164
  app.post(root, this.json(this.create.bind(this)));
115
165
  }
116
- if (!this.disableCreateMany) {
117
- app.post(`${root}/many`, this.json(this.createMany.bind(this)));
166
+ // GET /:id — branches to get() or getMany() based on comma presence
167
+ if (!this.disableGet || !this.disableGetMany) {
168
+ app.get(`${root}/:id`, this.json(this.getOrGetMany.bind(this)));
118
169
  }
119
170
  if (!this.disableUpdate) {
120
171
  app.put(`${root}/:id`, this.json(this.update.bind(this)));
121
172
  }
122
- if (!this.disableUpdateMany) {
123
- app.put(`${root}/many`, this.json(this.updateMany.bind(this)));
124
- }
125
173
  // DELETE /:id — branches to remove() or removeMany() based on comma presence
126
174
  if (!this.disableRemove || !this.disableRemoveMany) {
127
175
  app.delete(`${root}/:id`, this.json(this.removeOrRemoveMany.bind(this)));
@@ -130,8 +178,10 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
130
178
  // ─── Route handlers ─────────────────────────────────────────────────────────
131
179
  /**
132
180
  * GET /
133
- * Splits the query string into filter and pagination params, consistent
134
- * with the GraphQL list resolver argument shape.
181
+ *
182
+ * Splits the query string into filter (non-pagination keys) and params
183
+ * (pagination keys) via buildFilter() and buildParams(). Shape matches
184
+ * the GraphQL list resolver: core.list({ filter, params }).
135
185
  */
136
186
  async list(req) {
137
187
  const core = await this.resolveCore(req);
@@ -142,8 +192,9 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
142
192
  }
143
193
  /**
144
194
  * GET /:id
145
- * Routes to core.get() for a single id, or core.getMany() when the :id
146
- * param contains commas. Argument shape matches GraphQL resolver args.
195
+ *
196
+ * Routes to core.get({ id }) for a single id, or core.getMany({ ids })
197
+ * when the :id param contains comma-separated values.
147
198
  */
148
199
  async getOrGetMany(req) {
149
200
  const core = await this.resolveCore(req);
@@ -161,49 +212,59 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
161
212
  }
162
213
  /**
163
214
  * POST /
164
- * Body must be { params: {...} } — consistent with GraphQL mutation args.
215
+ *
216
+ * Body must be { params: {...} }.
217
+ * Consistent with GraphQL mutation: partyTicketTypeCreate(params: Input).
165
218
  */
166
219
  async create(req) {
167
220
  const core = await this.resolveCore(req);
168
- return core.create({ params: req.body.params });
221
+ return core.create({ params: req.body?.params });
169
222
  }
170
223
  /**
171
224
  * POST /many
172
- * Body must be { params: [{...}, ...] } or { params: {...} } for a single item.
225
+ *
226
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
227
+ * item which is auto-wrapped in an array.
173
228
  */
174
229
  async createMany(req) {
175
230
  const core = await this.resolveCore(req);
176
- const items = Array.isArray(req.body.params) ? req.body.params : [req.body.params];
231
+ const items = Array.isArray(req.body?.params) ? req.body.params : [req.body?.params];
177
232
  return core.createMany({ params: items });
178
233
  }
179
234
  /**
180
235
  * PUT /:id
181
- * Body must be { params: {...} }. The :id route param is parsed and merged
182
- * into the where object via buildWhere() — override buildWhere() to add
183
- * extra conditions while keeping the URL pattern.
236
+ *
237
+ * Body must be { params: {...} }. The :id route param is parsed into an
238
+ * array and passed to buildWhere() — override buildWhere() to add extra
239
+ * conditions beyond id while keeping the /:id URL pattern.
240
+ *
241
+ * Shape: core.update({ where: { id: [id] }, params: {...} })
184
242
  */
185
243
  async update(req) {
186
244
  const core = await this.resolveCore(req);
187
245
  const [, ids] = (0, parseIds_1.parseIds)(req.params.id);
188
246
  return core.update({
189
247
  where: this.buildWhere(req, ids),
190
- params: req.body.params,
248
+ params: req.body?.params,
191
249
  });
192
250
  }
193
251
  /**
194
252
  * PUT /many
195
- * Body must be { params: [{...}, ...] } or { params: {...} } for a single item.
253
+ *
254
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
255
+ * item which is auto-wrapped in an array.
196
256
  */
197
257
  async updateMany(req) {
198
258
  const core = await this.resolveCore(req);
199
- const items = Array.isArray(req.body.params) ? req.body.params : [req.body.params];
259
+ const items = Array.isArray(req.body?.params) ? req.body.params : [req.body?.params];
200
260
  return core.updateMany({ params: items });
201
261
  }
202
262
  /**
203
263
  * DELETE /:id
204
- * Routes to core.remove() for a single id, or core.removeMany() when the
205
- * :id param contains commas. where is built via buildWhere() — override
206
- * to add extra conditions while keeping the URL pattern.
264
+ *
265
+ * Routes to core.remove({ where }) for a single id, or
266
+ * core.removeMany({ where }) for comma-separated ids. where is built via
267
+ * buildWhere() — override to add extra conditions.
207
268
  */
208
269
  async removeOrRemoveMany(req) {
209
270
  const core = await this.resolveCore(req);
@@ -1,6 +1,42 @@
1
1
  import { BaseController } from './BaseController';
2
2
  import { BaseRestApiCrudControllerPropsInterface } from './interfaces';
3
+ /**
4
+ * BaseRestApiCrudController
5
+ *
6
+ * Provides a standard REST CRUD surface that maps HTTP requests to core
7
+ * method calls using the same argument shapes as GraphQL resolvers. This
8
+ * means a core written for GraphQL works identically over REST with no
9
+ * changes.
10
+ *
11
+ * ── Argument shapes ───────────────────────────────────────────────────────────
12
+ * list → core.list({ filter, params })
13
+ * get → core.get({ id })
14
+ * getMany → core.getMany({ ids })
15
+ * create → core.create({ params }) body: { params: {...} }
16
+ * createMany → core.createMany({ params }) body: { params: [{...}] }
17
+ * update → core.update({ where, params }) body: { params: {...} }
18
+ * updateMany → core.updateMany({ params }) body: { params: [{...}] }
19
+ * remove → core.remove({ where })
20
+ * removeMany → core.removeMany({ where })
21
+ *
22
+ * ── Extension points ──────────────────────────────────────────────────────────
23
+ * buildWhere(req, ids) — override to add extra where conditions beyond id
24
+ * buildFilter(req) — override to customise filter extraction from QS
25
+ * buildParams(req) — override to customise pagination extraction from QS
26
+ *
27
+ * ── Route registration ────────────────────────────────────────────────────────
28
+ * Each subclass declares its own `root` path (e.g. '/api/v1/party-ticket-types').
29
+ * app.ts calls controller.init({ app, root: controller.root }) so no
30
+ * root needs to be passed at instantiation time.
31
+ *
32
+ * ── Context resolution ────────────────────────────────────────────────────────
33
+ * `getContext` defaults to (req) => req.context, which is set by the
34
+ * createContext middleware in app.ts before any REST handler runs.
35
+ * Override via props only when a controller needs a different context source.
36
+ */
3
37
  declare class BaseRestApiCrudController extends BaseController {
38
+ /** Mount path for this controller, e.g. '/api/v1/party-ticket-types' */
39
+ root: string;
4
40
  protected coreToUse: string;
5
41
  protected getContext: (req: any) => Promise<any> | any;
6
42
  protected disableList: boolean;
@@ -12,81 +48,103 @@ declare class BaseRestApiCrudController extends BaseController {
12
48
  protected disableUpdateMany: boolean;
13
49
  protected disableRemove: boolean;
14
50
  protected disableRemoveMany: boolean;
15
- constructor(props: BaseRestApiCrudControllerPropsInterface);
51
+ constructor(props?: BaseRestApiCrudControllerPropsInterface);
16
52
  /**
17
53
  * Builds the `where` object for update and remove operations.
18
54
  *
19
- * Base implementation uses the ids parsed from the `:id` route param.
20
- * Override in a subclass to add extra conditions from the request body
21
- * or query string while keeping the URL pattern intact.
55
+ * Base implementation returns { id: ids } where ids is the array parsed
56
+ * from the `:id` route param (single or comma-separated).
22
57
  *
23
- * @param req - the Express request
24
- * @param ids - ids parsed from req.params.id (always an array)
58
+ * Override in a subclass to add extra conditions from req.body or
59
+ * req.query while keeping the /:id URL pattern intact. Example:
60
+ *
61
+ * protected buildWhere(req: any, ids: string[]): Record<string, any> {
62
+ * return { id: ids, statusId: req.body?.where?.statusId };
63
+ * }
25
64
  */
26
65
  protected buildWhere(req: any, ids: string[]): Record<string, any>;
27
66
  /**
28
- * Builds the `filter` object for list operations.
29
- *
30
- * Base implementation treats every query string key that is NOT in
31
- * PAGINATION_KEYS as a filter field. Override to apply custom filtering
32
- * logic or to parse typed values (e.g. booleans, arrays).
67
+ * Builds the `filter` object passed to core.list().
33
68
  *
34
- * @param req - the Express request
69
+ * Base implementation treats every query string key that is NOT a known
70
+ * pagination key as a filter field. Override to apply custom parsing
71
+ * (e.g. typed booleans, array values, renamed fields).
35
72
  */
36
73
  protected buildFilter(req: any): Record<string, any>;
37
74
  /**
38
- * Builds the `params` object for list operations (pagination / sorting).
75
+ * Builds the `params` object passed to core.list() (pagination / sorting).
39
76
  *
40
77
  * Base implementation picks only the known PAGINATION_KEYS from the query
41
- * string. Override to support additional pagination conventions.
42
- *
43
- * @param req - the Express request
78
+ * string. Override to support additional or renamed pagination conventions.
44
79
  */
45
80
  protected buildParams(req: any): Record<string, any>;
46
81
  protected resolveCore(req: any): Promise<any>;
82
+ /**
83
+ * Registers all enabled routes on the Express app under `root`.
84
+ * Called once at startup by app.ts:
85
+ *
86
+ * controller.init({ app, root: controller.root })
87
+ *
88
+ * Routes are only registered for operations that are not disabled.
89
+ * /many routes are registered before /:id to avoid Express matching
90
+ * "many" as an id param.
91
+ */
47
92
  init(props: {
48
93
  app: any;
49
94
  root: string;
50
95
  }): void;
51
96
  /**
52
97
  * GET /
53
- * Splits the query string into filter and pagination params, consistent
54
- * with the GraphQL list resolver argument shape.
98
+ *
99
+ * Splits the query string into filter (non-pagination keys) and params
100
+ * (pagination keys) via buildFilter() and buildParams(). Shape matches
101
+ * the GraphQL list resolver: core.list({ filter, params }).
55
102
  */
56
103
  protected list(req: any): Promise<any>;
57
104
  /**
58
105
  * GET /:id
59
- * Routes to core.get() for a single id, or core.getMany() when the :id
60
- * param contains commas. Argument shape matches GraphQL resolver args.
106
+ *
107
+ * Routes to core.get({ id }) for a single id, or core.getMany({ ids })
108
+ * when the :id param contains comma-separated values.
61
109
  */
62
110
  protected getOrGetMany(req: any): Promise<any>;
63
111
  /**
64
112
  * POST /
65
- * Body must be { params: {...} } — consistent with GraphQL mutation args.
113
+ *
114
+ * Body must be { params: {...} }.
115
+ * Consistent with GraphQL mutation: partyTicketTypeCreate(params: Input).
66
116
  */
67
117
  protected create(req: any): Promise<any>;
68
118
  /**
69
119
  * POST /many
70
- * Body must be { params: [{...}, ...] } or { params: {...} } for a single item.
120
+ *
121
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
122
+ * item which is auto-wrapped in an array.
71
123
  */
72
124
  protected createMany(req: any): Promise<any>;
73
125
  /**
74
126
  * PUT /:id
75
- * Body must be { params: {...} }. The :id route param is parsed and merged
76
- * into the where object via buildWhere() — override buildWhere() to add
77
- * extra conditions while keeping the URL pattern.
127
+ *
128
+ * Body must be { params: {...} }. The :id route param is parsed into an
129
+ * array and passed to buildWhere() — override buildWhere() to add extra
130
+ * conditions beyond id while keeping the /:id URL pattern.
131
+ *
132
+ * Shape: core.update({ where: { id: [id] }, params: {...} })
78
133
  */
79
134
  protected update(req: any): Promise<any>;
80
135
  /**
81
136
  * PUT /many
82
- * Body must be { params: [{...}, ...] } or { params: {...} } for a single item.
137
+ *
138
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
139
+ * item which is auto-wrapped in an array.
83
140
  */
84
141
  protected updateMany(req: any): Promise<any>;
85
142
  /**
86
143
  * DELETE /:id
87
- * Routes to core.remove() for a single id, or core.removeMany() when the
88
- * :id param contains commas. where is built via buildWhere() — override
89
- * to add extra conditions while keeping the URL pattern.
144
+ *
145
+ * Routes to core.remove({ where }) for a single id, or
146
+ * core.removeMany({ where }) for comma-separated ids. where is built via
147
+ * buildWhere() — override to add extra conditions.
90
148
  */
91
149
  protected removeOrRemoveMany(req: any): Promise<any>;
92
150
  }
@@ -6,7 +6,43 @@ import { parseIds } from './parseIds';
6
6
  * Everything else in the query string is treated as a filter field.
7
7
  */
8
8
  const PAGINATION_KEYS = new Set(['page', 'limit', 'offset', 'sortBy', 'sortDir', 'orderBy']);
9
+ /**
10
+ * BaseRestApiCrudController
11
+ *
12
+ * Provides a standard REST CRUD surface that maps HTTP requests to core
13
+ * method calls using the same argument shapes as GraphQL resolvers. This
14
+ * means a core written for GraphQL works identically over REST with no
15
+ * changes.
16
+ *
17
+ * ── Argument shapes ───────────────────────────────────────────────────────────
18
+ * list → core.list({ filter, params })
19
+ * get → core.get({ id })
20
+ * getMany → core.getMany({ ids })
21
+ * create → core.create({ params }) body: { params: {...} }
22
+ * createMany → core.createMany({ params }) body: { params: [{...}] }
23
+ * update → core.update({ where, params }) body: { params: {...} }
24
+ * updateMany → core.updateMany({ params }) body: { params: [{...}] }
25
+ * remove → core.remove({ where })
26
+ * removeMany → core.removeMany({ where })
27
+ *
28
+ * ── Extension points ──────────────────────────────────────────────────────────
29
+ * buildWhere(req, ids) — override to add extra where conditions beyond id
30
+ * buildFilter(req) — override to customise filter extraction from QS
31
+ * buildParams(req) — override to customise pagination extraction from QS
32
+ *
33
+ * ── Route registration ────────────────────────────────────────────────────────
34
+ * Each subclass declares its own `root` path (e.g. '/api/v1/party-ticket-types').
35
+ * app.ts calls controller.init({ app, root: controller.root }) so no
36
+ * root needs to be passed at instantiation time.
37
+ *
38
+ * ── Context resolution ────────────────────────────────────────────────────────
39
+ * `getContext` defaults to (req) => req.context, which is set by the
40
+ * createContext middleware in app.ts before any REST handler runs.
41
+ * Override via props only when a controller needs a different context source.
42
+ */
9
43
  class BaseRestApiCrudController extends BaseController {
44
+ /** Mount path for this controller, e.g. '/api/v1/party-ticket-types' */
45
+ root;
10
46
  coreToUse;
11
47
  getContext;
12
48
  disableList;
@@ -19,45 +55,47 @@ class BaseRestApiCrudController extends BaseController {
19
55
  disableRemove;
20
56
  disableRemoveMany;
21
57
  constructor(props) {
22
- super(props);
23
- const { prefix, core, getContext } = props || {};
24
- if (!getContext) {
25
- throw new Error('BaseRestApiCrudController: `getContext` is required');
26
- }
58
+ super(props ?? {});
59
+ const { prefix, core, getContext, root } = props || {};
60
+ this.root = root ?? '';
27
61
  this.coreToUse = core || `${prefix}Core`;
28
- this.getContext = getContext;
29
- this.disableList = props.disableList ?? false;
30
- this.disableGet = props.disableGet ?? false;
31
- this.disableGetMany = props.disableGetMany ?? false;
32
- this.disableCreate = props.disableCreate ?? false;
33
- this.disableCreateMany = props.disableCreateMany ?? false;
34
- this.disableUpdate = props.disableUpdate ?? false;
35
- this.disableUpdateMany = props.disableUpdateMany ?? false;
36
- this.disableRemove = props.disableRemove ?? false;
37
- this.disableRemoveMany = props.disableRemoveMany ?? false;
62
+ // Default: read the context that createContext middleware attached to req.
63
+ // Pass an explicit getContext in props only when a controller needs to
64
+ // resolve the context differently.
65
+ this.getContext = getContext ?? ((req) => req.context);
66
+ this.disableList = props?.disableList ?? false;
67
+ this.disableGet = props?.disableGet ?? false;
68
+ this.disableGetMany = props?.disableGetMany ?? false;
69
+ this.disableCreate = props?.disableCreate ?? false;
70
+ this.disableCreateMany = props?.disableCreateMany ?? false;
71
+ this.disableUpdate = props?.disableUpdate ?? false;
72
+ this.disableUpdateMany = props?.disableUpdateMany ?? false;
73
+ this.disableRemove = props?.disableRemove ?? false;
74
+ this.disableRemoveMany = props?.disableRemoveMany ?? false;
38
75
  }
39
76
  // ─── Extension points ───────────────────────────────────────────────────────
40
77
  /**
41
78
  * Builds the `where` object for update and remove operations.
42
79
  *
43
- * Base implementation uses the ids parsed from the `:id` route param.
44
- * Override in a subclass to add extra conditions from the request body
45
- * or query string while keeping the URL pattern intact.
80
+ * Base implementation returns { id: ids } where ids is the array parsed
81
+ * from the `:id` route param (single or comma-separated).
46
82
  *
47
- * @param req - the Express request
48
- * @param ids - ids parsed from req.params.id (always an array)
83
+ * Override in a subclass to add extra conditions from req.body or
84
+ * req.query while keeping the /:id URL pattern intact. Example:
85
+ *
86
+ * protected buildWhere(req: any, ids: string[]): Record<string, any> {
87
+ * return { id: ids, statusId: req.body?.where?.statusId };
88
+ * }
49
89
  */
50
90
  buildWhere(req, ids) {
51
91
  return { id: ids };
52
92
  }
53
93
  /**
54
- * Builds the `filter` object for list operations.
55
- *
56
- * Base implementation treats every query string key that is NOT in
57
- * PAGINATION_KEYS as a filter field. Override to apply custom filtering
58
- * logic or to parse typed values (e.g. booleans, arrays).
94
+ * Builds the `filter` object passed to core.list().
59
95
  *
60
- * @param req - the Express request
96
+ * Base implementation treats every query string key that is NOT a known
97
+ * pagination key as a filter field. Override to apply custom parsing
98
+ * (e.g. typed booleans, array values, renamed fields).
61
99
  */
62
100
  buildFilter(req) {
63
101
  const filter = {};
@@ -69,12 +107,10 @@ class BaseRestApiCrudController extends BaseController {
69
107
  return filter;
70
108
  }
71
109
  /**
72
- * Builds the `params` object for list operations (pagination / sorting).
110
+ * Builds the `params` object passed to core.list() (pagination / sorting).
73
111
  *
74
112
  * Base implementation picks only the known PAGINATION_KEYS from the query
75
- * string. Override to support additional pagination conventions.
76
- *
77
- * @param req - the Express request
113
+ * string. Override to support additional or renamed pagination conventions.
78
114
  */
79
115
  buildParams(req) {
80
116
  const params = {};
@@ -95,6 +131,16 @@ class BaseRestApiCrudController extends BaseController {
95
131
  return core;
96
132
  }
97
133
  // ─── Route registration ─────────────────────────────────────────────────────
134
+ /**
135
+ * Registers all enabled routes on the Express app under `root`.
136
+ * Called once at startup by app.ts:
137
+ *
138
+ * controller.init({ app, root: controller.root })
139
+ *
140
+ * Routes are only registered for operations that are not disabled.
141
+ * /many routes are registered before /:id to avoid Express matching
142
+ * "many" as an id param.
143
+ */
98
144
  init(props) {
99
145
  const { app, root } = props || {};
100
146
  if (!app || !root) {
@@ -103,22 +149,24 @@ class BaseRestApiCrudController extends BaseController {
103
149
  if (!this.disableList) {
104
150
  app.get(root, this.json(this.list.bind(this)));
105
151
  }
106
- // GET /:id — branches to get() or getMany() based on comma presence
107
- if (!this.disableGet || !this.disableGetMany) {
108
- app.get(`${root}/:id`, this.json(this.getOrGetMany.bind(this)));
152
+ // /many must be registered before /:id so Express does not treat the
153
+ // literal string "many" as an id param value.
154
+ if (!this.disableCreateMany) {
155
+ app.post(`${root}/many`, this.json(this.createMany.bind(this)));
156
+ }
157
+ if (!this.disableUpdateMany) {
158
+ app.put(`${root}/many`, this.json(this.updateMany.bind(this)));
109
159
  }
110
160
  if (!this.disableCreate) {
111
161
  app.post(root, this.json(this.create.bind(this)));
112
162
  }
113
- if (!this.disableCreateMany) {
114
- app.post(`${root}/many`, this.json(this.createMany.bind(this)));
163
+ // GET /:id — branches to get() or getMany() based on comma presence
164
+ if (!this.disableGet || !this.disableGetMany) {
165
+ app.get(`${root}/:id`, this.json(this.getOrGetMany.bind(this)));
115
166
  }
116
167
  if (!this.disableUpdate) {
117
168
  app.put(`${root}/:id`, this.json(this.update.bind(this)));
118
169
  }
119
- if (!this.disableUpdateMany) {
120
- app.put(`${root}/many`, this.json(this.updateMany.bind(this)));
121
- }
122
170
  // DELETE /:id — branches to remove() or removeMany() based on comma presence
123
171
  if (!this.disableRemove || !this.disableRemoveMany) {
124
172
  app.delete(`${root}/:id`, this.json(this.removeOrRemoveMany.bind(this)));
@@ -127,8 +175,10 @@ class BaseRestApiCrudController extends BaseController {
127
175
  // ─── Route handlers ─────────────────────────────────────────────────────────
128
176
  /**
129
177
  * GET /
130
- * Splits the query string into filter and pagination params, consistent
131
- * with the GraphQL list resolver argument shape.
178
+ *
179
+ * Splits the query string into filter (non-pagination keys) and params
180
+ * (pagination keys) via buildFilter() and buildParams(). Shape matches
181
+ * the GraphQL list resolver: core.list({ filter, params }).
132
182
  */
133
183
  async list(req) {
134
184
  const core = await this.resolveCore(req);
@@ -139,8 +189,9 @@ class BaseRestApiCrudController extends BaseController {
139
189
  }
140
190
  /**
141
191
  * GET /:id
142
- * Routes to core.get() for a single id, or core.getMany() when the :id
143
- * param contains commas. Argument shape matches GraphQL resolver args.
192
+ *
193
+ * Routes to core.get({ id }) for a single id, or core.getMany({ ids })
194
+ * when the :id param contains comma-separated values.
144
195
  */
145
196
  async getOrGetMany(req) {
146
197
  const core = await this.resolveCore(req);
@@ -158,49 +209,59 @@ class BaseRestApiCrudController extends BaseController {
158
209
  }
159
210
  /**
160
211
  * POST /
161
- * Body must be { params: {...} } — consistent with GraphQL mutation args.
212
+ *
213
+ * Body must be { params: {...} }.
214
+ * Consistent with GraphQL mutation: partyTicketTypeCreate(params: Input).
162
215
  */
163
216
  async create(req) {
164
217
  const core = await this.resolveCore(req);
165
- return core.create({ params: req.body.params });
218
+ return core.create({ params: req.body?.params });
166
219
  }
167
220
  /**
168
221
  * POST /many
169
- * Body must be { params: [{...}, ...] } or { params: {...} } for a single item.
222
+ *
223
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
224
+ * item which is auto-wrapped in an array.
170
225
  */
171
226
  async createMany(req) {
172
227
  const core = await this.resolveCore(req);
173
- const items = Array.isArray(req.body.params) ? req.body.params : [req.body.params];
228
+ const items = Array.isArray(req.body?.params) ? req.body.params : [req.body?.params];
174
229
  return core.createMany({ params: items });
175
230
  }
176
231
  /**
177
232
  * PUT /:id
178
- * Body must be { params: {...} }. The :id route param is parsed and merged
179
- * into the where object via buildWhere() — override buildWhere() to add
180
- * extra conditions while keeping the URL pattern.
233
+ *
234
+ * Body must be { params: {...} }. The :id route param is parsed into an
235
+ * array and passed to buildWhere() — override buildWhere() to add extra
236
+ * conditions beyond id while keeping the /:id URL pattern.
237
+ *
238
+ * Shape: core.update({ where: { id: [id] }, params: {...} })
181
239
  */
182
240
  async update(req) {
183
241
  const core = await this.resolveCore(req);
184
242
  const [, ids] = parseIds(req.params.id);
185
243
  return core.update({
186
244
  where: this.buildWhere(req, ids),
187
- params: req.body.params,
245
+ params: req.body?.params,
188
246
  });
189
247
  }
190
248
  /**
191
249
  * PUT /many
192
- * Body must be { params: [{...}, ...] } or { params: {...} } for a single item.
250
+ *
251
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
252
+ * item which is auto-wrapped in an array.
193
253
  */
194
254
  async updateMany(req) {
195
255
  const core = await this.resolveCore(req);
196
- const items = Array.isArray(req.body.params) ? req.body.params : [req.body.params];
256
+ const items = Array.isArray(req.body?.params) ? req.body.params : [req.body?.params];
197
257
  return core.updateMany({ params: items });
198
258
  }
199
259
  /**
200
260
  * DELETE /:id
201
- * Routes to core.remove() for a single id, or core.removeMany() when the
202
- * :id param contains commas. where is built via buildWhere() — override
203
- * to add extra conditions while keeping the URL pattern.
261
+ *
262
+ * Routes to core.remove({ where }) for a single id, or
263
+ * core.removeMany({ where }) for comma-separated ids. where is built via
264
+ * buildWhere() — override to add extra conditions.
204
265
  */
205
266
  async removeOrRemoveMany(req) {
206
267
  const core = await this.resolveCore(req);
@@ -1,4 +1,9 @@
1
1
  export interface BaseRestApiCrudControllerPropsInterface {
2
+ /**
3
+ * Mount path for this controller, e.g. '/api/v1/party-ticket-types'.
4
+ * Registered via controller.init({ app, root: controller.root }) in app.ts.
5
+ */
6
+ root?: string;
2
7
  /**
3
8
  * The prefix used to derive the core name, e.g. "user" → "userCore".
4
9
  * Ignored if `core` is provided explicitly.
@@ -11,9 +16,11 @@ export interface BaseRestApiCrudControllerPropsInterface {
11
16
  core?: string;
12
17
  /**
13
18
  * Factory that produces the ApiContext for a given request.
14
- * Required — controllers need context to reach cores.
19
+ * Defaults to (req) => req.context — which is set by the createContext
20
+ * middleware before any REST handler runs. Override only when a controller
21
+ * needs a different context source.
15
22
  */
16
- getContext: (req: any) => Promise<any> | any;
23
+ getContext?: (req: any) => Promise<any> | any;
17
24
  onResponse?: (req: any, res: any, next: any) => Promise<void> | void;
18
25
  logger?: any;
19
26
  disableList?: boolean;
@@ -1,4 +1,9 @@
1
1
  export interface BaseRestApiCrudControllerPropsInterface {
2
+ /**
3
+ * Mount path for this controller, e.g. '/api/v1/party-ticket-types'.
4
+ * Registered via controller.init({ app, root: controller.root }) in app.ts.
5
+ */
6
+ root?: string;
2
7
  /**
3
8
  * The prefix used to derive the core name, e.g. "user" → "userCore".
4
9
  * Ignored if `core` is provided explicitly.
@@ -11,9 +16,11 @@ export interface BaseRestApiCrudControllerPropsInterface {
11
16
  core?: string;
12
17
  /**
13
18
  * Factory that produces the ApiContext for a given request.
14
- * Required — controllers need context to reach cores.
19
+ * Defaults to (req) => req.context — which is set by the createContext
20
+ * middleware before any REST handler runs. Override only when a controller
21
+ * needs a different context source.
15
22
  */
16
- getContext: (req: any) => Promise<any> | any;
23
+ getContext?: (req: any) => Promise<any> | any;
17
24
  onResponse?: (req: any, res: any, next: any) => Promise<void> | void;
18
25
  logger?: any;
19
26
  disableList?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.129",
3
+ "version": "1.0.130",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "type": "commonjs",
6
6
  "exports": {