@sdflc/backend-helpers 1.0.128 → 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,25 +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);
52
+ /**
53
+ * Builds the `where` object for update and remove operations.
54
+ *
55
+ * Base implementation returns { id: ids } where ids is the array parsed
56
+ * from the `:id` route param (single or comma-separated).
57
+ *
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
+ * }
64
+ */
65
+ protected buildWhere(req: any, ids: string[]): Record<string, any>;
66
+ /**
67
+ * Builds the `filter` object passed to core.list().
68
+ *
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).
72
+ */
73
+ protected buildFilter(req: any): Record<string, any>;
74
+ /**
75
+ * Builds the `params` object passed to core.list() (pagination / sorting).
76
+ *
77
+ * Base implementation picks only the known PAGINATION_KEYS from the query
78
+ * string. Override to support additional or renamed pagination conventions.
79
+ */
80
+ protected buildParams(req: any): Record<string, any>;
16
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
+ */
17
92
  init(props: {
18
93
  app: any;
19
94
  root: string;
20
95
  }): void;
96
+ /**
97
+ * GET /
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 }).
102
+ */
21
103
  protected list(req: any): Promise<any>;
22
104
  /**
23
- * Handles GET /:id — routes to core.get() for a single id,
24
- * or core.getMany() when the :id param contains commas.
105
+ * GET /:id
106
+ *
107
+ * Routes to core.get({ id }) for a single id, or core.getMany({ ids })
108
+ * when the :id param contains comma-separated values.
25
109
  */
26
110
  protected getOrGetMany(req: any): Promise<any>;
111
+ /**
112
+ * POST /
113
+ *
114
+ * Body must be { params: {...} }.
115
+ * Consistent with GraphQL mutation: partyTicketTypeCreate(params: Input).
116
+ */
27
117
  protected create(req: any): Promise<any>;
118
+ /**
119
+ * POST /many
120
+ *
121
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
122
+ * item which is auto-wrapped in an array.
123
+ */
28
124
  protected createMany(req: any): Promise<any>;
125
+ /**
126
+ * PUT /:id
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: {...} })
133
+ */
29
134
  protected update(req: any): Promise<any>;
135
+ /**
136
+ * PUT /many
137
+ *
138
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
139
+ * item which is auto-wrapped in an array.
140
+ */
30
141
  protected updateMany(req: any): Promise<any>;
31
142
  /**
32
- * Handles DELETE /:id — routes to core.remove() for a single id,
33
- * or core.removeMany() when the :id param contains commas.
143
+ * DELETE /:id
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.
34
148
  */
35
149
  protected removeOrRemoveMany(req: any): Promise<any>;
36
150
  }
@@ -4,7 +4,48 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.BaseRestApiCrudController = void 0;
5
5
  const BaseController_1 = require("./BaseController");
6
6
  const parseIds_1 = require("./parseIds");
7
+ /**
8
+ * Pagination / sorting keys that are always routed to `params` in list().
9
+ * Everything else in the query string is treated as a filter field.
10
+ */
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
+ */
7
46
  class BaseRestApiCrudController extends BaseController_1.BaseController {
47
+ /** Mount path for this controller, e.g. '/api/v1/party-ticket-types' */
48
+ root;
8
49
  coreToUse;
9
50
  getContext;
10
51
  disableList;
@@ -17,23 +58,73 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
17
58
  disableRemove;
18
59
  disableRemoveMany;
19
60
  constructor(props) {
20
- super(props);
21
- const { prefix, core, getContext } = props || {};
22
- if (!getContext) {
23
- throw new Error('BaseRestApiCrudController: `getContext` is required');
24
- }
61
+ super(props ?? {});
62
+ const { prefix, core, getContext, root } = props || {};
63
+ this.root = root ?? '';
25
64
  this.coreToUse = core || `${prefix}Core`;
26
- this.getContext = getContext;
27
- this.disableList = props.disableList ?? false;
28
- this.disableGet = props.disableGet ?? false;
29
- this.disableGetMany = props.disableGetMany ?? false;
30
- this.disableCreate = props.disableCreate ?? false;
31
- this.disableCreateMany = props.disableCreateMany ?? false;
32
- this.disableUpdate = props.disableUpdate ?? false;
33
- this.disableUpdateMany = props.disableUpdateMany ?? false;
34
- this.disableRemove = props.disableRemove ?? false;
35
- 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;
78
+ }
79
+ // ─── Extension points ───────────────────────────────────────────────────────
80
+ /**
81
+ * Builds the `where` object for update and remove operations.
82
+ *
83
+ * Base implementation returns { id: ids } where ids is the array parsed
84
+ * from the `:id` route param (single or comma-separated).
85
+ *
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
+ * }
92
+ */
93
+ buildWhere(req, ids) {
94
+ return { id: ids };
36
95
  }
96
+ /**
97
+ * Builds the `filter` object passed to core.list().
98
+ *
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).
102
+ */
103
+ buildFilter(req) {
104
+ const filter = {};
105
+ for (const [key, value] of Object.entries(req.query ?? {})) {
106
+ if (!PAGINATION_KEYS.has(key)) {
107
+ filter[key] = value;
108
+ }
109
+ }
110
+ return filter;
111
+ }
112
+ /**
113
+ * Builds the `params` object passed to core.list() (pagination / sorting).
114
+ *
115
+ * Base implementation picks only the known PAGINATION_KEYS from the query
116
+ * string. Override to support additional or renamed pagination conventions.
117
+ */
118
+ buildParams(req) {
119
+ const params = {};
120
+ for (const [key, value] of Object.entries(req.query ?? {})) {
121
+ if (PAGINATION_KEYS.has(key)) {
122
+ params[key] = value;
123
+ }
124
+ }
125
+ return params;
126
+ }
127
+ // ─── Core resolution ────────────────────────────────────────────────────────
37
128
  async resolveCore(req) {
38
129
  const context = await this.getContext(req);
39
130
  const core = context?.cores?.[this.coreToUse];
@@ -42,6 +133,17 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
42
133
  }
43
134
  return core;
44
135
  }
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
+ */
45
147
  init(props) {
46
148
  const { app, root } = props || {};
47
149
  if (!app || !root) {
@@ -50,35 +152,49 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
50
152
  if (!this.disableList) {
51
153
  app.get(root, this.json(this.list.bind(this)));
52
154
  }
53
- // GET /:id — branches to get() or getMany() based on comma presence
54
- if (!this.disableGet || !this.disableGetMany) {
55
- 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)));
56
162
  }
57
163
  if (!this.disableCreate) {
58
164
  app.post(root, this.json(this.create.bind(this)));
59
165
  }
60
- if (!this.disableCreateMany) {
61
- 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)));
62
169
  }
63
170
  if (!this.disableUpdate) {
64
171
  app.put(`${root}/:id`, this.json(this.update.bind(this)));
65
172
  }
66
- if (!this.disableUpdateMany) {
67
- app.put(`${root}/many`, this.json(this.updateMany.bind(this)));
68
- }
69
173
  // DELETE /:id — branches to remove() or removeMany() based on comma presence
70
174
  if (!this.disableRemove || !this.disableRemoveMany) {
71
175
  app.delete(`${root}/:id`, this.json(this.removeOrRemoveMany.bind(this)));
72
176
  }
73
177
  }
74
- // ─── Route handlers ────────────────────────────────────────────────────────
178
+ // ─── Route handlers ─────────────────────────────────────────────────────────
179
+ /**
180
+ * GET /
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 }).
185
+ */
75
186
  async list(req) {
76
187
  const core = await this.resolveCore(req);
77
- return core.list({ params: req.query });
188
+ return core.list({
189
+ filter: this.buildFilter(req),
190
+ params: this.buildParams(req),
191
+ });
78
192
  }
79
193
  /**
80
- * Handles GET /:id — routes to core.get() for a single id,
81
- * or core.getMany() when the :id param contains commas.
194
+ * GET /:id
195
+ *
196
+ * Routes to core.get({ id }) for a single id, or core.getMany({ ids })
197
+ * when the :id param contains comma-separated values.
82
198
  */
83
199
  async getOrGetMany(req) {
84
200
  const core = await this.resolveCore(req);
@@ -87,34 +203,68 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
87
203
  if (this.disableGet) {
88
204
  throw new Error(`GET by single id is disabled on this resource`);
89
205
  }
90
- return core.get({ params: { ...req.query, id: ids[0] } });
206
+ return core.get({ id: ids[0] });
91
207
  }
92
208
  if (this.disableGetMany) {
93
209
  throw new Error(`GET by multiple ids is disabled on this resource`);
94
210
  }
95
- return core.getMany({ params: { ...req.query, ids } });
211
+ return core.getMany({ ids });
96
212
  }
213
+ /**
214
+ * POST /
215
+ *
216
+ * Body must be { params: {...} }.
217
+ * Consistent with GraphQL mutation: partyTicketTypeCreate(params: Input).
218
+ */
97
219
  async create(req) {
98
220
  const core = await this.resolveCore(req);
99
- return core.create({ params: req.body });
221
+ return core.create({ params: req.body?.params });
100
222
  }
223
+ /**
224
+ * POST /many
225
+ *
226
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
227
+ * item which is auto-wrapped in an array.
228
+ */
101
229
  async createMany(req) {
102
230
  const core = await this.resolveCore(req);
103
- const items = Array.isArray(req.body) ? req.body : [req.body];
231
+ const items = Array.isArray(req.body?.params) ? req.body.params : [req.body?.params];
104
232
  return core.createMany({ params: items });
105
233
  }
234
+ /**
235
+ * PUT /:id
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: {...} })
242
+ */
106
243
  async update(req) {
107
244
  const core = await this.resolveCore(req);
108
- return core.update({ params: { ...req.body, id: req.params.id } });
245
+ const [, ids] = (0, parseIds_1.parseIds)(req.params.id);
246
+ return core.update({
247
+ where: this.buildWhere(req, ids),
248
+ params: req.body?.params,
249
+ });
109
250
  }
251
+ /**
252
+ * PUT /many
253
+ *
254
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
255
+ * item which is auto-wrapped in an array.
256
+ */
110
257
  async updateMany(req) {
111
258
  const core = await this.resolveCore(req);
112
- const items = Array.isArray(req.body) ? req.body : [req.body];
259
+ const items = Array.isArray(req.body?.params) ? req.body.params : [req.body?.params];
113
260
  return core.updateMany({ params: items });
114
261
  }
115
262
  /**
116
- * Handles DELETE /:id — routes to core.remove() for a single id,
117
- * or core.removeMany() when the :id param contains commas.
263
+ * DELETE /:id
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.
118
268
  */
119
269
  async removeOrRemoveMany(req) {
120
270
  const core = await this.resolveCore(req);
@@ -123,12 +273,12 @@ class BaseRestApiCrudController extends BaseController_1.BaseController {
123
273
  if (this.disableRemove) {
124
274
  throw new Error(`DELETE by single id is disabled on this resource`);
125
275
  }
126
- return core.remove({ params: { id: ids[0] } });
276
+ return core.remove({ where: this.buildWhere(req, ids) });
127
277
  }
128
278
  if (this.disableRemoveMany) {
129
279
  throw new Error(`DELETE by multiple ids is disabled on this resource`);
130
280
  }
131
- return core.removeMany({ params: { ids } });
281
+ return core.removeMany({ where: this.buildWhere(req, ids) });
132
282
  }
133
283
  }
134
284
  exports.BaseRestApiCrudController = BaseRestApiCrudController;
@@ -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,25 +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);
52
+ /**
53
+ * Builds the `where` object for update and remove operations.
54
+ *
55
+ * Base implementation returns { id: ids } where ids is the array parsed
56
+ * from the `:id` route param (single or comma-separated).
57
+ *
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
+ * }
64
+ */
65
+ protected buildWhere(req: any, ids: string[]): Record<string, any>;
66
+ /**
67
+ * Builds the `filter` object passed to core.list().
68
+ *
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).
72
+ */
73
+ protected buildFilter(req: any): Record<string, any>;
74
+ /**
75
+ * Builds the `params` object passed to core.list() (pagination / sorting).
76
+ *
77
+ * Base implementation picks only the known PAGINATION_KEYS from the query
78
+ * string. Override to support additional or renamed pagination conventions.
79
+ */
80
+ protected buildParams(req: any): Record<string, any>;
16
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
+ */
17
92
  init(props: {
18
93
  app: any;
19
94
  root: string;
20
95
  }): void;
96
+ /**
97
+ * GET /
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 }).
102
+ */
21
103
  protected list(req: any): Promise<any>;
22
104
  /**
23
- * Handles GET /:id — routes to core.get() for a single id,
24
- * or core.getMany() when the :id param contains commas.
105
+ * GET /:id
106
+ *
107
+ * Routes to core.get({ id }) for a single id, or core.getMany({ ids })
108
+ * when the :id param contains comma-separated values.
25
109
  */
26
110
  protected getOrGetMany(req: any): Promise<any>;
111
+ /**
112
+ * POST /
113
+ *
114
+ * Body must be { params: {...} }.
115
+ * Consistent with GraphQL mutation: partyTicketTypeCreate(params: Input).
116
+ */
27
117
  protected create(req: any): Promise<any>;
118
+ /**
119
+ * POST /many
120
+ *
121
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
122
+ * item which is auto-wrapped in an array.
123
+ */
28
124
  protected createMany(req: any): Promise<any>;
125
+ /**
126
+ * PUT /:id
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: {...} })
133
+ */
29
134
  protected update(req: any): Promise<any>;
135
+ /**
136
+ * PUT /many
137
+ *
138
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
139
+ * item which is auto-wrapped in an array.
140
+ */
30
141
  protected updateMany(req: any): Promise<any>;
31
142
  /**
32
- * Handles DELETE /:id — routes to core.remove() for a single id,
33
- * or core.removeMany() when the :id param contains commas.
143
+ * DELETE /:id
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.
34
148
  */
35
149
  protected removeOrRemoveMany(req: any): Promise<any>;
36
150
  }
@@ -1,7 +1,48 @@
1
1
  // ./src/baseRestApiCrudController.ts
2
2
  import { BaseController } from './BaseController';
3
3
  import { parseIds } from './parseIds';
4
+ /**
5
+ * Pagination / sorting keys that are always routed to `params` in list().
6
+ * Everything else in the query string is treated as a filter field.
7
+ */
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
+ */
4
43
  class BaseRestApiCrudController extends BaseController {
44
+ /** Mount path for this controller, e.g. '/api/v1/party-ticket-types' */
45
+ root;
5
46
  coreToUse;
6
47
  getContext;
7
48
  disableList;
@@ -14,23 +55,73 @@ class BaseRestApiCrudController extends BaseController {
14
55
  disableRemove;
15
56
  disableRemoveMany;
16
57
  constructor(props) {
17
- super(props);
18
- const { prefix, core, getContext } = props || {};
19
- if (!getContext) {
20
- throw new Error('BaseRestApiCrudController: `getContext` is required');
21
- }
58
+ super(props ?? {});
59
+ const { prefix, core, getContext, root } = props || {};
60
+ this.root = root ?? '';
22
61
  this.coreToUse = core || `${prefix}Core`;
23
- this.getContext = getContext;
24
- this.disableList = props.disableList ?? false;
25
- this.disableGet = props.disableGet ?? false;
26
- this.disableGetMany = props.disableGetMany ?? false;
27
- this.disableCreate = props.disableCreate ?? false;
28
- this.disableCreateMany = props.disableCreateMany ?? false;
29
- this.disableUpdate = props.disableUpdate ?? false;
30
- this.disableUpdateMany = props.disableUpdateMany ?? false;
31
- this.disableRemove = props.disableRemove ?? false;
32
- 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;
75
+ }
76
+ // ─── Extension points ───────────────────────────────────────────────────────
77
+ /**
78
+ * Builds the `where` object for update and remove operations.
79
+ *
80
+ * Base implementation returns { id: ids } where ids is the array parsed
81
+ * from the `:id` route param (single or comma-separated).
82
+ *
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
+ * }
89
+ */
90
+ buildWhere(req, ids) {
91
+ return { id: ids };
33
92
  }
93
+ /**
94
+ * Builds the `filter` object passed to core.list().
95
+ *
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).
99
+ */
100
+ buildFilter(req) {
101
+ const filter = {};
102
+ for (const [key, value] of Object.entries(req.query ?? {})) {
103
+ if (!PAGINATION_KEYS.has(key)) {
104
+ filter[key] = value;
105
+ }
106
+ }
107
+ return filter;
108
+ }
109
+ /**
110
+ * Builds the `params` object passed to core.list() (pagination / sorting).
111
+ *
112
+ * Base implementation picks only the known PAGINATION_KEYS from the query
113
+ * string. Override to support additional or renamed pagination conventions.
114
+ */
115
+ buildParams(req) {
116
+ const params = {};
117
+ for (const [key, value] of Object.entries(req.query ?? {})) {
118
+ if (PAGINATION_KEYS.has(key)) {
119
+ params[key] = value;
120
+ }
121
+ }
122
+ return params;
123
+ }
124
+ // ─── Core resolution ────────────────────────────────────────────────────────
34
125
  async resolveCore(req) {
35
126
  const context = await this.getContext(req);
36
127
  const core = context?.cores?.[this.coreToUse];
@@ -39,6 +130,17 @@ class BaseRestApiCrudController extends BaseController {
39
130
  }
40
131
  return core;
41
132
  }
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
+ */
42
144
  init(props) {
43
145
  const { app, root } = props || {};
44
146
  if (!app || !root) {
@@ -47,35 +149,49 @@ class BaseRestApiCrudController extends BaseController {
47
149
  if (!this.disableList) {
48
150
  app.get(root, this.json(this.list.bind(this)));
49
151
  }
50
- // GET /:id — branches to get() or getMany() based on comma presence
51
- if (!this.disableGet || !this.disableGetMany) {
52
- 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)));
53
159
  }
54
160
  if (!this.disableCreate) {
55
161
  app.post(root, this.json(this.create.bind(this)));
56
162
  }
57
- if (!this.disableCreateMany) {
58
- 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)));
59
166
  }
60
167
  if (!this.disableUpdate) {
61
168
  app.put(`${root}/:id`, this.json(this.update.bind(this)));
62
169
  }
63
- if (!this.disableUpdateMany) {
64
- app.put(`${root}/many`, this.json(this.updateMany.bind(this)));
65
- }
66
170
  // DELETE /:id — branches to remove() or removeMany() based on comma presence
67
171
  if (!this.disableRemove || !this.disableRemoveMany) {
68
172
  app.delete(`${root}/:id`, this.json(this.removeOrRemoveMany.bind(this)));
69
173
  }
70
174
  }
71
- // ─── Route handlers ────────────────────────────────────────────────────────
175
+ // ─── Route handlers ─────────────────────────────────────────────────────────
176
+ /**
177
+ * GET /
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 }).
182
+ */
72
183
  async list(req) {
73
184
  const core = await this.resolveCore(req);
74
- return core.list({ params: req.query });
185
+ return core.list({
186
+ filter: this.buildFilter(req),
187
+ params: this.buildParams(req),
188
+ });
75
189
  }
76
190
  /**
77
- * Handles GET /:id — routes to core.get() for a single id,
78
- * or core.getMany() when the :id param contains commas.
191
+ * GET /:id
192
+ *
193
+ * Routes to core.get({ id }) for a single id, or core.getMany({ ids })
194
+ * when the :id param contains comma-separated values.
79
195
  */
80
196
  async getOrGetMany(req) {
81
197
  const core = await this.resolveCore(req);
@@ -84,34 +200,68 @@ class BaseRestApiCrudController extends BaseController {
84
200
  if (this.disableGet) {
85
201
  throw new Error(`GET by single id is disabled on this resource`);
86
202
  }
87
- return core.get({ params: { ...req.query, id: ids[0] } });
203
+ return core.get({ id: ids[0] });
88
204
  }
89
205
  if (this.disableGetMany) {
90
206
  throw new Error(`GET by multiple ids is disabled on this resource`);
91
207
  }
92
- return core.getMany({ params: { ...req.query, ids } });
208
+ return core.getMany({ ids });
93
209
  }
210
+ /**
211
+ * POST /
212
+ *
213
+ * Body must be { params: {...} }.
214
+ * Consistent with GraphQL mutation: partyTicketTypeCreate(params: Input).
215
+ */
94
216
  async create(req) {
95
217
  const core = await this.resolveCore(req);
96
- return core.create({ params: req.body });
218
+ return core.create({ params: req.body?.params });
97
219
  }
220
+ /**
221
+ * POST /many
222
+ *
223
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
224
+ * item which is auto-wrapped in an array.
225
+ */
98
226
  async createMany(req) {
99
227
  const core = await this.resolveCore(req);
100
- const items = Array.isArray(req.body) ? req.body : [req.body];
228
+ const items = Array.isArray(req.body?.params) ? req.body.params : [req.body?.params];
101
229
  return core.createMany({ params: items });
102
230
  }
231
+ /**
232
+ * PUT /:id
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: {...} })
239
+ */
103
240
  async update(req) {
104
241
  const core = await this.resolveCore(req);
105
- return core.update({ params: { ...req.body, id: req.params.id } });
242
+ const [, ids] = parseIds(req.params.id);
243
+ return core.update({
244
+ where: this.buildWhere(req, ids),
245
+ params: req.body?.params,
246
+ });
106
247
  }
248
+ /**
249
+ * PUT /many
250
+ *
251
+ * Body must be { params: [{...}, ...] } or { params: {...} } for a single
252
+ * item which is auto-wrapped in an array.
253
+ */
107
254
  async updateMany(req) {
108
255
  const core = await this.resolveCore(req);
109
- const items = Array.isArray(req.body) ? req.body : [req.body];
256
+ const items = Array.isArray(req.body?.params) ? req.body.params : [req.body?.params];
110
257
  return core.updateMany({ params: items });
111
258
  }
112
259
  /**
113
- * Handles DELETE /:id — routes to core.remove() for a single id,
114
- * or core.removeMany() when the :id param contains commas.
260
+ * DELETE /:id
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.
115
265
  */
116
266
  async removeOrRemoveMany(req) {
117
267
  const core = await this.resolveCore(req);
@@ -120,12 +270,12 @@ class BaseRestApiCrudController extends BaseController {
120
270
  if (this.disableRemove) {
121
271
  throw new Error(`DELETE by single id is disabled on this resource`);
122
272
  }
123
- return core.remove({ params: { id: ids[0] } });
273
+ return core.remove({ where: this.buildWhere(req, ids) });
124
274
  }
125
275
  if (this.disableRemoveMany) {
126
276
  throw new Error(`DELETE by multiple ids is disabled on this resource`);
127
277
  }
128
- return core.removeMany({ params: { ids } });
278
+ return core.removeMany({ where: this.buildWhere(req, ids) });
129
279
  }
130
280
  }
131
281
  export { BaseRestApiCrudController };
@@ -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.128",
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": {