waibu-rest-api 2.12.0 → 2.14.0

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.
package/index.js CHANGED
@@ -1,99 +1,61 @@
1
- import docSchemaDescription from './lib/doc-schema/description.js'
2
- import docSchemaForFind from './lib/doc-schema/for-find.js'
3
- import docSchemaGeneral from './lib/doc-schema/general.js'
4
- import docSchemaLib from './lib/doc-schema/lib.js'
5
- import docSchemaModel from './lib/doc-schema/model.js'
6
- import docSchemaParams from './lib/doc-schema/params.js'
7
- import docSchemaQs from './lib/doc-schema/qs.js'
1
+ import path from 'path'
2
+ import config from './lib/config.js'
3
+ import {
4
+ handleResponseXml, extractHeaders, buildPropsReqsForSchema, buildResponseForSchema
5
+ } from './lib/helper.js'
8
6
 
9
7
  /**
10
- * Plugin factory
8
+ * Plugin factory.
9
+ *
10
+ * **Never** call this function directly!!! It's only-meant to be called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin initialization.
11
11
  *
12
12
  * @param {string} pkgName - NPM package name
13
- * @returns {class}
13
+ * @returns {WaibuRestApi} WaibuRestApi class
14
14
  */
15
15
  async function factory (pkgName) {
16
16
  const me = this
17
+ const { defaultsDeep } = this.app.lib.aneka
18
+ const { importModule, runHook } = this.app.bajo
19
+ const { getPluginPrefix } = this.app.waibu
20
+ const { methodMap, getParams } = this.app.waibuDb
21
+ const { pick, isFunction, merge, cloneDeep, each, get } = this.app.lib._
17
22
 
18
23
  /**
19
- * WaibuRestApi class
24
+ * WaibuRestApi class defniton. This class is used to create a REST API services for Waibu.
20
25
  *
21
26
  * @class
22
27
  */
23
28
  class WaibuRestApi extends this.app.baseClass.Base {
29
+ /**
30
+ * Constructor
31
+ */
24
32
  constructor () {
25
33
  super(pkgName, me.app)
26
34
  this.routePathHandlers = ['restapi']
27
- this.config = {
28
- waibu: {
29
- prefix: 'api'
30
- },
31
- mountMainAsRoot: true,
32
- exposeHead: true,
33
- enablePatch: false,
34
- bodyLimit: 1048576,
35
- intl: {
36
- detectors: ['qs', 'header']
37
- },
38
- format: {
39
- supported: ['json', 'xml'],
40
- asExt: false,
41
- xml: {
42
- bodyParser: {
43
- contentTypes: ['text/xml', 'application/xml', 'application/rss+xml'],
44
- validate: false
45
- },
46
- response: {
47
- wrapper: 'doc',
48
- declaration: true,
49
- valueAsAttributes: true
50
- }
51
- }
52
- },
53
- responseKey: {
54
- data: 'data',
55
- oldData: 'oldData',
56
- page: 'page',
57
- count: 'count',
58
- pages: 'pages',
59
- success: 'success',
60
- statusCode: 'code',
61
- error: 'error',
62
- cached: 'cached',
63
- hardCapped: 'hardCapped',
64
- message: 'message',
65
- warnings: 'warnings',
66
- details: 'details'
67
- },
68
- mapSlash: '~',
69
- mapDot: ',',
70
- multipart: {
71
- },
72
- cors: {},
73
- helmet: {},
74
- compress: false,
75
- rateLimit: false,
76
- disabled: [],
77
- rerouted: {}
78
- }
79
-
80
- this.selfBind([
81
- 'docSchemaDescription',
82
- 'docSchemaForFind',
83
- 'docSchemaGeneral',
84
- 'docSchemaLib',
85
- 'docSchemaModel',
86
- 'docSchemaParams',
87
- 'docSchemaQs'
88
- ])
35
+ this.config = config
89
36
  }
90
37
 
38
+ /**
39
+ * Initialize the plugin.
40
+ *
41
+ * @async
42
+ * @method
43
+ */
91
44
  init = async () => {
92
45
  const { uniq } = this.app.lib._
93
46
  this.config.format.supported.push('json')
94
47
  this.config.format.supported = uniq(this.config.format.supported)
95
48
  }
96
49
 
50
+ /**
51
+ * Generate the route path for a given name.
52
+ *
53
+ * @param {string} name - The name of the route
54
+ * @param {Object} [options={}] - Options for route path generation
55
+ * @param {string|boolean} [options.defFormat='.json'] - Default format for the route
56
+ * @param {boolean} [options.uriEncoded=true] - Whether to URI encode the path
57
+ * @returns {string} The generated route path
58
+ */
97
59
  routePath = (name, { defFormat = '.json', uriEncoded = true } = {}) => {
98
60
  const { get, trimStart } = this.app.lib._
99
61
  const { fullPath, ns } = this.app.bajo.breakNsPath(name)
@@ -104,6 +66,16 @@ async function factory (pkgName) {
104
66
  return '/' + trimStart(path, '/')
105
67
  }
106
68
 
69
+ /**
70
+ * Transform the result before sending the response.
71
+ *
72
+ * @param {Object} param0 - The parameters for transforming the result
73
+ * @param {Object} param0.data - The data to be transformed
74
+ * @param {Object} param0.req - The request object
75
+ * @param {Object} param0.reply - The reply object
76
+ * @param {Object} [param0.options={}] - Additional options for transformation
77
+ * @returns {Object} The transformed result
78
+ */
107
79
  transformResult = ({ data, req, reply, options = {} }) => {
108
80
  const reformat = ({ data, req, reply, options = {} }) => {
109
81
  const { forOwn, get } = this.app.lib._
@@ -163,13 +135,530 @@ async function factory (pkgName) {
163
135
  return returnSuccess({ data, req, reply, options })
164
136
  }
165
137
 
166
- docSchemaDescription = docSchemaDescription
167
- docSchemaForFind = docSchemaForFind
168
- docSchemaGeneral = docSchemaGeneral
169
- docSchemaLib = docSchemaLib
170
- docSchemaModel = docSchemaModel
171
- docSchemaParams = docSchemaParams
172
- docSchemaQs = docSchemaQs
138
+ /**
139
+ * Generate the schema description for a given method.
140
+ *
141
+ * @method
142
+ * @param {string} method - The method name
143
+ * @returns {string} The schema description
144
+ */
145
+ docSchemaDescription = (method) => {
146
+ const desc = {
147
+ create: 'postRecordWithBody',
148
+ find: 'findRecordsWithFilter',
149
+ get: 'getRecordById',
150
+ update: 'updateRecordByIdWithBody',
151
+ remove: 'removeRecordById'
152
+ }
153
+ return this.t(desc[method])
154
+ }
155
+
156
+ /**
157
+ * Generate the schema for the "find" operation.
158
+ *
159
+ * @async
160
+ * @method
161
+ * @param {Object} items - The items schema
162
+ * @returns {Object} The schema for the "find" operation
163
+ */
164
+ docSchemaForFind = async (items) => {
165
+ return {
166
+ data: {
167
+ type: 'array',
168
+ items
169
+ },
170
+ limit: { type: 'integer' },
171
+ page: { type: 'integer' },
172
+ pages: { type: 'integer' },
173
+ count: { type: 'integer' },
174
+ success: { type: 'boolean', default: true },
175
+ statusCode: { type: 'integer', default: 200 },
176
+ warnings: { type: 'array' }
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Generate the general schema for the API responses.
182
+ *
183
+ * @async
184
+ * @method
185
+ * @returns {Object} The general schema for API responses
186
+ */
187
+ docSchemaGeneral = async () => {
188
+ const cfg = this.config
189
+ const cfgWdb = this.app.waibuDb.config
190
+ const def = {
191
+ type: 'object',
192
+ properties: {
193
+ error: { type: 'string' },
194
+ message: { type: 'string' }
195
+ }
196
+ }
197
+ for (const type of ['4xx', '5xx']) {
198
+ const item = cloneDeep(def)
199
+ if (type === '4xx') {
200
+ merge(item, {
201
+ properties: {
202
+ details: {
203
+ type: 'array',
204
+ items: {
205
+ type: 'object',
206
+ properties: {
207
+ field: { type: 'string' },
208
+ error: { type: 'string' }
209
+ }
210
+ }
211
+ },
212
+ success: { type: 'boolean', default: false },
213
+ statusCode: { type: 'integer', default: 400 }
214
+ }
215
+ })
216
+ } else {
217
+ merge(item, {
218
+ properties: {
219
+ success: { type: 'boolean', default: false },
220
+ statusCode: { type: 'integer', default: 500 }
221
+ }
222
+ })
223
+ }
224
+ if (cfgWdb.dbModel.dataOnly) item.properties = { error: item.properties.message }
225
+ const props = {}
226
+ each(item.properties, (v, k) => {
227
+ const key = get(cfg, `responseKey.${k}`, k)
228
+ props[key] = item.properties[k]
229
+ })
230
+ item.properties = props
231
+ await this.docSchemaLib(type + 'Resp', item)
232
+ }
233
+ await this.docSchemaParams('qsFilter',
234
+ 'query||NQL/Mongo Query. Leave empty to disable query',
235
+ 'limit|integer|Number of records per page. Must be >= 1|' + this.app.dobo.config.default.filter.limit,
236
+ 'page|integer|Desired page number. Must be >= 1|1',
237
+ 'sort||Order of records, format: <field>:<dir>[,<field>:<dir>,[...]]',
238
+ 'fields||Comma delimited fields to show. Leave empty to show all fields',
239
+ true
240
+ )
241
+ await this.docSchemaParams('paramsId', 'id||Record ID')
242
+ await this.docSchemaParams('qsFields',
243
+ 'fields||Comma delimited fields to show. Leave empty to show all fields',
244
+ true
245
+ )
246
+ }
247
+
248
+ /**
249
+ * Add a schema to the library.
250
+ *
251
+ * @async
252
+ * @method
253
+ * @param {string} name - The name of the schema
254
+ * @param {Object} obj - The schema object
255
+ */
256
+ docSchemaLib = async (name, obj) => {
257
+ const { merge } = this.app.lib._
258
+ if (this.webAppCtx.getSchema(name)) return
259
+ const value = merge({}, obj, { $id: name })
260
+ this.webAppCtx.addSchema(value)
261
+ }
262
+
263
+ /**
264
+ * Generate the schema for a model method.
265
+ *
266
+ * @async
267
+ * @method
268
+ * @param {Object} param0 - The parameters for generating the schema
269
+ * @param {string} param0.model - The model name
270
+ * @param {string} param0.method - The method name
271
+ * @param {Object} [param0.options={}] - Additional options for schema generation
272
+ * @returns {Object} The generated schema
273
+ */
274
+ docSchemaModel = async ({ model, method, options = {} }) => {
275
+ const mdl = this.app.dobo.getModel(model)
276
+ const { omit } = this.app.lib._
277
+ const out = {
278
+ description: options.description ?? this.docSchemaDescription(method),
279
+ tags: [this.alias.toUpperCase(), ...(options.alias ?? [])]
280
+ }
281
+ if (['find'].includes(method)) {
282
+ out.querystring = { $ref: 'qsFilter#' }
283
+ }
284
+ if (['get', 'update', 'replace', 'remove'].includes(method)) {
285
+ out.querystring = { $ref: 'qsFields#' }
286
+ if (!options.noId) out.params = { $ref: 'paramsId#' }
287
+ }
288
+ if (['update'].includes(method)) {
289
+ const { properties } = await buildPropsReqsForSchema.call(this, { model: mdl, method, options })
290
+ const name = 'model' + mdl.name + 'Update'
291
+ delete properties._ref
292
+ await this.docSchemaLib(name, {
293
+ type: 'object',
294
+ properties: omit(properties, ['id'])
295
+ })
296
+ out.body = { $ref: name + '#' }
297
+ }
298
+ if (['replace'].includes(method)) {
299
+ const { properties, required } = await buildPropsReqsForSchema.call(this, { model: mdl, method, options })
300
+ const name = 'model' + model.name + 'Replace'
301
+ delete properties._ref
302
+ await this.docSchemaLib(name, {
303
+ type: 'object',
304
+ properties: omit(properties, ['id']),
305
+ required
306
+ })
307
+ out.body = { $ref: name + '#' }
308
+ }
309
+ if (['create'].includes(method)) {
310
+ const { properties, required } = await buildPropsReqsForSchema.call(this, { model: mdl, method, options })
311
+ const name = 'model' + model.name + 'Create'
312
+ delete properties._ref
313
+ await this.docSchemaLib(name, {
314
+ type: 'object',
315
+ properties,
316
+ required
317
+ })
318
+ out.body = { $ref: name + '#' }
319
+ out.querystring = { $ref: 'qsFields#' }
320
+ }
321
+ out.response = await buildResponseForSchema.call(this, { model: mdl, method, options })
322
+ return out
323
+ }
324
+
325
+ /**
326
+ * Generate the schema for query parameters.
327
+ *
328
+ * @async
329
+ * @method
330
+ * @param {string} paramName - The name of the parameter
331
+ * @param {...string} args - The arguments for the parameter schema
332
+ * @returns {void}
333
+ */
334
+ docSchemaParams = async (paramName, ...args) => {
335
+ const { each, isEmpty, keys, last, isBoolean } = this.app.lib._
336
+ const cfgWeb = this.app.waibu.getConfig()
337
+ let transform = false
338
+ if (isBoolean(last(args))) {
339
+ transform = args.pop()
340
+ }
341
+ const item = {
342
+ type: 'object',
343
+ properties: {}
344
+ }
345
+ each(args, a => {
346
+ let [name, type, description, def] = a.split('|')
347
+ if (isEmpty(type)) type = 'string'
348
+ item.properties[name] = { type, description: this.t(description), default: def }
349
+ })
350
+ if (transform) {
351
+ each(keys(cfgWeb.qsKey), k => {
352
+ const v = cfgWeb.qsKey[k]
353
+ if (k === v || !item.properties[k]) return undefined
354
+ item.properties[v] = item.properties[k]
355
+ delete item.properties[k]
356
+ })
357
+ }
358
+ if (!isEmpty(args)) await this.docSchemaLib(paramName, item)
359
+ }
360
+
361
+ /**
362
+ * Generate the schema for query string parameters.
363
+ *
364
+ * @async
365
+ * @method
366
+ * @param {string} paramName - The name of the parameter
367
+ * @param {...string} args - The arguments for the parameter schema
368
+ * @returns {void}
369
+ */
370
+ docSchemaQs = async (paramName, ...args) => {
371
+ const { each, isEmpty } = this.app.lib._
372
+ const item = {
373
+ type: 'object',
374
+ properties: {}
375
+ }
376
+ each(args, a => {
377
+ let [name, type, description] = a.split(':')
378
+ if (isEmpty(type)) type = 'string'
379
+ item.properties[name] = { type, description: this.t(description) }
380
+ })
381
+ if (!isEmpty(args)) await this.docSchemaLib(paramName, item)
382
+ }
383
+
384
+ /**
385
+ * Handle not found errors.
386
+ *
387
+ * @async
388
+ * @method
389
+ * @param {Object} [err={}] - The error object
390
+ * @param {Object} req - The request object
391
+ * @param {Object} reply - The reply object
392
+ * @returns {Object} The transformed result
393
+ */
394
+ _handleNotFound = async (err = {}, req, reply) => {
395
+ const msg = this.t('routeNotFound%s%s', req.url, req.method)
396
+ const data = this.webAppCtx.httpErrors.createError(404, msg)
397
+ return this.transformResult({ data, req, reply })
398
+ }
399
+
400
+ /**
401
+ * Handle general errors.
402
+ *
403
+ * @async
404
+ * @method
405
+ * @param {Object} err - The error object
406
+ * @param {Object} req - The request object
407
+ * @param {Object} reply - The reply object
408
+ * @returns {Object} The transformed result
409
+ */
410
+ _handleError = async (err, req, reply) => {
411
+ err.statusCode = err.statusCode ?? 500
412
+ const msg = err.message
413
+ if (msg === '_notFound' || err.statusCode === 404) {
414
+ return this._handleNotFound(err, req, reply)
415
+ }
416
+ const data = this.webAppCtx.httpErrors.createError(err.statusCode, msg)
417
+ data.statusCode = err.statusCode
418
+ data.details = err.details
419
+ return this.transformResult({ data, req, reply })
420
+ }
421
+
422
+ /**
423
+ * Handle the response.
424
+ *
425
+ * @async
426
+ * @method
427
+ * @returns {void}
428
+ */
429
+ _handleResponse = async () => {
430
+ const me = this
431
+
432
+ this.webAppCtx.addHook('onSend', async function (req, reply, payload) {
433
+ let type = req.params.format
434
+ if (!type) {
435
+ const types = req.accepts().types()
436
+ if (me.config.format.supported.includes('xml') && types[0] === 'application/xml') type = 'xml'
437
+ else type = 'json'
438
+ }
439
+ let result = payload
440
+ switch (type) {
441
+ case 'xml': result = await handleResponseXml.call(me, req, reply, payload); break
442
+ }
443
+ return result
444
+ })
445
+ }
446
+
447
+ /**
448
+ * Serve a route.
449
+ *
450
+ * @async
451
+ * @method
452
+ * @param {Object} options - The options for serving the route
453
+ * @param {Object} options.mod - The module object
454
+ * @param {string} options.ns - The namespace
455
+ * @param {string} [options.parent] - The parent namespace
456
+ * @returns {Object} The served route
457
+ */
458
+ _serveRoute = async (options) => {
459
+ let { mod, ns, parent } = options
460
+ const { mergeRouteHooks } = await importModule('waibu:/lib/webapp.js', { asDefaultImport: false })
461
+ const cfgWdb = this.app.waibuDb.config
462
+ mod.config = mod.config ?? {}
463
+ mod.config.prefix = getPluginPrefix(ns, 'waibuRestApi')
464
+ mod.config.pathSrc = mod.url
465
+ mod.config.webApp = parent ?? ns
466
+ mod.config.ns = ns
467
+ mod.config.subNs = 'restapi'
468
+ mod.config.xSite = mod.xSite
469
+ mod.config.title = mod.title
470
+ delete mod.title
471
+ if (mod.method === 'PUT' && cfgWdb.dbModel.patchEnabled) mod.method = [mod.method, 'PATCH']
472
+ mod = defaultsDeep(pick(this.config, ['exposeHeadRoute', 'bodyLimit']), mod)
473
+ await mergeRouteHooks.call(this, mod, false) // Don't include handler, hence 'false'
474
+ return mod
475
+ }
476
+
477
+ /**
478
+ * Build a route based on the model configuration.
479
+ *
480
+ * @async
481
+ * @method
482
+ * @param {Object} options - The options for building the route
483
+ * @param {string} options.file - The file path of the model configuration
484
+ * @param {string} options.dir - The directory of the model configuration
485
+ * @param {string} options.pathPrefix - The path prefix for the route
486
+ * @param {string} options.ns - The namespace
487
+ * @param {string} [options.parent] - The parent namespace
488
+ * @returns {Object} The built route
489
+ */
490
+ _routeByModelBuilder = async (options) => {
491
+ const { file, dir, pathPrefix, ns, parent } = options
492
+ const { readConfig } = this.app.bajo
493
+ const { pascalCase } = this.app.lib.aneka
494
+ const { methodMap, getParams } = this.app.waibuDb
495
+ const { isFunction, camelCase, omit, merge, keys, filter } = this.app.lib._
496
+ const builder = await readConfig(file, { ns, ignoreError: true })
497
+ builder.disabled = builder.disabled ?? []
498
+ let url = path.dirname(file).replace(`${dir}/extend/${pathPrefix}`, '').replaceAll('@', ':')
499
+ if (isFunction(builder.url)) url = await builder.url.call(this)
500
+ const methods = keys(methodMap)
501
+ if (this.config.enablePatch) methods.push('replace')
502
+ const me = this
503
+ const mods = []
504
+ let model = {}
505
+ if (!builder.model.startsWith(':')) model = this.app.dobo.getModel(builder.model)
506
+ for (const method of methods) {
507
+ let disabled = (model.disabled ?? []).includes(method) || builder.disabled.includes(method)
508
+ if (method === 'replace' && ((model.disabled ?? []).includes('update') || (builder.disabled ?? []).includes('update'))) disabled = true
509
+ if (disabled) continue
510
+ const mod = omit(builder, ['model', 'url', 'method', 'handler', 'hidden', ...methods])
511
+ const customMod = builder[method] ?? {}
512
+ customMod.schema = customMod.schema ?? false
513
+ if (customMod.schema === true && !builder.model.startsWith(':')) customMod.schema = await this.docSchemaModel({ model: builder.model, method, options: { hidden: builder.hidden } })
514
+ let mapmethod = methodMap[method]
515
+ if (this.config.enablePatch) {
516
+ if (method === 'replace') mapmethod = 'PUT'
517
+ else if (method === 'update') mapmethod = 'PATCH'
518
+ }
519
+ merge(mod, customMod, {
520
+ url: ['get', 'update', 'replace', 'remove'].includes(method) ? `${url}/:id` : url,
521
+ method: mapmethod,
522
+ handler: async function (req, reply) {
523
+ const helper = me.app.waibuDb[`${method === 'replace' ? 'update' : method}Record`]
524
+ const { fields } = getParams(req)
525
+ const options = { fields, dynHooks: builder.hooks ?? [] }
526
+ extractHeaders.call(me, req, options)
527
+ options.hidden = builder.hidden ?? []
528
+ options.queryHandler = builder.queryHandler
529
+ if (method === 'replace') options.partial = false
530
+ if (['get', 'remove', 'update'].includes(method)) options.throwNotFound = true
531
+ const model = builder.model.startsWith(':') ? pascalCase(req.params[builder.model.slice(1)]) : builder.model
532
+ const data = await helper({ model, req, reply, options, transaction: builder.transaction })
533
+ data.success = true
534
+ data.statusCode = method === 'create' ? 201 : 200
535
+ if (method === 'find') options.forFind = true
536
+ return me.transformResult({ data, req, reply, options })
537
+ }
538
+ })
539
+ if (mod.schema === false) delete mod.schema
540
+ mod.config = mod.config ?? {}
541
+ mod.config.pathSrc = url
542
+ mods.push(await me._serveRoute({ mod, ns, parent }))
543
+ }
544
+ // stats
545
+ const supported = ['aggregate', 'histogram']
546
+ builder.stat = filter(builder.stat ?? supported, item => supported.includes(item))
547
+ const method = 'GET'
548
+ const disabled = (model.disabled ?? []).includes(method) || builder.disabled.includes(method)
549
+ if (disabled) return mods
550
+ const mod = {
551
+ schema: false,
552
+ method,
553
+ url: `${url}/stat/:stat`,
554
+ handler: async function (req, reply) {
555
+ if (!supported.includes(req.params.stat)) throw me.error('_notFound')
556
+ const helper = me.app.waibuDb[camelCase(`create ${req.params.stat}`)]
557
+ if (!helper) throw me.error('_notFound')
558
+ const options = { queryHandler: builder.queryHandler }
559
+ const model = builder.model.startsWith(':') ? pascalCase(req.params[builder.model.slice(1)]) : builder.model
560
+ const data = await helper({ model, req, reply, options })
561
+ data.success = true
562
+ data.statusCode = method === 'create' ? 201 : 200
563
+ options.forFind = true
564
+ return me.transformResult({ data, req, reply, options })
565
+ }
566
+ }
567
+ mod.config = builder.config ?? {}
568
+ mod.config.pathSrc = url
569
+ mods.push(await me._serveRoute({ mod, ns, parent }))
570
+ return mods
571
+ }
572
+
573
+ /**
574
+ * Build a route based on the HTTP verb.
575
+ *
576
+ * @async
577
+ * @method
578
+ * @param {Object} options - The options for building the route
579
+ * @param {string} options.file - The file path of the route configuration
580
+ * @param {Object} options.appCtx - The application context
581
+ * @param {string} options.dir - The directory of the route configuration
582
+ * @param {string} options.pathPrefix - The path prefix for the route
583
+ * @param {string} options.ns - The namespace
584
+ * @param {string} options.alias - The alias for the route
585
+ * @param {string} [options.parent] - The parent namespace
586
+ * @returns {Object} The built route
587
+ */
588
+ _routeByVerb = async (options) => {
589
+ const { file, appCtx, dir, pathPrefix, ns, alias, parent } = options
590
+ const me = this
591
+ const url = path.dirname(file).replace(`${dir}/extend/${pathPrefix}`, '')
592
+ .replaceAll('@@', '*').replaceAll('@', ':')
593
+ const action = path.basename(file, '.js')
594
+ let method = methodMap[action]
595
+ if (this.enablePatch) {
596
+ if (action === 'update') method = 'PATCH'
597
+ else if (action === 'replace') method = 'PUT'
598
+ }
599
+ let mod = await importModule(file)
600
+ if (isFunction(mod)) {
601
+ if (mod.length <= 1) mod = await mod.call(this)
602
+ else mod = { handler: mod }
603
+ }
604
+ mod.url = mod.url ?? url
605
+ if (isFunction(mod.url)) mod.url = await mod.url.call(this)
606
+ mod.method = method
607
+ const defSchema = {
608
+ description: this.docSchemaDescription(action),
609
+ tags: [alias.toUpperCase()],
610
+ response: {}
611
+ }
612
+ if (['create', 'update', 'replace'].includes(action)) {
613
+ defSchema.response['4xx'] = {
614
+ description: this.t('docErrorResponse'),
615
+ $ref: '4xxResp#'
616
+ }
617
+ }
618
+ defSchema.response['5xx'] = {
619
+ description: this.t('generalErrorResponse'),
620
+ $ref: '5xxResp#'
621
+ }
622
+ if (action === 'find') defSchema.querystring = { $ref: 'qsFilter#' }
623
+ if (isFunction(mod.schema)) mod.schema = await mod.schema.call(this, appCtx)
624
+ mod.schema = merge({}, defSchema, mod.schema ?? {})
625
+ const oldHandler = mod.handler
626
+ mod.handler = async function (req, reply) {
627
+ const { fields } = getParams(req)
628
+ const options = { fields, dynHooks: mod.hooks ?? [] }
629
+ extractHeaders.call(me, req, options)
630
+ if (method === 'find') options.forFind = true
631
+ if (method === 'replace') options.partial = false
632
+ const data = await oldHandler.call(me.app[ns], req, reply, options, this)
633
+ if (!data) return
634
+ data.success = true
635
+ data.statusCode = method === 'create' ? 201 : 200
636
+ return me.transformResult({ data, req, reply, options })
637
+ }
638
+ if (mod.schema === false) delete mod.schema
639
+ mod.config = mod.config ?? {}
640
+ mod.config.pathSrc = url
641
+ return me._serveRoute({ mod, ns, parent })
642
+ }
643
+
644
+ /**
645
+ * Handle sub-applications by collecting and registering their routes.
646
+ *
647
+ * @async
648
+ * @method
649
+ */
650
+ _handleSubApp = async () => {
651
+ const { collectWebApps } = await importModule('waibu:/lib/helper.js', { asDefaultImport: false })
652
+ const mods = await collectWebApps.call(this.app[this.ns], 'boot.js', 'waibuRestApi')
653
+ for (const m of mods) {
654
+ this.log.debug('bootSubApp%s', m.ns)
655
+ await this.webAppCtx.register(async (subCtx) => {
656
+ this.app[m.ns].instance = subCtx
657
+ await runHook(`${this.ns}.${m.alias}:afterCreateContext`, subCtx)
658
+ await m.handler.call(this.app[m.ns], subCtx, m.prefix)
659
+ }, { prefix: m.prefix })
660
+ }
661
+ }
173
662
  }
174
663
 
175
664
  return WaibuRestApi