waibu-rest-api 1.0.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/LICENSE +21 -0
- package/README.md +23 -0
- package/bajo/config.json +51 -0
- package/bajo/hook/bajo-i18n@before-init.js +6 -0
- package/bajo/hook/waibu-rest-api@pre-parsing.js +16 -0
- package/bajo/hook/waibu@after-init.js +6 -0
- package/bajo/init.js +7 -0
- package/bajo/method/transform-result.js +58 -0
- package/bajoI18N/resource/id.json +3 -0
- package/lib/decorate.js +5 -0
- package/lib/error.js +21 -0
- package/lib/handle-response/xml.js +36 -0
- package/lib/handle-response.js +21 -0
- package/lib/not-found.js +14 -0
- package/lib/route-by-coll-builder.js +60 -0
- package/lib/route-by-verb.js +65 -0
- package/lib/serve-route.js +18 -0
- package/lib/sub-app.js +11 -0
- package/package.json +29 -0
- package/waibu/boot.js +95 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Ardhi Lukianto
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# wakatobi-rest-api
|
|
2
|
+
|
|
3
|
+
Plugin name: **wakatobiRestApi**, alias: **wktbrestapi**
|
|
4
|
+
|
|
5
|
+
 
|
|
6
|
+
|
|
7
|
+
> <br />**Attention**: I do NOT accept any pull request at the moment, thanks!<br /><br />
|
|
8
|
+
|
|
9
|
+
Rest API support for [wakatobi](https://github.com/ardhi/wakatobi)
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
Goto your ```<bajo-base-dir>``` and type:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
$ npm install wakatobi-rest-api
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Now open your ```<bajo-data-dir>/config/.plugins``` and put ```wakatobi-rest-api``` in it
|
|
20
|
+
|
|
21
|
+
## License
|
|
22
|
+
|
|
23
|
+
[MIT](LICENSE)
|
package/bajo/config.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"alias": "wbrestapi",
|
|
3
|
+
"prefix": "api",
|
|
4
|
+
"mountAppAsRoot": true,
|
|
5
|
+
"exposeHead": true,
|
|
6
|
+
"enablePatch": false,
|
|
7
|
+
"bodyLimit": 1048576,
|
|
8
|
+
"i18n": {
|
|
9
|
+
"detectors": ["qs", "header"],
|
|
10
|
+
"defaultNs": ["dobo", "waibuRestApi"]
|
|
11
|
+
},
|
|
12
|
+
"format": {
|
|
13
|
+
"supported": ["json", "xml"],
|
|
14
|
+
"asExt": false,
|
|
15
|
+
"xml": {
|
|
16
|
+
"bodyParser": {
|
|
17
|
+
"contentTypes": ["text/xml", "application/xml", "application/rss+xml"],
|
|
18
|
+
"validate": false
|
|
19
|
+
},
|
|
20
|
+
"response": {
|
|
21
|
+
"wrapper": "doc",
|
|
22
|
+
"declaration": true,
|
|
23
|
+
"valueAsAttributes": true
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"responseKey": {
|
|
28
|
+
"data": "data",
|
|
29
|
+
"oldData": "oldData",
|
|
30
|
+
"page": "page",
|
|
31
|
+
"count": "count",
|
|
32
|
+
"pages": "pages",
|
|
33
|
+
"success": "success",
|
|
34
|
+
"statusCode": "code",
|
|
35
|
+
"error": "error",
|
|
36
|
+
"cached": "cached",
|
|
37
|
+
"message": "message",
|
|
38
|
+
"details": "details"
|
|
39
|
+
},
|
|
40
|
+
"mapSlash": "~",
|
|
41
|
+
"mapDot": ",",
|
|
42
|
+
"multipart": {
|
|
43
|
+
},
|
|
44
|
+
"cors": {},
|
|
45
|
+
"helmet": {},
|
|
46
|
+
"compress": false,
|
|
47
|
+
"rateLimit": false,
|
|
48
|
+
"disabled": [],
|
|
49
|
+
"rerouted": {},
|
|
50
|
+
"dependencies": ["bajo-db", "bajo-extra", "waibu"]
|
|
51
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const waibuRestApiPreParsing = {
|
|
2
|
+
level: 9,
|
|
3
|
+
handler: async function (ctx, req, reply) {
|
|
4
|
+
const { importModule } = this.app.bajo
|
|
5
|
+
const attachI18N = await importModule('waibu:/lib/webapp-scope/attach-i18n.js')
|
|
6
|
+
await attachI18N.call(this, this.config.i18n.detectors, req, reply)
|
|
7
|
+
reply.header('Content-Language', req.lang)
|
|
8
|
+
if (this.config.format.asExt && req.params.format) {
|
|
9
|
+
if (!this.config.format.supported.includes(req.params.format)) {
|
|
10
|
+
throw this.error('Unsupported format \'%s\'', req.params.format, { statusCode: 406 })
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export default waibuRestApiPreParsing
|
package/bajo/init.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
function reformat ({ data, req, reply, options = {} }) {
|
|
2
|
+
const { forOwn, get } = this.app.bajo.lib._
|
|
3
|
+
const newData = {}
|
|
4
|
+
forOwn(data, (v, k) => {
|
|
5
|
+
let key = get(this.config, `responseKey.${k}`, k)
|
|
6
|
+
if (options.forFind && k === 'data') key = get(this.config, 'responseKey.data')
|
|
7
|
+
newData[key] = v
|
|
8
|
+
})
|
|
9
|
+
return newData
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function returnError ({ data, req, reply, options = {} }) {
|
|
13
|
+
const { pascalCase } = this.app.bajo
|
|
14
|
+
const { last, map, kebabCase, upperFirst, keys, each, get, isEmpty } = this.app.bajo.lib._
|
|
15
|
+
const cfg = this.config
|
|
16
|
+
const cfgWeb = this.app.waibu.config
|
|
17
|
+
const errNames = kebabCase(data.constructor.name).split('-')
|
|
18
|
+
if (last(errNames) === 'error') errNames.pop()
|
|
19
|
+
data.error = this.print.write(map(errNames, s => upperFirst(s)).join(' '))
|
|
20
|
+
data.success = false
|
|
21
|
+
data.statusCode = data.statusCode ?? 500
|
|
22
|
+
if (reply && cfgWeb.dbColl.dataOnly) {
|
|
23
|
+
each(keys(data), k => {
|
|
24
|
+
const key = get(cfg, `responseKey.${k}`, k)
|
|
25
|
+
if (k === 'details' && !isEmpty(data[k])) data[k] = JSON.stringify(data[k])
|
|
26
|
+
reply.header(`X-${pascalCase(this.alias)}-${pascalCase(key)}`, data[k])
|
|
27
|
+
})
|
|
28
|
+
}
|
|
29
|
+
reply.code(data.statusCode)
|
|
30
|
+
const result = cfgWeb.dbColl.dataOnly ? { error: data.message } : data
|
|
31
|
+
return reformat.call(this, { data: result, req, reply, options })
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function returnSuccess ({ data, req, reply, options = {} }) {
|
|
35
|
+
const { pascalCase } = this.app.bajo
|
|
36
|
+
const { each, keys, omit, get } = this.app.bajo.lib._
|
|
37
|
+
const cfg = this.config
|
|
38
|
+
const cfgWeb = this.app.waibu.config
|
|
39
|
+
if (reply) {
|
|
40
|
+
reply.code(req.method.toUpperCase() === 'POST' ? 201 : 200)
|
|
41
|
+
if (cfgWeb.dbColl.dataOnly) {
|
|
42
|
+
each(keys(omit(data, ['data'])), k => {
|
|
43
|
+
const key = get(cfg, `responseKey.${k}`, k)
|
|
44
|
+
reply.header(`X-${pascalCase(this.alias)}-${pascalCase(key)}`, data[k])
|
|
45
|
+
})
|
|
46
|
+
return data.data
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return reformat.call(this, { data, req, reply, options })
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function transformResult ({ data, req, reply, options = {} }) {
|
|
53
|
+
const isError = data instanceof Error
|
|
54
|
+
if (isError) return returnError.call(this, { data, req, reply, options })
|
|
55
|
+
return returnSuccess.call(this, { data, req, reply, options })
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export default transformResult
|
package/lib/decorate.js
ADDED
package/lib/error.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { handler } from './not-found.js'
|
|
2
|
+
|
|
3
|
+
const extHandler = async function (ctx, err, req, reply) {
|
|
4
|
+
const code = err.statusCode ?? 500
|
|
5
|
+
const msg = err.message
|
|
6
|
+
if (msg === 'notfound') {
|
|
7
|
+
return handler.call(this, ctx, req, reply)
|
|
8
|
+
}
|
|
9
|
+
const data = ctx.httpErrors.createError(code, msg)
|
|
10
|
+
data.statusCode = code
|
|
11
|
+
data.details = err.details
|
|
12
|
+
return this.transformResult({ data, req, reply })
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function error (ctx) {
|
|
16
|
+
const { importModule } = this.app.bajo
|
|
17
|
+
const errorHandler = await importModule('waibu:/lib/webapp-scope/error-handler.js')
|
|
18
|
+
await errorHandler.call(this, ctx, extHandler)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export default error
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
async function xml (req, reply, payload) {
|
|
2
|
+
const { importPkg } = this.app.bajo
|
|
3
|
+
const { XMLBuilder } = await importPkg('bajoExtra:fast-xml-parser', { returnDefault: false })
|
|
4
|
+
const { get, set, isPlainObject, isArray } = this.app.bajo.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
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import xml from './handle-response/xml.js'
|
|
2
|
+
|
|
3
|
+
async function handleResponse (ctx) {
|
|
4
|
+
const me = this
|
|
5
|
+
|
|
6
|
+
ctx.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
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export function handler (ctx, req, reply) {
|
|
2
|
+
const msg = this.print.write('Route \'%s (%s)\' not found', req.url, req.method)
|
|
3
|
+
const data = ctx.httpErrors.createError(404, msg)
|
|
4
|
+
return this.transformResult({ data, req, reply })
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
async function notFound (ctx) {
|
|
8
|
+
const me = this
|
|
9
|
+
await ctx.setNotFoundHandler(async function (req, reply) {
|
|
10
|
+
return handler.call(me, ctx, req, reply)
|
|
11
|
+
})
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export default notFound
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import path from 'path'
|
|
2
|
+
import serveRoute from './serve-route.js'
|
|
3
|
+
|
|
4
|
+
async function routeByCollBuilder ({ file, ctx, dir, pathPrefix, ns }) {
|
|
5
|
+
const { getPlugin } = this.app.bajo
|
|
6
|
+
getPlugin('dobo') // ensure dobo is loaded
|
|
7
|
+
const { readConfig, parseObject, isSet } = this.app.bajo
|
|
8
|
+
const { methodMap, getParams } = this.app.waibu
|
|
9
|
+
const { getInfo } = this.app.dobo
|
|
10
|
+
const { camelCase, omit, merge, keys } = this.app.bajo.lib._
|
|
11
|
+
const builder = await readConfig(file, { ns, ignoreError: true })
|
|
12
|
+
const { schema } = getInfo(builder.coll)
|
|
13
|
+
const url = path.dirname(file).replace(`${dir}/${pathPrefix}`, '').replaceAll('@', ':')
|
|
14
|
+
const methods = keys(methodMap)
|
|
15
|
+
if (this.config.enablePatch) methods.push('replace')
|
|
16
|
+
const me = this
|
|
17
|
+
const mods = []
|
|
18
|
+
const swagger = this.app.waibuSwagger
|
|
19
|
+
for (const method of methods) {
|
|
20
|
+
let disabled = schema.disabled.includes(method) || (builder.disabled ?? []).includes(method)
|
|
21
|
+
if (method === 'replace' && (schema.disabled.includes('update') || (builder.disabled ?? []).includes('update'))) disabled = true
|
|
22
|
+
if (disabled) continue
|
|
23
|
+
const mod = omit(builder, ['coll', 'url', 'method', 'handler', 'hidden', ...methods])
|
|
24
|
+
const customMod = builder[method] ?? {}
|
|
25
|
+
if (!customMod.schema && swagger) customMod.schema = await swagger.docSchemaColl({ coll: builder.coll, method, ctx, options: { hidden: builder.hidden } })
|
|
26
|
+
let mapmethod = methodMap[method]
|
|
27
|
+
if (this.config.enablePatch) {
|
|
28
|
+
if (method === 'replace') mapmethod = 'PUT'
|
|
29
|
+
else if (method === 'update') mapmethod = 'PATCH'
|
|
30
|
+
}
|
|
31
|
+
merge(mod, customMod, {
|
|
32
|
+
url: ['get', 'update', 'replace', 'remove'].includes(method) ? `${url}/:id` : url,
|
|
33
|
+
method: mapmethod,
|
|
34
|
+
handler: async function (req, reply) {
|
|
35
|
+
const helper = me.app.waibu[camelCase(`record ${method === 'replace' ? 'update' : method}`)]
|
|
36
|
+
let { fields, count } = getParams(req)
|
|
37
|
+
let rels = []
|
|
38
|
+
const headers = parseObject(req.headers, true, true)
|
|
39
|
+
if (isSet(headers['x-count'])) count = headers['x-count']
|
|
40
|
+
if (isSet(headers['x-rels'])) rels = headers['x-rels']
|
|
41
|
+
if (typeof rels === 'string' && !['*', 'all'].includes(rels)) rels = [rels]
|
|
42
|
+
const options = { fields, count, rels }
|
|
43
|
+
options.hidden = builder.hidden ?? []
|
|
44
|
+
if (method === 'replace') options.partial = false
|
|
45
|
+
const data = await helper({ coll: builder.coll, req, reply, ctx: this, options })
|
|
46
|
+
data.success = true
|
|
47
|
+
data.statusCode = method === 'create' ? 201 : 200
|
|
48
|
+
if (method === 'find') options.forFind = true
|
|
49
|
+
return me.transformResult({ data, req, reply, options })
|
|
50
|
+
}
|
|
51
|
+
})
|
|
52
|
+
if (builder.schema === false) delete mod.schema
|
|
53
|
+
mod.config = mod.config ?? {}
|
|
54
|
+
mod.config.pathSrc = url
|
|
55
|
+
mods.push(await serveRoute.call(me, { mod, ns }))
|
|
56
|
+
}
|
|
57
|
+
return mods
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export default routeByCollBuilder
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import path from 'path'
|
|
2
|
+
import serveRoute from './serve-route.js'
|
|
3
|
+
|
|
4
|
+
async function routeByVerb ({ file, ctx, appCtx, dir, pathPrefix, ns, alias }) {
|
|
5
|
+
const { importModule, parseObject, isSet } = this.app.bajo
|
|
6
|
+
const { methodMap, getParams } = this.app.waibu
|
|
7
|
+
const { isFunction, merge } = this.app.bajo.lib._
|
|
8
|
+
const me = this
|
|
9
|
+
const url = path.dirname(file).replace(`${dir}/${pathPrefix}`, '')
|
|
10
|
+
.replaceAll('@@', '*').replaceAll('@', ':')
|
|
11
|
+
const action = path.basename(file, '.js')
|
|
12
|
+
let method = methodMap[action]
|
|
13
|
+
if (this.enablePatch) {
|
|
14
|
+
if (action === 'update') method = 'PATCH'
|
|
15
|
+
else if (action === 'replace') method = 'PUT'
|
|
16
|
+
}
|
|
17
|
+
let mod = await importModule(file)
|
|
18
|
+
if (isFunction(mod)) {
|
|
19
|
+
if (mod.length <= 1) mod = await mod.call(this, { ctx })
|
|
20
|
+
else mod = { handler: mod }
|
|
21
|
+
}
|
|
22
|
+
mod.url = mod.url ?? url
|
|
23
|
+
mod.method = method
|
|
24
|
+
const swagger = this.app.waibuSwagger
|
|
25
|
+
const defSchema = {
|
|
26
|
+
description: swagger ? swagger.docSchemaDescription(action) : undefined,
|
|
27
|
+
tags: [alias.toUpperCase()],
|
|
28
|
+
response: {}
|
|
29
|
+
}
|
|
30
|
+
if (['create', 'update', 'replace'].includes(action)) {
|
|
31
|
+
defSchema.response['4xx'] = {
|
|
32
|
+
description: this.print.write('Document error response'),
|
|
33
|
+
$ref: '4xxResp#'
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
defSchema.response['5xx'] = {
|
|
37
|
+
description: this.print.write('General error response'),
|
|
38
|
+
$ref: '5xxResp#'
|
|
39
|
+
}
|
|
40
|
+
if (action === 'find') defSchema.querystring = { $ref: 'qsFilter#' }
|
|
41
|
+
if (isFunction(mod.schema)) mod.schema = await mod.schema.call(this, appCtx, ctx)
|
|
42
|
+
mod.schema = merge({}, defSchema, mod.schema ?? {})
|
|
43
|
+
const oldHandler = mod.handler
|
|
44
|
+
mod.handler = async function (req, reply) {
|
|
45
|
+
let { fields, count } = getParams(req)
|
|
46
|
+
let rels = []
|
|
47
|
+
const headers = parseObject(req.headers, true, true)
|
|
48
|
+
if (isSet(headers['x-count'])) count = headers['x-count']
|
|
49
|
+
if (isSet(headers['x-rels'])) rels = headers['x-rels']
|
|
50
|
+
if (typeof rels === 'string' && !['*', 'all'].includes(rels)) rels = [rels]
|
|
51
|
+
const options = { fields, count, rels }
|
|
52
|
+
if (method === 'find') options.forFind = true
|
|
53
|
+
if (method === 'replace') options.partial = false
|
|
54
|
+
const data = await oldHandler.call(me, this, req, reply, options)
|
|
55
|
+
if (!data) return
|
|
56
|
+
data.success = true
|
|
57
|
+
data.statusCode = method === 'create' ? 201 : 200
|
|
58
|
+
return this.transformResult({ data, req, reply, options })
|
|
59
|
+
}
|
|
60
|
+
mod.config = mod.config ?? {}
|
|
61
|
+
mod.config.pathSrc = url
|
|
62
|
+
return serveRoute.call(me, { mod, ns })
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export default routeByVerb
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
async function serveRoute ({ mod, ns, parent }) {
|
|
2
|
+
const { defaultsDeep } = this.app.bajo
|
|
3
|
+
const { mergeRouteHooks } = this.app.waibu
|
|
4
|
+
const { pick } = this.app.bajo.lib._
|
|
5
|
+
const cfgWeb = this.app.waibu.config
|
|
6
|
+
mod.config = mod.config ?? {}
|
|
7
|
+
mod.config.webApp = this.name
|
|
8
|
+
mod.config.ns = parent ?? ns
|
|
9
|
+
mod.config.title = mod.title
|
|
10
|
+
if (parent) mod.config.subRouteOf = ns
|
|
11
|
+
delete mod.title
|
|
12
|
+
if (mod.method === 'PUT' && cfgWeb.dbColl.patchEnabled) mod.method = [mod.method, 'PATCH']
|
|
13
|
+
mod = defaultsDeep(pick(this.config, ['exposeHeadRoute', 'bodyLimit']), mod)
|
|
14
|
+
await mergeRouteHooks(mod, false)
|
|
15
|
+
return mod
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default serveRoute
|
package/lib/sub-app.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
async function subApp (ctx) {
|
|
2
|
+
const { importModule } = this.app.bajo
|
|
3
|
+
const { collect } = await importModule('waibu:/lib/app.js', { asDefaultImport: false })
|
|
4
|
+
const mods = await collect.call(this.app[this.name], 'boot.js', 'waibuRestApi')
|
|
5
|
+
for (const m of mods) {
|
|
6
|
+
this.log.debug('Boot sub app: %s', m.ns)
|
|
7
|
+
await m.handler.call(this.app[m.ns], ctx)
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export default subApp
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "waibu-rest-api",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "REST API for Waibu",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
8
|
+
},
|
|
9
|
+
"type": "module",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/ardhi/waibu-rest-api.git"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"restapi",
|
|
16
|
+
"web",
|
|
17
|
+
"webserver",
|
|
18
|
+
"bajo",
|
|
19
|
+
"framework",
|
|
20
|
+
"fastify",
|
|
21
|
+
"modular"
|
|
22
|
+
],
|
|
23
|
+
"author": "Ardhi Lukianto <ardhi@lukianto.com>",
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"bugs": {
|
|
26
|
+
"url": "https://github.com/ardhi/waibu-rest-api/issues"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://github.com/ardhi/waibu-rest-api#readme"
|
|
29
|
+
}
|
package/waibu/boot.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import path from 'path'
|
|
2
|
+
import decorate from '../lib/decorate.js'
|
|
3
|
+
import routeByCollBuilder from '../lib/route-by-coll-builder.js'
|
|
4
|
+
import routeByVerb from '../lib/route-by-verb.js'
|
|
5
|
+
import notFound from '../lib/not-found.js'
|
|
6
|
+
import error from '../lib/error.js'
|
|
7
|
+
import subApp from '../lib/sub-app.js'
|
|
8
|
+
import handleResponse from '../lib/handle-response.js'
|
|
9
|
+
|
|
10
|
+
const routeActions = { routeByCollBuilder, routeByVerb }
|
|
11
|
+
|
|
12
|
+
function formatExt (item) {
|
|
13
|
+
return item + '.:format'
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const boot = {
|
|
17
|
+
level: 10,
|
|
18
|
+
handler: async function () {
|
|
19
|
+
const { importPkg, eachPlugins, importModule, runHook } = this.app.bajo
|
|
20
|
+
const { fastGlob } = this.app.bajo.lib
|
|
21
|
+
const [bodyParser, accepts] = await importPkg('waibu:@fastify/formbody', 'waibu:@fastify/accepts')
|
|
22
|
+
const cfg = this.config
|
|
23
|
+
const pathPrefix = `${this.name}/route`
|
|
24
|
+
let prefix = cfg.prefix === '' ? '' : ('/' + cfg.prefix)
|
|
25
|
+
if (cfg.i18n.detectors.includes('path')) prefix = `/:lang${prefix}`
|
|
26
|
+
const routeHook = await importModule('waibu:/lib/webapp-scope/route-hook.js')
|
|
27
|
+
const handleMultipart = await importModule('waibu:/lib/webapp-scope/handle-multipart-body.js')
|
|
28
|
+
const handleXmlBody = await importModule('waibu:/lib/handle-xml-body.js')
|
|
29
|
+
const handleCors = await importModule('waibu:/lib/webapp-scope/handle-cors.js')
|
|
30
|
+
const handleHelmet = await importModule('waibu:/lib/webapp-scope/handle-helmet.js')
|
|
31
|
+
const handleCompress = await importModule('waibu:/lib/webapp-scope/handle-compress.js')
|
|
32
|
+
const handleRateLimit = await importModule('waibu:/lib/webapp-scope/handle-rate-limit.js')
|
|
33
|
+
const reroutedPath = await importModule('waibu:/lib/webapp-scope/rerouted-path.js')
|
|
34
|
+
const me = this
|
|
35
|
+
await this.app.waibu.instance.register(async (ctx) => {
|
|
36
|
+
this.instance = ctx
|
|
37
|
+
await runHook(`${this.name}:afterCreateContext`, ctx)
|
|
38
|
+
await routeHook.call(this, this.name)
|
|
39
|
+
await decorate.call(this, ctx)
|
|
40
|
+
if (cfg.format.supported.includes('xml')) {
|
|
41
|
+
await handleXmlBody.call(this, ctx, cfg.format.xml.bodyParser)
|
|
42
|
+
}
|
|
43
|
+
await ctx.register(accepts)
|
|
44
|
+
await ctx.register(bodyParser)
|
|
45
|
+
await handleRateLimit.call(this, ctx, cfg.rateLimit)
|
|
46
|
+
await handleCors.call(this, ctx, cfg.cors)
|
|
47
|
+
await handleHelmet.call(this, ctx, cfg.helmet)
|
|
48
|
+
await handleMultipart.call(this, ctx, cfg.multipart)
|
|
49
|
+
await handleCompress.call(this, ctx, cfg.compress)
|
|
50
|
+
await handleResponse.call(this, ctx)
|
|
51
|
+
await error.call(this, ctx)
|
|
52
|
+
await runHook(`${this.name}:beforeCreateRoutes`, ctx)
|
|
53
|
+
const actions = ['find', 'get', 'create', 'update', 'remove']
|
|
54
|
+
if (cfg.enablePatch) actions.push('replace')
|
|
55
|
+
await eachPlugins(async function ({ dir, alias, ns }) {
|
|
56
|
+
const appPrefix = '/' + (ns === this.app.bajo.mainNs && cfg.mountAppAsRoot ? '' : alias)
|
|
57
|
+
const pattern = [
|
|
58
|
+
`${dir}/${pathPrefix}/**/{${actions.join(',')}}.js`,
|
|
59
|
+
`${dir}/${pathPrefix}/**/coll-builder.*`
|
|
60
|
+
]
|
|
61
|
+
const files = await fastGlob(pattern)
|
|
62
|
+
if (files.length === 0) return undefined
|
|
63
|
+
await ctx.register(async (appCtx) => {
|
|
64
|
+
for (const file of files) {
|
|
65
|
+
const base = path.basename(file, path.extname(file))
|
|
66
|
+
const action = base === 'coll-builder' ? 'routeByCollBuilder' : 'routeByVerb'
|
|
67
|
+
let mods = await routeActions[action].call(me, { file, appCtx, ctx, dir, pathPrefix, ns, alias })
|
|
68
|
+
if (!Array.isArray(mods)) mods = [mods]
|
|
69
|
+
for (const mod of mods) {
|
|
70
|
+
const fullPath = appPrefix === '/' ? mod.url : (appPrefix + mod.url)
|
|
71
|
+
const isRouteDisabled = await importModule('waibu:/lib/webapp-scope/is-route-disabled.js')
|
|
72
|
+
if (await isRouteDisabled.call(this, fullPath, mod.method, cfg.disabled)) {
|
|
73
|
+
this.log.warn('Route %s (%s) is disabled', `${prefix}${fullPath}`, mod.method)
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
const rpath = await reroutedPath.call(this, fullPath, cfg.rerouted)
|
|
77
|
+
if (cfg.format.asExt) mod.url = formatExt(mod.url)
|
|
78
|
+
if (rpath) {
|
|
79
|
+
mod.config.pathReroutedTo = rpath
|
|
80
|
+
this.log.warn('Rerouted %s -> %s', `${prefix}${fullPath}`, `${prefix}${rpath}`)
|
|
81
|
+
mod.url = cfg.format.asExt ? formatExt(rpath) : rpath
|
|
82
|
+
await ctx.route(mod)
|
|
83
|
+
} else await appCtx.route(mod)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}, { prefix: appPrefix })
|
|
87
|
+
})
|
|
88
|
+
await runHook(`${this.name}:afterCreateRoutes`, ctx)
|
|
89
|
+
await subApp.call(this, ctx)
|
|
90
|
+
await notFound.call(this, ctx)
|
|
91
|
+
}, { prefix })
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export default boot
|