waibu-rest-api 1.0.0 → 1.0.2

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/README.md CHANGED
@@ -1,22 +1,22 @@
1
- # wakatobi-rest-api
1
+ # waibu-rest-api
2
2
 
3
- Plugin name: **wakatobiRestApi**, alias: **wktbrestapi**
3
+ Plugin name: **waibuRestApi**, alias: **wrest**
4
4
 
5
- ![GitHub package.json version](https://img.shields.io/github/package-json/v/ardhi/wakatobi-rest-api) ![NPM Version](https://img.shields.io/npm/v/wakatobi-rest-api)
5
+ ![GitHub package.json version](https://img.shields.io/github/package-json/v/ardhi/waibu-rest-api) ![NPM Version](https://img.shields.io/npm/v/waibu-rest-api)
6
6
 
7
7
  > <br />**Attention**: I do NOT accept any pull request at the moment, thanks!<br /><br />
8
8
 
9
- Rest API support for [wakatobi](https://github.com/ardhi/wakatobi)
9
+ Rest API support for [waibu](https://github.com/ardhi/waibu)
10
10
 
11
11
  ## Installation
12
12
 
13
13
  Goto your ```<bajo-base-dir>``` and type:
14
14
 
15
15
  ```bash
16
- $ npm install wakatobi-rest-api
16
+ $ npm install waibu-rest-api
17
17
  ```
18
18
 
19
- Now open your ```<bajo-data-dir>/config/.plugins``` and put ```wakatobi-rest-api``` in it
19
+ Now open your ```<bajo-data-dir>/config/.plugins``` and put ```waibu-rest-api``` in it
20
20
 
21
21
  ## License
22
22
 
package/bajo/.alias ADDED
@@ -0,0 +1 @@
1
+ wra
@@ -0,0 +1,3 @@
1
+ waibu-db
2
+ bajo-extra
3
+ waibu
package/bajo/config.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
- "alias": "wbrestapi",
3
- "prefix": "api",
4
- "mountAppAsRoot": true,
2
+ "waibu": {
3
+ "prefix": "api"
4
+ },
5
+ "mountMainAsRoot": true,
5
6
  "exposeHead": true,
6
7
  "enablePatch": false,
7
8
  "bodyLimit": 1048576,
@@ -46,6 +47,5 @@
46
47
  "compress": false,
47
48
  "rateLimit": false,
48
49
  "disabled": [],
49
- "rerouted": {},
50
- "dependencies": ["bajo-db", "bajo-extra", "waibu"]
50
+ "rerouted": {}
51
51
  }
@@ -1,6 +1,6 @@
1
1
  const waibuRestApiPreParsing = {
2
2
  level: 9,
3
- handler: async function (ctx, req, reply) {
3
+ handler: async function (req, reply) {
4
4
  const { importModule } = this.app.bajo
5
5
  const attachI18N = await importModule('waibu:/lib/webapp-scope/attach-i18n.js')
6
6
  await attachI18N.call(this, this.config.i18n.detectors, req, reply)
@@ -1,6 +1,6 @@
1
1
  async function waibuAfterInit () {
2
2
  this.app.waibu.config.paramsCharMap[this.config.mapSlash] = '/'
3
- this.app.waibu.config.paramsCharMap[this.config.mapDot] = '.'
3
+ // this.app.waibu.config.paramsCharMap[this.config.mapDot] = '.'
4
4
  }
5
5
 
6
6
  export default waibuAfterInit
@@ -0,0 +1,13 @@
1
+ const desc = {
2
+ create: 'Post a new record',
3
+ find: 'Find records by query, page size and number.',
4
+ get: 'Get record by ID',
5
+ update: 'Update record by ID',
6
+ remove: 'Remove record by ID'
7
+ }
8
+
9
+ function docDescription (method) {
10
+ return this.print.write(desc[method])
11
+ }
12
+
13
+ export default docDescription
@@ -0,0 +1,16 @@
1
+ async function forFind (ctx, items) {
2
+ return {
3
+ data: {
4
+ type: 'array',
5
+ items
6
+ },
7
+ limit: { type: 'integer' },
8
+ page: { type: 'integer' },
9
+ pages: { type: 'integer' },
10
+ count: { type: 'integer' },
11
+ success: { type: 'boolean', default: true },
12
+ statusCode: { type: 'integer', default: 200 }
13
+ }
14
+ }
15
+
16
+ export default forFind
@@ -0,0 +1,79 @@
1
+ async function buildErrResp (ctx) {
2
+ const { cloneDeep, merge, each, get } = this.app.bajo.lib._
3
+ const cfg = this.config
4
+ const cfgWdb = this.app.waibuDb.config
5
+ const def = {
6
+ type: 'object',
7
+ properties: {
8
+ error: { type: 'string' },
9
+ message: { type: 'string' }
10
+ }
11
+ }
12
+ for (const type of ['4xx', '5xx']) {
13
+ const item = cloneDeep(def)
14
+ if (type === '4xx') {
15
+ merge(item, {
16
+ properties: {
17
+ details: {
18
+ type: 'array',
19
+ items: {
20
+ type: 'object',
21
+ properties: {
22
+ field: { type: 'string' },
23
+ error: { type: 'string' }
24
+ }
25
+ }
26
+ },
27
+ success: { type: 'boolean', default: false },
28
+ statusCode: { type: 'integer', default: 400 }
29
+ }
30
+ })
31
+ } else {
32
+ merge(item, {
33
+ properties: {
34
+ success: { type: 'boolean', default: false },
35
+ statusCode: { type: 'integer', default: 500 }
36
+ }
37
+ })
38
+ }
39
+ if (cfgWdb.dbModel.dataOnly) item.properties = { error: item.properties.message }
40
+ const props = {}
41
+ each(item.properties, (v, k) => {
42
+ const key = get(cfg, `responseKey.${k}`, k)
43
+ props[key] = item.properties[k]
44
+ })
45
+ item.properties = props
46
+ await this.docSchemaLib(ctx, type + 'Resp', item)
47
+ }
48
+ }
49
+
50
+ async function buildFilter (ctx) {
51
+ await this.docSchemaParams(ctx, 'qsFilter',
52
+ 'query||NQL/Mongo Query. Leave empty to disable query',
53
+ 'limit|integer|Number of records per page. Must be >= 1|' + this.app.dobo.config.default.filter.limit,
54
+ 'page|integer|Desired page number. Must be >= 1|1',
55
+ 'sort||Order of records, format: &lt;field&gt;:&lt;dir&gt;[,&lt;field&gt;:&lt;dir&gt;,[...]]',
56
+ 'fields||Comma delimited fields to show. Leave empty to show all fields',
57
+ true
58
+ )
59
+ }
60
+
61
+ async function buildFields (ctx) {
62
+ await this.docSchemaParams(ctx, 'qsFields',
63
+ 'fields||Comma delimited fields to show. Leave empty to show all fields',
64
+ true
65
+ )
66
+ }
67
+
68
+ async function buildParamsId (ctx) {
69
+ await this.docSchemaParams(ctx, 'paramsId', 'id||Record ID')
70
+ }
71
+
72
+ async function docSchemaGeneral (ctx) {
73
+ await buildErrResp.call(this, ctx)
74
+ await buildFilter.call(this, ctx)
75
+ await buildParamsId.call(this, ctx)
76
+ await buildFields.call(this, ctx)
77
+ }
78
+
79
+ export default docSchemaGeneral
@@ -0,0 +1,8 @@
1
+ async function docSchemaLib (ctx, name, obj) {
2
+ const { merge } = this.app.bajo.lib._
3
+ if (ctx.getSchema(name)) return
4
+ const value = merge({}, obj, { $id: name })
5
+ ctx.addSchema(value)
6
+ }
7
+
8
+ export default docSchemaLib
@@ -0,0 +1,165 @@
1
+ function getType (input) {
2
+ let type = 'string'
3
+ if (['float', 'double'].includes(input)) type = 'number'
4
+ if (['boolean'].includes(input)) type = 'boolean'
5
+ if (['integer', 'smallint'].includes(input)) type = 'integer'
6
+ if (['object'].includes(input)) type = 'object'
7
+ if (['array'].includes(input)) type = 'array'
8
+ return type
9
+ }
10
+
11
+ async function buildPropsReqs ({ schema, method, options = {} }) {
12
+ const { getSchema } = this.app.dobo
13
+ const properties = {}
14
+ const required = []
15
+ const rels = {}
16
+ const hidden = [...schema.hidden, ...(options.hidden ?? [])] ?? []
17
+ for (const p of schema.properties) {
18
+ if (hidden.includes(p.name)) continue
19
+ properties[p.name] = { type: getType(p.type) }
20
+ if (!p.required) properties[p.name].nullable = true
21
+ else if (method === 'create' && p.name !== 'id') required.push(p.name)
22
+ if (['datetime'].includes(p.type)) properties[p.name].format = 'date-time'
23
+ if (p.rel) {
24
+ for (const key in p.rel) {
25
+ const val = p.rel[key]
26
+ if (val.fields.length === 0) continue
27
+ const props = { type: 'object', properties: {} }
28
+ const relschema = getSchema(val.schema)
29
+ for (const f of val.fields) {
30
+ const item = relschema.properties.find(s => s.name === f)
31
+ props.properties[item.name] = { type: getType(item.type) }
32
+ }
33
+ if (Object.keys(props.properties).length > 0) {
34
+ if (val.type === 'one-to-many') {
35
+ rels[key] = { type: 'array', items: props }
36
+ } else if (val.type === 'one-to-one') {
37
+ rels[key] = props
38
+ }
39
+ }
40
+ }
41
+ }
42
+ }
43
+ if (Object.keys(rels).length > 0) properties._rel = { type: 'object', properties: rels }
44
+ return { properties, required }
45
+ }
46
+
47
+ async function buildResponse ({ ctx, schema, method, options }) {
48
+ const { merge, cloneDeep } = this.app.bajo.lib._
49
+ const { transformResult } = this.app.waibuRestApi
50
+ const cfgWdb = this.app.waibuDb.config
51
+ const { properties } = await buildPropsReqs.call(this, { schema, method, options })
52
+
53
+ async function buildData (keys) {
54
+ const data = {}
55
+ for (const k of keys) {
56
+ const name = 'model' + schema.name
57
+ const props = cloneDeep(properties)
58
+ await this.docSchemaLib(ctx, name, {
59
+ type: 'object',
60
+ properties: props
61
+ })
62
+ data[k] = { $ref: name + '#' }
63
+ }
64
+ return data
65
+ }
66
+
67
+ const result = {
68
+ '2xx': {
69
+ description: this.print.write('Successfull response'),
70
+ type: 'object'
71
+ }
72
+ }
73
+ if (['create', 'update', 'replace'].includes(method)) {
74
+ result['4xx'] = {
75
+ description: this.print.write('Document error response'),
76
+ $ref: '4xxResp#'
77
+ }
78
+ }
79
+ result['5xx'] = {
80
+ description: this.print.write('General error response'),
81
+ $ref: '5xxResp#'
82
+ }
83
+ if (cfgWdb.dbModel.dataOnly) {
84
+ if (method === 'find') {
85
+ result['2xx'] = {
86
+ type: 'array',
87
+ items: (await buildData.call(this, ['data'])).data
88
+ }
89
+ } else if (method === 'get') result['2xx'] = (await buildData.call(this, ['data'])).data
90
+ else result['2xx'] = (await buildData.call(this, ['data'], true)).data
91
+ return result
92
+ }
93
+ const success = { type: 'boolean', default: true }
94
+ const statusCode = { type: 'integer', default: 200 }
95
+ if (method === 'get') {
96
+ result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['data']), { success, statusCode }) })
97
+ } else if (method === 'create') {
98
+ statusCode.default = 201
99
+ result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['data']), { success, statusCode }) })
100
+ } else if (['update', 'replace'].includes(method)) {
101
+ result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['data', 'oldData']), { success, statusCode }) })
102
+ } else if (method === 'remove') {
103
+ result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['oldData']), { success, statusCode }) })
104
+ } else if (method === 'find') {
105
+ result['2xx'].properties = transformResult({
106
+ data: await this.docSchemaForFind(ctx, { type: 'object', properties }),
107
+ options: { forFind: true }
108
+ })
109
+ }
110
+ return result
111
+ }
112
+
113
+ async function docSchemaModel ({ model, method, ctx, options = {} }) {
114
+ const { getInfo } = this.app.dobo
115
+ const { schema } = getInfo(model)
116
+ const { omit } = this.app.bajo.lib._
117
+ const out = {
118
+ description: options.description ?? this.docSchemaDescription(method),
119
+ tags: [this.alias.toUpperCase(), ...(options.alias ?? [])]
120
+ }
121
+ if (['find'].includes(method)) {
122
+ out.querystring = { $ref: 'qsFilter#' }
123
+ }
124
+ if (['get', 'update', 'replace', 'remove'].includes(method)) {
125
+ out.querystring = { $ref: 'qsFields#' }
126
+ if (!options.noId) out.params = { $ref: 'paramsId#' }
127
+ }
128
+ if (['update'].includes(method)) {
129
+ const { properties } = await buildPropsReqs.call(this, { schema, method, options })
130
+ const name = 'model' + schema.name + 'Update'
131
+ delete properties._rel
132
+ await this.docSchemaLib(ctx, name, {
133
+ type: 'object',
134
+ properties: omit(properties, ['id'])
135
+ })
136
+ out.body = { $ref: name + '#' }
137
+ }
138
+ if (['replace'].includes(method)) {
139
+ const { properties, required } = await buildPropsReqs.call(this, { schema, method, options })
140
+ const name = 'model' + schema.name + 'Replace'
141
+ delete properties._rel
142
+ await this.docSchemaLib(ctx, name, {
143
+ type: 'object',
144
+ properties: omit(properties, ['id']),
145
+ required
146
+ })
147
+ out.body = { $ref: name + '#' }
148
+ }
149
+ if (['create'].includes(method)) {
150
+ const { properties, required } = await buildPropsReqs.call(this, { schema, method, options })
151
+ const name = 'model' + schema.name + 'Create'
152
+ delete properties._rel
153
+ await this.docSchemaLib(ctx, name, {
154
+ type: 'object',
155
+ properties,
156
+ required
157
+ })
158
+ out.body = { $ref: name + '#' }
159
+ out.querystring = { $ref: 'qsFields#' }
160
+ }
161
+ out.response = await buildResponse.call(this, { ctx, schema, method, options })
162
+ return out
163
+ }
164
+
165
+ export default docSchemaModel
@@ -0,0 +1,28 @@
1
+ async function buildParams (ctx, paramName, ...args) {
2
+ const { each, isEmpty, keys, last, isBoolean } = this.app.bajo.lib._
3
+ const cfgWeb = this.app.waibu.config
4
+ let transform = false
5
+ if (isBoolean(last(args))) {
6
+ transform = args.pop()
7
+ }
8
+ const item = {
9
+ type: 'object',
10
+ properties: {}
11
+ }
12
+ each(args, a => {
13
+ let [name, type, description, def] = a.split('|')
14
+ if (isEmpty(type)) type = 'string'
15
+ item.properties[name] = { type, description: this.print.write(description), default: def }
16
+ })
17
+ if (transform) {
18
+ each(keys(cfgWeb.qsKey), k => {
19
+ const v = cfgWeb.qsKey[k]
20
+ if (k === v || !item.properties[k]) return undefined
21
+ item.properties[v] = item.properties[k]
22
+ delete item.properties[k]
23
+ })
24
+ }
25
+ if (!isEmpty(args)) await this.docSchemaLib(ctx, paramName, item)
26
+ }
27
+
28
+ export default buildParams
@@ -0,0 +1,15 @@
1
+ async function buildParams (ctx, paramName, ...args) {
2
+ const { each, isEmpty } = this.app.bajo.lib._
3
+ const item = {
4
+ type: 'object',
5
+ properties: {}
6
+ }
7
+ each(args, a => {
8
+ let [name, type, description] = a.split(':')
9
+ if (isEmpty(type)) type = 'string'
10
+ item.properties[name] = { type, description: this.print.write(description) }
11
+ })
12
+ if (!isEmpty(args)) await this.docSchemaLib(ctx, paramName, item)
13
+ }
14
+
15
+ export default buildParams
@@ -0,0 +1 @@
1
+ ["api"]
@@ -0,0 +1,8 @@
1
+ function routePath (name) {
2
+ const { get } = this.app.bajo.lib._
3
+ const { fullPath, ns } = this.app.bajo.breakNsPath(name)
4
+ const prefix = get(this.app[ns], 'config.waibu.prefix', this.app[ns].alias)
5
+ return `/${this.config.waibu.prefix}/${prefix}${fullPath}${this.config.format.asExt ? '.json' : ''}`
6
+ }
7
+
8
+ export default routePath
@@ -13,13 +13,13 @@ function returnError ({ data, req, reply, options = {} }) {
13
13
  const { pascalCase } = this.app.bajo
14
14
  const { last, map, kebabCase, upperFirst, keys, each, get, isEmpty } = this.app.bajo.lib._
15
15
  const cfg = this.config
16
- const cfgWeb = this.app.waibu.config
16
+ const cfgWdb = this.app.waibuDb.config
17
17
  const errNames = kebabCase(data.constructor.name).split('-')
18
18
  if (last(errNames) === 'error') errNames.pop()
19
19
  data.error = this.print.write(map(errNames, s => upperFirst(s)).join(' '))
20
20
  data.success = false
21
21
  data.statusCode = data.statusCode ?? 500
22
- if (reply && cfgWeb.dbColl.dataOnly) {
22
+ if (reply && cfgWdb.dbModel.dataOnly) {
23
23
  each(keys(data), k => {
24
24
  const key = get(cfg, `responseKey.${k}`, k)
25
25
  if (k === 'details' && !isEmpty(data[k])) data[k] = JSON.stringify(data[k])
@@ -27,7 +27,7 @@ function returnError ({ data, req, reply, options = {} }) {
27
27
  })
28
28
  }
29
29
  reply.code(data.statusCode)
30
- const result = cfgWeb.dbColl.dataOnly ? { error: data.message } : data
30
+ const result = cfgWdb.dbModel.dataOnly ? { error: data.message } : data
31
31
  return reformat.call(this, { data: result, req, reply, options })
32
32
  }
33
33
 
@@ -35,10 +35,10 @@ function returnSuccess ({ data, req, reply, options = {} }) {
35
35
  const { pascalCase } = this.app.bajo
36
36
  const { each, keys, omit, get } = this.app.bajo.lib._
37
37
  const cfg = this.config
38
- const cfgWeb = this.app.waibu.config
38
+ const cfgWdb = this.app.waibuDb.config
39
39
  if (reply) {
40
40
  reply.code(req.method.toUpperCase() === 'POST' ? 201 : 200)
41
- if (cfgWeb.dbColl.dataOnly) {
41
+ if (cfgWdb.dbModel.dataOnly) {
42
42
  each(keys(omit(data, ['data'])), k => {
43
43
  const key = get(cfg, `responseKey.${k}`, k)
44
44
  reply.header(`X-${pascalCase(this.alias)}-${pascalCase(key)}`, data[k])
package/lib/decorate.js CHANGED
@@ -1,5 +1,5 @@
1
1
  async function decorate (ctx) {
2
- ctx.decorateRequest('i18n', null)
2
+ // ctx.decorateRequest('i18n', null)
3
3
  }
4
4
 
5
5
  export default decorate
package/lib/error.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { handler } from './not-found.js'
2
2
 
3
- const extHandler = async function (ctx, err, req, reply) {
3
+ const extHandler = async function (err, req, reply, ctx) {
4
4
  const code = err.statusCode ?? 500
5
5
  const msg = err.message
6
- if (msg === 'notfound') {
7
- return handler.call(this, ctx, req, reply)
6
+ if (msg === 'notFound') {
7
+ return handler.call(this, req, reply, ctx)
8
8
  }
9
9
  const data = ctx.httpErrors.createError(code, msg)
10
10
  data.statusCode = code
@@ -1,28 +1,27 @@
1
1
  import path from 'path'
2
2
  import serveRoute from './serve-route.js'
3
3
 
4
- async function routeByCollBuilder ({ file, ctx, dir, pathPrefix, ns }) {
4
+ async function routeByModelBuilder ({ file, ctx, dir, pathPrefix, ns, parent }) {
5
5
  const { getPlugin } = this.app.bajo
6
6
  getPlugin('dobo') // ensure dobo is loaded
7
7
  const { readConfig, parseObject, isSet } = this.app.bajo
8
- const { methodMap, getParams } = this.app.waibu
8
+ const { methodMap, getParams } = this.app.waibuDb
9
9
  const { getInfo } = this.app.dobo
10
10
  const { camelCase, omit, merge, keys } = this.app.bajo.lib._
11
11
  const builder = await readConfig(file, { ns, ignoreError: true })
12
- const { schema } = getInfo(builder.coll)
12
+ const { schema } = getInfo(builder.model)
13
13
  const url = path.dirname(file).replace(`${dir}/${pathPrefix}`, '').replaceAll('@', ':')
14
14
  const methods = keys(methodMap)
15
15
  if (this.config.enablePatch) methods.push('replace')
16
16
  const me = this
17
17
  const mods = []
18
- const swagger = this.app.waibuSwagger
19
18
  for (const method of methods) {
20
19
  let disabled = schema.disabled.includes(method) || (builder.disabled ?? []).includes(method)
21
20
  if (method === 'replace' && (schema.disabled.includes('update') || (builder.disabled ?? []).includes('update'))) disabled = true
22
21
  if (disabled) continue
23
- const mod = omit(builder, ['coll', 'url', 'method', 'handler', 'hidden', ...methods])
22
+ const mod = omit(builder, ['model', 'url', 'method', 'handler', 'hidden', ...methods])
24
23
  const customMod = builder[method] ?? {}
25
- if (!customMod.schema && swagger) customMod.schema = await swagger.docSchemaColl({ coll: builder.coll, method, ctx, options: { hidden: builder.hidden } })
24
+ if (!customMod.schema) customMod.schema = await this.docSchemaModel({ model: builder.model, method, ctx, options: { hidden: builder.hidden } })
26
25
  let mapmethod = methodMap[method]
27
26
  if (this.config.enablePatch) {
28
27
  if (method === 'replace') mapmethod = 'PUT'
@@ -32,17 +31,18 @@ async function routeByCollBuilder ({ file, ctx, dir, pathPrefix, ns }) {
32
31
  url: ['get', 'update', 'replace', 'remove'].includes(method) ? `${url}/:id` : url,
33
32
  method: mapmethod,
34
33
  handler: async function (req, reply) {
35
- const helper = me.app.waibu[camelCase(`record ${method === 'replace' ? 'update' : method}`)]
34
+ const helper = me.app.waibuDb[camelCase(`record ${method === 'replace' ? 'update' : method}`)]
36
35
  let { fields, count } = getParams(req)
37
36
  let rels = []
38
- const headers = parseObject(req.headers, true, true)
37
+ const headers = parseObject(req.headers, { parseValue: true })
39
38
  if (isSet(headers['x-count'])) count = headers['x-count']
40
39
  if (isSet(headers['x-rels'])) rels = headers['x-rels']
41
40
  if (typeof rels === 'string' && !['*', 'all'].includes(rels)) rels = [rels]
42
41
  const options = { fields, count, rels }
43
42
  options.hidden = builder.hidden ?? []
43
+ options.queryHandler = builder.queryHandler
44
44
  if (method === 'replace') options.partial = false
45
- const data = await helper({ coll: builder.coll, req, reply, ctx: this, options })
45
+ const data = await helper({ model: builder.model, req, reply, ctx: this, options })
46
46
  data.success = true
47
47
  data.statusCode = method === 'create' ? 201 : 200
48
48
  if (method === 'find') options.forFind = true
@@ -52,9 +52,9 @@ async function routeByCollBuilder ({ file, ctx, dir, pathPrefix, ns }) {
52
52
  if (builder.schema === false) delete mod.schema
53
53
  mod.config = mod.config ?? {}
54
54
  mod.config.pathSrc = url
55
- mods.push(await serveRoute.call(me, { mod, ns }))
55
+ mods.push(await serveRoute.call(me, { mod, ns, parent }))
56
56
  }
57
57
  return mods
58
58
  }
59
59
 
60
- export default routeByCollBuilder
60
+ export default routeByModelBuilder
@@ -1,9 +1,9 @@
1
1
  import path from 'path'
2
2
  import serveRoute from './serve-route.js'
3
3
 
4
- async function routeByVerb ({ file, ctx, appCtx, dir, pathPrefix, ns, alias }) {
4
+ async function routeByVerb ({ file, ctx, appCtx, dir, pathPrefix, ns, alias, parent }) {
5
5
  const { importModule, parseObject, isSet } = this.app.bajo
6
- const { methodMap, getParams } = this.app.waibu
6
+ const { methodMap, getParams } = this.app.waibuDb
7
7
  const { isFunction, merge } = this.app.bajo.lib._
8
8
  const me = this
9
9
  const url = path.dirname(file).replace(`${dir}/${pathPrefix}`, '')
@@ -21,9 +21,8 @@ async function routeByVerb ({ file, ctx, appCtx, dir, pathPrefix, ns, alias }) {
21
21
  }
22
22
  mod.url = mod.url ?? url
23
23
  mod.method = method
24
- const swagger = this.app.waibuSwagger
25
24
  const defSchema = {
26
- description: swagger ? swagger.docSchemaDescription(action) : undefined,
25
+ description: this.docSchemaDescription(action),
27
26
  tags: [alias.toUpperCase()],
28
27
  response: {}
29
28
  }
@@ -44,22 +43,23 @@ async function routeByVerb ({ file, ctx, appCtx, dir, pathPrefix, ns, alias }) {
44
43
  mod.handler = async function (req, reply) {
45
44
  let { fields, count } = getParams(req)
46
45
  let rels = []
47
- const headers = parseObject(req.headers, true, true)
46
+ const headers = parseObject(req.headers, { parseValue: true })
48
47
  if (isSet(headers['x-count'])) count = headers['x-count']
49
48
  if (isSet(headers['x-rels'])) rels = headers['x-rels']
50
49
  if (typeof rels === 'string' && !['*', 'all'].includes(rels)) rels = [rels]
51
50
  const options = { fields, count, rels }
52
51
  if (method === 'find') options.forFind = true
53
52
  if (method === 'replace') options.partial = false
54
- const data = await oldHandler.call(me, this, req, reply, options)
53
+ const data = await oldHandler.call(me.app[ns], req, reply, options, this)
55
54
  if (!data) return
56
55
  data.success = true
57
56
  data.statusCode = method === 'create' ? 201 : 200
58
- return this.transformResult({ data, req, reply, options })
57
+ return me.transformResult({ data, req, reply, options })
59
58
  }
59
+ if (mod.schema === false) delete mod.schema
60
60
  mod.config = mod.config ?? {}
61
61
  mod.config.pathSrc = url
62
- return serveRoute.call(me, { mod, ns })
62
+ return serveRoute.call(me, { mod, ns, parent })
63
63
  }
64
64
 
65
65
  export default routeByVerb
@@ -1,17 +1,18 @@
1
1
  async function serveRoute ({ mod, ns, parent }) {
2
- const { defaultsDeep } = this.app.bajo
3
- const { mergeRouteHooks } = this.app.waibu
2
+ const { defaultsDeep, importModule } = this.app.bajo
3
+ const { getPluginPrefix } = this.app.waibu
4
4
  const { pick } = this.app.bajo.lib._
5
- const cfgWeb = this.app.waibu.config
5
+ const mergeRouteHooks = await importModule('waibu:/lib/webapp-scope/merge-route-hooks.js')
6
+ const cfgWdb = this.app.waibuDb.config
6
7
  mod.config = mod.config ?? {}
7
- mod.config.webApp = this.name
8
- mod.config.ns = parent ?? ns
8
+ mod.config.webApp = parent ?? ns
9
+ mod.config.ns = ns
9
10
  mod.config.title = mod.title
10
- if (parent) mod.config.subRouteOf = ns
11
+ mod.config.prefix = getPluginPrefix(ns)
11
12
  delete mod.title
12
- if (mod.method === 'PUT' && cfgWeb.dbColl.patchEnabled) mod.method = [mod.method, 'PATCH']
13
+ if (mod.method === 'PUT' && cfgWdb.dbModel.patchEnabled) mod.method = [mod.method, 'PATCH']
13
14
  mod = defaultsDeep(pick(this.config, ['exposeHeadRoute', 'bodyLimit']), mod)
14
- await mergeRouteHooks(mod, false)
15
+ await mergeRouteHooks.call(this, mod, false) // Don't include handler, hence 'false'
15
16
  return mod
16
17
  }
17
18
 
package/lib/sub-app.js CHANGED
@@ -1,10 +1,14 @@
1
1
  async function subApp (ctx) {
2
- const { importModule } = this.app.bajo
2
+ const { importModule, runHook } = this.app.bajo
3
3
  const { collect } = await importModule('waibu:/lib/app.js', { asDefaultImport: false })
4
4
  const mods = await collect.call(this.app[this.name], 'boot.js', 'waibuRestApi')
5
5
  for (const m of mods) {
6
6
  this.log.debug('Boot sub app: %s', m.ns)
7
- await m.handler.call(this.app[m.ns], ctx)
7
+ await ctx.register(async (subCtx) => {
8
+ this.app[m.ns].instance = subCtx
9
+ await runHook(`${this.name}.${m.alias}:afterCreateContext`, subCtx)
10
+ await m.handler.call(this.app[m.ns], subCtx, m.prefix)
11
+ }, { prefix: m.prefix })
8
12
  }
9
13
  }
10
14
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "waibu-rest-api",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "REST API for Waibu",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -12,7 +12,10 @@
12
12
  "url": "git+https://github.com/ardhi/waibu-rest-api.git"
13
13
  },
14
14
  "keywords": [
15
+ "api",
16
+ "restful",
15
17
  "restapi",
18
+ "waibu",
16
19
  "web",
17
20
  "webserver",
18
21
  "bajo",
package/waibu/boot.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import path from 'path'
2
2
  import decorate from '../lib/decorate.js'
3
- import routeByCollBuilder from '../lib/route-by-coll-builder.js'
3
+ import routeByModelBuilder from '../lib/route-by-model-builder.js'
4
4
  import routeByVerb from '../lib/route-by-verb.js'
5
5
  import notFound from '../lib/not-found.js'
6
6
  import error from '../lib/error.js'
7
7
  import subApp from '../lib/sub-app.js'
8
8
  import handleResponse from '../lib/handle-response.js'
9
9
 
10
- const routeActions = { routeByCollBuilder, routeByVerb }
10
+ const routeActions = { routeByModelBuilder, routeByVerb }
11
11
 
12
12
  function formatExt (item) {
13
13
  return item + '.:format'
@@ -15,14 +15,11 @@ function formatExt (item) {
15
15
 
16
16
  const boot = {
17
17
  level: 10,
18
- handler: async function () {
18
+ handler: async function (ctx, prefix) {
19
19
  const { importPkg, eachPlugins, importModule, runHook } = this.app.bajo
20
20
  const { fastGlob } = this.app.bajo.lib
21
+ const { getPluginPrefix } = this.app.waibu
21
22
  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
23
  const routeHook = await importModule('waibu:/lib/webapp-scope/route-hook.js')
27
24
  const handleMultipart = await importModule('waibu:/lib/webapp-scope/handle-multipart-body.js')
28
25
  const handleXmlBody = await importModule('waibu:/lib/handle-xml-body.js')
@@ -31,64 +28,64 @@ const boot = {
31
28
  const handleCompress = await importModule('waibu:/lib/webapp-scope/handle-compress.js')
32
29
  const handleRateLimit = await importModule('waibu:/lib/webapp-scope/handle-rate-limit.js')
33
30
  const reroutedPath = await importModule('waibu:/lib/webapp-scope/rerouted-path.js')
31
+
32
+ const pathPrefix = `${this.name}/route`
33
+ await this.docSchemaGeneral(ctx)
34
+ await routeHook.call(this, this.name)
35
+ await decorate.call(this, ctx)
36
+ if (this.config.format.supported.includes('xml')) {
37
+ await handleXmlBody.call(this, ctx, this.config.format.xml.bodyParser)
38
+ }
39
+ await ctx.register(accepts)
40
+ await ctx.register(bodyParser)
41
+ await handleRateLimit.call(this, ctx, this.config.rateLimit)
42
+ await handleCors.call(this, ctx, this.config.cors)
43
+ await handleHelmet.call(this, ctx, this.config.helmet)
44
+ await handleMultipart.call(this, ctx, this.config.multipart)
45
+ await handleCompress.call(this, ctx, this.config.compress)
46
+ await handleResponse.call(this, ctx)
47
+ await error.call(this, ctx)
48
+ await runHook(`${this.name}:beforeCreateRoutes`, ctx)
49
+ const actions = ['find', 'get', 'create', 'update', 'remove']
50
+ if (this.config.enablePatch) actions.push('replace')
34
51
  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)
52
+
53
+ await eachPlugins(async function ({ dir, alias, ns }) {
54
+ const appPrefix = '/' + (ns === me.app.bajo.mainNs && me.config.mountMainAsRoot ? '' : getPluginPrefix(ns))
55
+ const pattern = [
56
+ `${dir}/${pathPrefix}/**/{${actions.join(',')}}.js`,
57
+ `${dir}/${pathPrefix}/**/model-builder.*`
58
+ ]
59
+ const files = await fastGlob(pattern)
60
+ if (files.length === 0) return undefined
61
+ await ctx.register(async (appCtx) => {
62
+ for (const file of files) {
63
+ const base = path.basename(file, path.extname(file))
64
+ const action = base === 'model-builder' ? 'routeByModelBuilder' : 'routeByVerb'
65
+ let mods = await routeActions[action].call(me, { file, appCtx, ctx, dir, pathPrefix, ns, alias, parent: me.name })
66
+ if (!Array.isArray(mods)) mods = [mods]
67
+ for (const mod of mods) {
68
+ const fullPath = appPrefix === '/' ? mod.url : (appPrefix + mod.url)
69
+ const isRouteDisabled = await importModule('waibu:/lib/webapp-scope/is-route-disabled.js')
70
+ if (await isRouteDisabled.call(this, fullPath, mod.method, me.config.disabled)) {
71
+ this.log.warn('Route %s (%s) is disabled', `${prefix}${fullPath}`, mod.method)
72
+ continue
84
73
  }
74
+ const rpath = await reroutedPath.call(this, fullPath, me.config.rerouted)
75
+ if (me.config.format.asExt) mod.url = formatExt(mod.url)
76
+ if (rpath) {
77
+ mod.config.pathReroutedTo = rpath
78
+ this.log.warn('Rerouted %s -> %s', `${prefix}${fullPath}`, `${prefix}${rpath}`)
79
+ mod.url = me.config.format.asExt ? formatExt(rpath) : rpath
80
+ await ctx.route(mod)
81
+ } else await appCtx.route(mod)
85
82
  }
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 })
83
+ }
84
+ }, { prefix: appPrefix })
85
+ })
86
+ await runHook(`${this.name}:afterCreateRoutes`, ctx)
87
+ await subApp.call(this, ctx)
88
+ await notFound.call(this, ctx)
92
89
  }
93
90
  }
94
91
 
@@ -1,6 +0,0 @@
1
- async function bajoI18nBeforeInit () {
2
- const config = this.app.bajoI18N.config
3
- if (!config.fallbackNS.includes(this.name)) config.fallbackNS.push(this.name)
4
- }
5
-
6
- export default bajoI18nBeforeInit