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.
@@ -1,36 +0,0 @@
1
- async function xml (req, reply, payload) {
2
- const { importPkg } = this.app.bajo
3
- const { XMLBuilder } = await importPkg('bajoExtra:fast-xml-parser')
4
- const { get, set, isPlainObject, isArray } = this.app.lib._
5
- const { wrapper, valueAsAttributes, declaration } = this.config.format.xml.response
6
-
7
- reply.type('application/xml; charset=utf-8')
8
- const wrapped = set({}, wrapper, JSON.parse(payload))
9
- const opts = {
10
- attributeValueProcessor: function (k, v) {
11
- return v === 'null' ? '' : v
12
- }
13
- }
14
- const dataKey = this.config.responseKey.data
15
- if (valueAsAttributes) {
16
- const dataValue = get(wrapped, `${wrapper}.${dataKey}`)
17
- opts.attributesGroupName = '_attrs'
18
- if (isPlainObject(dataValue)) {
19
- delete wrapped[wrapper][dataKey]
20
- set(wrapped[wrapper], `${dataKey}._attrs`, dataValue)
21
- } else if (isArray(dataValue)) {
22
- delete wrapped[wrapper][dataKey]
23
- const recs = []
24
- for (const d of dataValue) {
25
- recs.push(set({}, '_attrs', d))
26
- }
27
- set(wrapped[wrapper], dataKey, recs)
28
- }
29
- }
30
- const builder = new XMLBuilder(opts)
31
- let content = builder.build(wrapped)
32
- if (declaration) content = '<?xml version="1.0" encoding="UTF-8" ?>' + content
33
- return content
34
- }
35
-
36
- export default xml
@@ -1,21 +0,0 @@
1
- import xml from './handle-response/xml.js'
2
-
3
- async function handleResponse () {
4
- const me = this
5
-
6
- this.webAppCtx.addHook('onSend', async function (req, reply, payload) {
7
- let type = req.params.format
8
- if (!type) {
9
- const types = req.accepts().types()
10
- if (me.config.format.supported.includes('xml') && types[0] === 'application/xml') type = 'xml'
11
- else type = 'json'
12
- }
13
- let result = payload
14
- switch (type) {
15
- case 'xml': result = await xml.call(me, req, reply, payload); break
16
- }
17
- return result
18
- })
19
- }
20
-
21
- export default handleResponse
package/lib/not-found.js DELETED
@@ -1,11 +0,0 @@
1
- export function handler (req, reply) {
2
- const msg = this.t('routeNotFound%s%s', req.url, req.method)
3
- const data = this.webAppCtx.httpErrors.createError(404, msg)
4
- return this.transformResult({ data, req, reply })
5
- }
6
-
7
- async function notFound (err = {}, req, reply) {
8
- return handler.call(this, req, reply)
9
- }
10
-
11
- export default notFound
@@ -1,99 +0,0 @@
1
- import path from 'path'
2
- import serveRoute from './serve-route.js'
3
-
4
- export function extractHeaders (req, options) {
5
- const { parseObject } = this.app.lib
6
- const { isSet } = this.app.lib.aneka
7
- options.count = true
8
- options.refs = []
9
- const headers = parseObject(req.headers, { parseValue: true })
10
- if (headers['x-no-count']) options.count = false
11
- if (isSet(headers['x-refs'])) options.refs = headers['x-refs']
12
- if (typeof options.refs === 'string' && !['*', 'all'].includes(options.refs)) options.refs = [options.refs]
13
- if (headers['x-warnings']) options.showWarnings = true
14
- if (headers['x-formatted'] || headers['x-fmt']) options.fmt = true
15
- }
16
-
17
- async function routeByModelBuilder ({ file, dir, pathPrefix, ns, parent }) {
18
- const { readConfig } = this.app.bajo
19
- const { pascalCase } = this.app.lib.aneka
20
- const { methodMap, getParams } = this.app.waibuDb
21
- const { isFunction, camelCase, omit, merge, keys, filter } = this.app.lib._
22
- const builder = await readConfig(file, { ns, ignoreError: true })
23
- builder.disabled = builder.disabled ?? []
24
- let url = path.dirname(file).replace(`${dir}/extend/${pathPrefix}`, '').replaceAll('@', ':')
25
- if (isFunction(builder.url)) url = await builder.url.call(this)
26
- const methods = keys(methodMap)
27
- if (this.config.enablePatch) methods.push('replace')
28
- const me = this
29
- const mods = []
30
- let model = {}
31
- if (!builder.model.startsWith(':')) model = this.app.dobo.getModel(builder.model)
32
- for (const method of methods) {
33
- let disabled = (model.disabled ?? []).includes(method) || builder.disabled.includes(method)
34
- if (method === 'replace' && ((model.disabled ?? []).includes('update') || (builder.disabled ?? []).includes('update'))) disabled = true
35
- if (disabled) continue
36
- const mod = omit(builder, ['model', 'url', 'method', 'handler', 'hidden', ...methods])
37
- const customMod = builder[method] ?? {}
38
- customMod.schema = customMod.schema ?? false
39
- if (customMod.schema === true && !builder.model.startsWith(':')) customMod.schema = await this.docSchemaModel({ model: builder.model, method, options: { hidden: builder.hidden } })
40
- let mapmethod = methodMap[method]
41
- if (this.config.enablePatch) {
42
- if (method === 'replace') mapmethod = 'PUT'
43
- else if (method === 'update') mapmethod = 'PATCH'
44
- }
45
- merge(mod, customMod, {
46
- url: ['get', 'update', 'replace', 'remove'].includes(method) ? `${url}/:id` : url,
47
- method: mapmethod,
48
- handler: async function (req, reply) {
49
- const helper = me.app.waibuDb[`${method === 'replace' ? 'update' : method}Record`]
50
- const { fields } = getParams(req)
51
- const options = { fields, dynHooks: builder.hooks ?? [] }
52
- extractHeaders.call(me, req, options)
53
- options.hidden = builder.hidden ?? []
54
- options.queryHandler = builder.queryHandler
55
- if (method === 'replace') options.partial = false
56
- if (['get', 'remove', 'update'].includes(method)) options.throwNotFound = true
57
- const model = builder.model.startsWith(':') ? pascalCase(req.params[builder.model.slice(1)]) : builder.model
58
- const data = await helper({ model, req, reply, options, transaction: builder.transaction })
59
- data.success = true
60
- data.statusCode = method === 'create' ? 201 : 200
61
- if (method === 'find') options.forFind = true
62
- return me.transformResult({ data, req, reply, options })
63
- }
64
- })
65
- if (mod.schema === false) delete mod.schema
66
- mod.config = mod.config ?? {}
67
- mod.config.pathSrc = url
68
- mods.push(await serveRoute.call(me, { mod, ns, parent }))
69
- }
70
- // stats
71
- const supported = ['aggregate', 'histogram']
72
- builder.stat = filter(builder.stat ?? supported, item => supported.includes(item))
73
- const method = 'GET'
74
- const disabled = (model.disabled ?? []).includes(method) || builder.disabled.includes(method)
75
- if (disabled) return mods
76
- const mod = {
77
- schema: false,
78
- method,
79
- url: `${url}/stat/:stat`,
80
- handler: async function (req, reply) {
81
- if (!supported.includes(req.params.stat)) throw me.error('_notFound')
82
- const helper = me.app.waibuDb[camelCase(`create ${req.params.stat}`)]
83
- if (!helper) throw this.error('_notFound')
84
- const options = { queryHandler: builder.queryHandler }
85
- const model = builder.model.startsWith(':') ? pascalCase(req.params[builder.model.slice(1)]) : builder.model
86
- const data = await helper({ model, req, reply, options })
87
- data.success = true
88
- data.statusCode = method === 'create' ? 201 : 200
89
- options.forFind = true
90
- return me.transformResult({ data, req, reply, options })
91
- }
92
- }
93
- mod.config = builder.config ?? {}
94
- mod.config.pathSrc = url
95
- mods.push(await serveRoute.call(me, { mod, ns, parent }))
96
- return mods
97
- }
98
-
99
- export default routeByModelBuilder
@@ -1,63 +0,0 @@
1
- import path from 'path'
2
- import serveRoute from './serve-route.js'
3
- import { extractHeaders } from './route-by-model-builder.js'
4
-
5
- async function routeByVerb ({ file, appCtx, dir, pathPrefix, ns, alias, parent }) {
6
- const { importModule } = this.app.bajo
7
- const { methodMap, getParams } = this.app.waibuDb
8
- const { isFunction, merge } = this.app.lib._
9
- const me = this
10
- const url = path.dirname(file).replace(`${dir}/extend/${pathPrefix}`, '')
11
- .replaceAll('@@', '*').replaceAll('@', ':')
12
- const action = path.basename(file, '.js')
13
- let method = methodMap[action]
14
- if (this.enablePatch) {
15
- if (action === 'update') method = 'PATCH'
16
- else if (action === 'replace') method = 'PUT'
17
- }
18
- let mod = await importModule(file)
19
- if (isFunction(mod)) {
20
- if (mod.length <= 1) mod = await mod.call(this)
21
- else mod = { handler: mod }
22
- }
23
- mod.url = mod.url ?? url
24
- if (isFunction(mod.url)) mod.url = await mod.url.call(this)
25
- mod.method = method
26
- const defSchema = {
27
- description: this.docSchemaDescription(action),
28
- tags: [alias.toUpperCase()],
29
- response: {}
30
- }
31
- if (['create', 'update', 'replace'].includes(action)) {
32
- defSchema.response['4xx'] = {
33
- description: this.t('docErrorResponse'),
34
- $ref: '4xxResp#'
35
- }
36
- }
37
- defSchema.response['5xx'] = {
38
- description: this.t('generalErrorResponse'),
39
- $ref: '5xxResp#'
40
- }
41
- if (action === 'find') defSchema.querystring = { $ref: 'qsFilter#' }
42
- if (isFunction(mod.schema)) mod.schema = await mod.schema.call(this, appCtx)
43
- mod.schema = merge({}, defSchema, mod.schema ?? {})
44
- const oldHandler = mod.handler
45
- mod.handler = async function (req, reply) {
46
- const { fields } = getParams(req)
47
- const options = { fields, dynHooks: mod.hooks ?? [] }
48
- extractHeaders.call(me, req, options)
49
- if (method === 'find') options.forFind = true
50
- if (method === 'replace') options.partial = false
51
- const data = await oldHandler.call(me.app[ns], req, reply, options, this)
52
- if (!data) return
53
- data.success = true
54
- data.statusCode = method === 'create' ? 201 : 200
55
- return me.transformResult({ data, req, reply, options })
56
- }
57
- if (mod.schema === false) delete mod.schema
58
- mod.config = mod.config ?? {}
59
- mod.config.pathSrc = url
60
- return serveRoute.call(me, { mod, ns, parent })
61
- }
62
-
63
- export default routeByVerb
@@ -1,23 +0,0 @@
1
- async function serveRoute ({ mod, ns, parent }) {
2
- const { defaultsDeep } = this.app.lib.aneka
3
- const { importModule } = this.app.bajo
4
- const { getPluginPrefix } = this.app.waibu
5
- const { pick } = this.app.lib._
6
- const mergeRouteHooks = await importModule('waibu:/lib/webapp-scope/merge-route-hooks.js')
7
- const cfgWdb = this.app.waibuDb.config
8
- mod.config = mod.config ?? {}
9
- mod.config.prefix = getPluginPrefix(ns, 'waibuRestApi')
10
- mod.config.pathSrc = mod.url
11
- mod.config.webApp = parent ?? ns
12
- mod.config.ns = ns
13
- mod.config.subNs = 'restapi'
14
- mod.config.xSite = mod.xSite
15
- mod.config.title = mod.title
16
- delete mod.title
17
- if (mod.method === 'PUT' && cfgWdb.dbModel.patchEnabled) mod.method = [mod.method, 'PATCH']
18
- mod = defaultsDeep(pick(this.config, ['exposeHeadRoute', 'bodyLimit']), mod)
19
- await mergeRouteHooks.call(this, mod, false) // Don't include handler, hence 'false'
20
- return mod
21
- }
22
-
23
- export default serveRoute
package/lib/sub-app.js DELETED
@@ -1,15 +0,0 @@
1
- async function subApp () {
2
- const { importModule, runHook } = this.app.bajo
3
- const { collect } = await importModule('waibu:/lib/web-app.js', { asDefaultImport: false })
4
- const mods = await collect.call(this.app[this.ns], 'boot.js', 'waibuRestApi')
5
- for (const m of mods) {
6
- this.log.debug('bootSubApp%s', m.ns)
7
- await this.webAppCtx.register(async (subCtx) => {
8
- this.app[m.ns].instance = subCtx
9
- await runHook(`${this.ns}.${m.alias}:afterCreateContext`, subCtx)
10
- await m.handler.call(this.app[m.ns], subCtx, m.prefix)
11
- }, { prefix: m.prefix })
12
- }
13
- }
14
-
15
- export default subApp