waibu-rest-api 2.14.1 → 2.14.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.
Files changed (50) hide show
  1. package/.github/FUNDING.yml +0 -0
  2. package/.github/workflows/repo-lockdown.yml +0 -0
  3. package/.jsdoc.conf.json +0 -0
  4. package/LICENSE +0 -0
  5. package/README.md +0 -0
  6. package/docs/WaibuRestApi.html +0 -0
  7. package/docs/data/search.json +0 -0
  8. package/docs/fonts/Inconsolata-Regular.ttf +0 -0
  9. package/docs/fonts/OpenSans-Regular.ttf +0 -0
  10. package/docs/fonts/WorkSans-Bold.ttf +0 -0
  11. package/docs/global.html +0 -0
  12. package/docs/index.html +0 -0
  13. package/docs/index.js.html +0 -0
  14. package/docs/lib_config.js.html +0 -0
  15. package/docs/scripts/core.js +0 -0
  16. package/docs/scripts/core.min.js +0 -0
  17. package/docs/scripts/resize.js +0 -0
  18. package/docs/scripts/search.js +0 -0
  19. package/docs/scripts/search.min.js +5 -5
  20. package/docs/scripts/third-party/Apache-License-2.0.txt +0 -0
  21. package/docs/scripts/third-party/fuse.js +0 -0
  22. package/docs/scripts/third-party/hljs-line-num-original.js +0 -0
  23. package/docs/scripts/third-party/hljs-line-num.js +0 -0
  24. package/docs/scripts/third-party/hljs-original.js +0 -0
  25. package/docs/scripts/third-party/hljs.js +0 -0
  26. package/docs/scripts/third-party/popper.js +0 -0
  27. package/docs/scripts/third-party/tippy.js +0 -0
  28. package/docs/scripts/third-party/tocbot.js +0 -0
  29. package/docs/scripts/third-party/tocbot.min.js +0 -0
  30. package/docs/static/bitcoin.jpeg +0 -0
  31. package/docs/static/home.md +0 -0
  32. package/docs/static/logo-ecosystem.png +0 -0
  33. package/docs/static/logo.png +0 -0
  34. package/docs/styles/clean-jsdoc-theme-base.css +0 -0
  35. package/docs/styles/clean-jsdoc-theme-dark.css +0 -0
  36. package/docs/styles/clean-jsdoc-theme-light.css +0 -0
  37. package/docs/styles/clean-jsdoc-theme-scrollbar.css +0 -0
  38. package/docs/styles/clean-jsdoc-theme-without-scrollbar.min.css +0 -0
  39. package/docs/styles/clean-jsdoc-theme.min.css +0 -0
  40. package/extend/bajo/hook.js +25 -25
  41. package/extend/bajo/intl/en-US.json +0 -0
  42. package/extend/bajo/intl/id.json +0 -0
  43. package/extend/waibu/webapp/boot.js +0 -0
  44. package/index.js +2 -2
  45. package/lib/config.js +90 -90
  46. package/lib/helper.js +161 -161
  47. package/package.json +1 -1
  48. package/wiki/CHANGES.md +99 -95
  49. package/wiki/CONFIG.md +0 -0
  50. package/wiki/CONTRIBUTING.md +0 -0
File without changes
File without changes
package/.jsdoc.conf.json CHANGED
File without changes
package/LICENSE CHANGED
File without changes
package/README.md CHANGED
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
package/docs/global.html CHANGED
File without changes
package/docs/index.html CHANGED
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -1,6 +1,6 @@
1
- const searchId="LiBfqbJVcV",searchHash="#"+searchId,searchContainer=document.querySelector("#PkfLWpAbet"),searchWrapper=document.querySelector("#iCxFxjkHbP"),searchCloseButton=document.querySelector("#VjLlGakifb"),searchInput=document.querySelector("#vpcKVYIppa"),resultBox=document.querySelector("#fWwVHRuDuN");function showResultText(e){resultBox.innerHTML=`<span class="search-result-c-text">${e}</span>`}function hideSearch(){window.location.hash===searchHash&&history.go(-1),window.onhashchange=null,searchContainer&&(searchContainer.style.display="none")}function listenCloseKey(e){"Escape"===e.key&&(hideSearch(),window.removeEventListener("keyup",listenCloseKey))}function showSearch(){try{hideMobileMenu()}catch(e){console.error(e)}window.onhashchange=hideSearch,window.location.hash!==searchHash&&history.pushState(null,null,searchHash),searchContainer&&(searchContainer.style.display="flex",window.addEventListener("keyup",listenCloseKey)),searchInput&&searchInput.focus()}async function fetchAllData(){var{hostname:e,protocol:t,port:n}=location,t=t+"//"+e+(""!==n?":"+n:"")+baseURL,e=new URL("data/search.json",t);const a=await fetch(e);n=(await a.json()).list;return n}function onClickSearchItem(t){const n=t.currentTarget;if(n){const a=n.getAttribute("href")||"";t=a.split("#")[1]||"";let e=document.getElementById(t);e||(t=decodeURI(t),e=document.getElementById(t)),e&&setTimeout(function(){bringElementIntoView(e)},100)}}function buildSearchResult(e){let t="";var n=/(<([^>]+)>)/gi;for(const s of e){const{title:c="",description:i=""}=s.item;var a=s.item.link.replace('<a href="',"").replace(/">.*/,""),o=c.replace(n,""),r=i.replace(n,"");t+=`
2
- <a onclick="onClickSearchItem(event)" href="${a}" class="search-result-item">
3
- <div class="search-result-item-title">${o}</div>
4
- <div class="search-result-item-p">${r||"No description available."}</div>
5
- </a>
1
+ const searchId="LiBfqbJVcV",searchHash="#"+searchId,searchContainer=document.querySelector("#PkfLWpAbet"),searchWrapper=document.querySelector("#iCxFxjkHbP"),searchCloseButton=document.querySelector("#VjLlGakifb"),searchInput=document.querySelector("#vpcKVYIppa"),resultBox=document.querySelector("#fWwVHRuDuN");function showResultText(e){resultBox.innerHTML=`<span class="search-result-c-text">${e}</span>`}function hideSearch(){window.location.hash===searchHash&&history.go(-1),window.onhashchange=null,searchContainer&&(searchContainer.style.display="none")}function listenCloseKey(e){"Escape"===e.key&&(hideSearch(),window.removeEventListener("keyup",listenCloseKey))}function showSearch(){try{hideMobileMenu()}catch(e){console.error(e)}window.onhashchange=hideSearch,window.location.hash!==searchHash&&history.pushState(null,null,searchHash),searchContainer&&(searchContainer.style.display="flex",window.addEventListener("keyup",listenCloseKey)),searchInput&&searchInput.focus()}async function fetchAllData(){var{hostname:e,protocol:t,port:n}=location,t=t+"//"+e+(""!==n?":"+n:"")+baseURL,e=new URL("data/search.json",t);const a=await fetch(e);n=(await a.json()).list;return n}function onClickSearchItem(t){const n=t.currentTarget;if(n){const a=n.getAttribute("href")||"";t=a.split("#")[1]||"";let e=document.getElementById(t);e||(t=decodeURI(t),e=document.getElementById(t)),e&&setTimeout(function(){bringElementIntoView(e)},100)}}function buildSearchResult(e){let t="";var n=/(<([^>]+)>)/gi;for(const s of e){const{title:c="",description:i=""}=s.item;var a=s.item.link.replace('<a href="',"").replace(/">.*/,""),o=c.replace(n,""),r=i.replace(n,"");t+=`
2
+ <a onclick="onClickSearchItem(event)" href="${a}" class="search-result-item">
3
+ <div class="search-result-item-title">${o}</div>
4
+ <div class="search-result-item-p">${r||"No description available."}</div>
5
+ </a>
6
6
  `}return t}function getSearchResult(e,t,n){var t={...{shouldSort:!0,threshold:.4,location:0,distance:100,maxPatternLength:32,minMatchCharLength:1,keys:t}},a=Fuse.createIndex(t.keys,e);const o=new Fuse(e,t,a),r=o.search(n);return 20<r.length?r.slice(0,20):r}function debounce(t,n,a){let o;return function(){const e=arguments;clearTimeout(o),o=setTimeout(()=>{o=null,a||t.apply(this,e)},n),a&&!o&&t.apply(this,e)}}let searchData;async function search(e){e=e.target.value;if(resultBox)if(e){if(!searchData){showResultText("Loading...");try{searchData=await fetchAllData()}catch(e){return console.log(e),void showResultText("Failed to load result.")}}e=getSearchResult(searchData,["title","description"],e);e.length?resultBox.innerHTML=buildSearchResult(e):showResultText("No result found! Try some different combination.")}else showResultText("Type anything to view search result");else console.error("Search result container not found")}function onDomContentLoaded(){const e=document.querySelectorAll(".search-button");var t=debounce(search,300);searchCloseButton&&searchCloseButton.addEventListener("click",hideSearch),e&&e.forEach(function(e){e.addEventListener("click",showSearch)}),searchContainer&&searchContainer.addEventListener("click",hideSearch),searchWrapper&&searchWrapper.addEventListener("click",function(e){e.stopPropagation()}),searchInput&&searchInput.addEventListener("keyup",t),window.location.hash===searchHash&&showSearch()}window.addEventListener("DOMContentLoaded",onDomContentLoaded),window.addEventListener("hashchange",function(){window.location.hash===searchHash&&showSearch()});
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -1,25 +1,25 @@
1
- async function hook () {
2
- return [{
3
- level: 9,
4
- name: 'waibuRestApi:preParsing',
5
- handler: async function (req, reply) {
6
- const { importModule } = this.app.bajo
7
- const { attachIntl } = await importModule('waibu:/lib/webapp.js', { asDefaultImport: false })
8
- await attachIntl.call(this, this.config.intl.detectors, req, reply)
9
- reply.header('Content-Language', req.lang)
10
- if (this.config.format.asExt && req.params.format) {
11
- if (!this.config.format.supported.includes(req.params.format)) {
12
- throw this.error('unsupportedFormat%s', req.params.format, { statusCode: 406 })
13
- }
14
- }
15
- }
16
- }, {
17
- name: 'waibu:afterInit',
18
- handler: async function () {
19
- this.app.waibu.config.paramsCharMap[this.config.mapSlash] = '/'
20
- // this.app.waibu.config.paramsCharMap[this.config.mapDot] = '.'
21
- }
22
- }]
23
- }
24
-
25
- export default hook
1
+ async function hook () {
2
+ return [{
3
+ level: 9,
4
+ name: 'waibuRestApi:preParsing',
5
+ handler: async function (req, reply) {
6
+ const { importModule } = this.app.bajo
7
+ const { attachIntl } = await importModule('waibu:/lib/webapp.js', { asDefaultImport: false })
8
+ await attachIntl.call(this, this.config.intl.detectors, req, reply)
9
+ reply.header('Content-Language', req.lang)
10
+ if (this.config.format.asExt && req.params.format) {
11
+ if (!this.config.format.supported.includes(req.params.format)) {
12
+ throw this.error('unsupportedFormat%s', req.params.format, { statusCode: 406 })
13
+ }
14
+ }
15
+ }
16
+ }, {
17
+ name: 'waibu:afterInit',
18
+ handler: async function () {
19
+ this.app.waibu.config.paramsCharMap[this.config.mapSlash] = '/'
20
+ // this.app.waibu.config.paramsCharMap[this.config.mapDot] = '.'
21
+ }
22
+ }]
23
+ }
24
+
25
+ export default hook
File without changes
File without changes
File without changes
package/index.js CHANGED
@@ -492,7 +492,7 @@ async function factory (pkgName) {
492
492
  const { readConfig } = this.app.bajo
493
493
  const { pascalCase } = this.app.lib.aneka
494
494
  const { methodMap, getParams } = this.app.waibuDb
495
- const { isFunction, camelCase, omit, merge, keys, filter } = this.app.lib._
495
+ const { isFunction, omit, merge, keys, filter } = this.app.lib._
496
496
  const builder = await readConfig(file, { ns, ignoreError: true })
497
497
  builder.disabled = builder.disabled ?? []
498
498
  let url = path.dirname(file).replace(`${dir}/extend/${pathPrefix}`, '').replaceAll('@', ':')
@@ -553,7 +553,7 @@ async function factory (pkgName) {
553
553
  url: `${url}/stat/:stat`,
554
554
  handler: async function (req, reply) {
555
555
  if (!supported.includes(req.params.stat)) throw me.error('_notFound')
556
- const helper = me.app.waibuDb[camelCase(`create ${req.params.stat}`)]
556
+ const helper = me.app.waibuDb[req.params.stat]
557
557
  if (!helper) throw me.error('_notFound')
558
558
  const options = { queryHandler: builder.queryHandler }
559
559
  const model = builder.model.startsWith(':') ? pascalCase(req.params[builder.model.slice(1)]) : builder.model
package/lib/config.js CHANGED
@@ -1,90 +1,90 @@
1
- /**
2
- * @typedef {Object} TConfig
3
- * @property {Object} [waibu={}] - Waibu configuration
4
- * @property {string} [waibu.prefix='api'] - Prefix for the Waibu REST API routes
5
- * @property {boolean} [mountMainAsRoot=true] - Whether to mount the main route as root
6
- * @property {boolean} [exposeHead=true] - Whether to expose the HEAD method
7
- * @property {boolean} [enablePatch=false] - Whether to enable the PATCH method
8
- * @property {number} [bodyLimit=1048576] - Maximum size of the request body in bytes
9
- * @property {Object} [intl={}] - Internationalization configuration
10
- * @property {Array<string>} [intl.detectors=['qs', 'header']] - List of detectors for internationalization
11
- * @property {Object} [format={}] - Format configuration
12
- * @property {Array<string>} [format.supported=['json', 'xml']] - List of supported formats (e.g., 'json', 'xml')
13
- * @property {boolean} [format.asExt=false] - Whether to use file extensions for format detection
14
- * @property {Object} [format.xml={}] - XML format configuration
15
- * @property {Object} [format.xml.bodyParser={}] - XML body parser configuration
16
- * @property {Array<string>} [format.xml.bodyParser.contentTypes=['text/xml', 'application/xml', 'application/rss+xml']] - List of content types for XML body parsing
17
- * @property {boolean} [format.xml.bodyParser.validate=false] - Whether to validate XML body
18
- * @property {Object} [format.xml.response={}] - XML response configuration
19
- * @property {string} [format.xml.response.wrapper='doc'] - Wrapper element for XML response
20
- * @property {boolean} [format.xml.response.declaration=true] - Whether to include XML declaration in response
21
- * @property {boolean} [format.xml.response.valueAsAttributes=true] - Whether to treat values as attributes in XML response
22
- * @property {Object} [responseKey={}] - Response key mapping configuration
23
- * @property {string} [responseKey.data='data'] - Key for data in the response
24
- * @property {string} [responseKey.oldData='oldData'] - Key for old data in the response
25
- * @property {string} [responseKey.page='page'] - Key for page number in the response
26
- * @property {string} [responseKey.count='count'] - Key for count
27
- * @property {string} [responseKey.pages='pages'] - Key for total pages
28
- * @property {string} [responseKey.success='success'] - Key for success status
29
- * @property {string} [responseKey.statusCode='code'] - Key for status code
30
- * @property {string} [responseKey.error='error'] - Key for error message
31
- * @property {string} [responseKey.cached='cached'] - Key for cached status
32
- * @property {string} [responseKey.hardCapped='hardCapped'] - Key for hard capped status
33
- * @property {string} [responseKey.message='message'] - Key for message
34
- * @property {string} [responseKey.warnings='warnings'] - Key for warnings
35
- * @property {string} [responseKey.details='details'] - Key for details
36
- */
37
- const config = {
38
- waibu: {
39
- prefix: 'api'
40
- },
41
- mountMainAsRoot: true,
42
- exposeHead: true,
43
- enablePatch: false,
44
- bodyLimit: 1048576,
45
- intl: {
46
- detectors: ['qs', 'header']
47
- },
48
- format: {
49
- supported: ['json', 'xml'],
50
- asExt: false,
51
- xml: {
52
- bodyParser: {
53
- contentTypes: ['text/xml', 'application/xml', 'application/rss+xml'],
54
- validate: false
55
- },
56
- response: {
57
- wrapper: 'doc',
58
- declaration: true,
59
- valueAsAttributes: true
60
- }
61
- }
62
- },
63
- responseKey: {
64
- data: 'data',
65
- oldData: 'oldData',
66
- page: 'page',
67
- count: 'count',
68
- pages: 'pages',
69
- success: 'success',
70
- statusCode: 'code',
71
- error: 'error',
72
- cached: 'cached',
73
- hardCapped: 'hardCapped',
74
- message: 'message',
75
- warnings: 'warnings',
76
- details: 'details'
77
- },
78
- mapSlash: '~',
79
- mapDot: ',',
80
- multipart: {
81
- },
82
- cors: {},
83
- helmet: {},
84
- compress: false,
85
- rateLimit: false,
86
- disabled: [],
87
- rerouted: {}
88
- }
89
-
90
- export default config
1
+ /**
2
+ * @typedef {Object} TConfig
3
+ * @property {Object} [waibu={}] - Waibu configuration
4
+ * @property {string} [waibu.prefix='api'] - Prefix for the Waibu REST API routes
5
+ * @property {boolean} [mountMainAsRoot=true] - Whether to mount the main route as root
6
+ * @property {boolean} [exposeHead=true] - Whether to expose the HEAD method
7
+ * @property {boolean} [enablePatch=false] - Whether to enable the PATCH method
8
+ * @property {number} [bodyLimit=1048576] - Maximum size of the request body in bytes
9
+ * @property {Object} [intl={}] - Internationalization configuration
10
+ * @property {Array<string>} [intl.detectors=['qs', 'header']] - List of detectors for internationalization
11
+ * @property {Object} [format={}] - Format configuration
12
+ * @property {Array<string>} [format.supported=['json', 'xml']] - List of supported formats (e.g., 'json', 'xml')
13
+ * @property {boolean} [format.asExt=false] - Whether to use file extensions for format detection
14
+ * @property {Object} [format.xml={}] - XML format configuration
15
+ * @property {Object} [format.xml.bodyParser={}] - XML body parser configuration
16
+ * @property {Array<string>} [format.xml.bodyParser.contentTypes=['text/xml', 'application/xml', 'application/rss+xml']] - List of content types for XML body parsing
17
+ * @property {boolean} [format.xml.bodyParser.validate=false] - Whether to validate XML body
18
+ * @property {Object} [format.xml.response={}] - XML response configuration
19
+ * @property {string} [format.xml.response.wrapper='doc'] - Wrapper element for XML response
20
+ * @property {boolean} [format.xml.response.declaration=true] - Whether to include XML declaration in response
21
+ * @property {boolean} [format.xml.response.valueAsAttributes=true] - Whether to treat values as attributes in XML response
22
+ * @property {Object} [responseKey={}] - Response key mapping configuration
23
+ * @property {string} [responseKey.data='data'] - Key for data in the response
24
+ * @property {string} [responseKey.oldData='oldData'] - Key for old data in the response
25
+ * @property {string} [responseKey.page='page'] - Key for page number in the response
26
+ * @property {string} [responseKey.count='count'] - Key for count
27
+ * @property {string} [responseKey.pages='pages'] - Key for total pages
28
+ * @property {string} [responseKey.success='success'] - Key for success status
29
+ * @property {string} [responseKey.statusCode='code'] - Key for status code
30
+ * @property {string} [responseKey.error='error'] - Key for error message
31
+ * @property {string} [responseKey.cached='cached'] - Key for cached status
32
+ * @property {string} [responseKey.hardCapped='hardCapped'] - Key for hard capped status
33
+ * @property {string} [responseKey.message='message'] - Key for message
34
+ * @property {string} [responseKey.warnings='warnings'] - Key for warnings
35
+ * @property {string} [responseKey.details='details'] - Key for details
36
+ */
37
+ const config = {
38
+ waibu: {
39
+ prefix: 'api'
40
+ },
41
+ mountMainAsRoot: true,
42
+ exposeHead: true,
43
+ enablePatch: false,
44
+ bodyLimit: 1048576,
45
+ intl: {
46
+ detectors: ['qs', 'header']
47
+ },
48
+ format: {
49
+ supported: ['json', 'xml'],
50
+ asExt: false,
51
+ xml: {
52
+ bodyParser: {
53
+ contentTypes: ['text/xml', 'application/xml', 'application/rss+xml'],
54
+ validate: false
55
+ },
56
+ response: {
57
+ wrapper: 'doc',
58
+ declaration: true,
59
+ valueAsAttributes: true
60
+ }
61
+ }
62
+ },
63
+ responseKey: {
64
+ data: 'data',
65
+ oldData: 'oldData',
66
+ page: 'page',
67
+ count: 'count',
68
+ pages: 'pages',
69
+ success: 'success',
70
+ statusCode: 'code',
71
+ error: 'error',
72
+ cached: 'cached',
73
+ hardCapped: 'hardCapped',
74
+ message: 'message',
75
+ warnings: 'warnings',
76
+ details: 'details'
77
+ },
78
+ mapSlash: '~',
79
+ mapDot: ',',
80
+ multipart: {
81
+ },
82
+ cors: {},
83
+ helmet: {},
84
+ compress: false,
85
+ rateLimit: false,
86
+ disabled: [],
87
+ rerouted: {}
88
+ }
89
+
90
+ export default config
package/lib/helper.js CHANGED
@@ -1,161 +1,161 @@
1
- export function extractHeaders (req, options) {
2
- const { parseObject } = this.app.lib
3
- const { isSet } = this.app.lib.aneka
4
- options.count = true
5
- options.refs = []
6
- const headers = parseObject(req.headers, { parseValue: true })
7
- if (headers['x-no-count']) options.count = false
8
- if (isSet(headers['x-refs'])) options.refs = headers['x-refs']
9
- if (typeof options.refs === 'string' && !['*', 'all'].includes(options.refs)) options.refs = [options.refs]
10
- if (headers['x-warnings']) options.showWarnings = true
11
- if (headers['x-formatted'] || headers['x-fmt']) options.fmt = true
12
- }
13
-
14
- export async function handleResponseXml (req, reply, payload) {
15
- const { importPkg } = this.app.bajo
16
- const { XMLBuilder } = await importPkg('bajoExtra:fast-xml-parser')
17
- const { get, set, isPlainObject, isArray } = this.app.lib._
18
- const { wrapper, valueAsAttributes, declaration } = this.config.format.xml.response
19
-
20
- reply.type('application/xml; charset=utf-8')
21
- const wrapped = set({}, wrapper, JSON.parse(payload))
22
- const opts = {
23
- attributeValueProcessor: function (k, v) {
24
- return v === 'null' ? '' : v
25
- }
26
- }
27
- const dataKey = this.config.responseKey.data
28
- if (valueAsAttributes) {
29
- const dataValue = get(wrapped, `${wrapper}.${dataKey}`)
30
- opts.attributesGroupName = '_attrs'
31
- if (isPlainObject(dataValue)) {
32
- delete wrapped[wrapper][dataKey]
33
- set(wrapped[wrapper], `${dataKey}._attrs`, dataValue)
34
- } else if (isArray(dataValue)) {
35
- delete wrapped[wrapper][dataKey]
36
- const recs = []
37
- for (const d of dataValue) {
38
- recs.push(set({}, '_attrs', d))
39
- }
40
- set(wrapped[wrapper], dataKey, recs)
41
- }
42
- }
43
- const builder = new XMLBuilder(opts)
44
- let content = builder.build(wrapped)
45
- if (declaration) content = '<?xml version="1.0" encoding="UTF-8" ?>' + content
46
- return content
47
- }
48
-
49
- function getType (input) {
50
- let type = 'string'
51
- if (['float', 'double'].includes(input)) type = 'number'
52
- if (['boolean'].includes(input)) type = 'boolean'
53
- if (['integer', 'smallint'].includes(input)) type = 'integer'
54
- if (['object'].includes(input)) type = 'object'
55
- if (['array'].includes(input)) type = 'array'
56
- return type
57
- }
58
-
59
- export async function buildPropsReqsForSchema ({ model, method, options = {} }) {
60
- const properties = {}
61
- const required = []
62
- const refs = {}
63
- const hidden = [...model.hidden, ...(options.hidden ?? [])] ?? []
64
- for (const p of model.properties) {
65
- if (hidden.includes(p.name)) continue
66
- properties[p.name] = { type: getType(p.type) }
67
- if (properties[p.name].type === 'object') {
68
- properties[p.name].additionalProperties = true
69
- }
70
- if (!p.required) properties[p.name].nullable = true
71
- else if (method === 'create' && p.name !== 'id') required.push(p.name)
72
- if (['datetime'].includes(p.type)) properties[p.name].format = 'date-time'
73
- if (p.ref) {
74
- for (const key in p.ref) {
75
- const val = p.ref[key]
76
- if (val.fields.length === 0) continue
77
- const props = { type: 'object', properties: {} }
78
- const rModel = this.app.dobo.getModel(val.model)
79
- for (const f of val.fields) {
80
- const item = rModel.properties.find(s => s.name === f)
81
- props.properties[item.name] = { type: getType(item.type) }
82
- }
83
- if (Object.keys(props.properties).length > 0) {
84
- if (val.type === '1:n') {
85
- refs[key] = { type: 'array', items: props }
86
- } else if (val.type === '1:1') {
87
- refs[key] = props
88
- }
89
- }
90
- }
91
- }
92
- }
93
- if (Object.keys(refs).length > 0) properties._ref = { type: 'object', properties: refs }
94
- return { properties, required }
95
- }
96
-
97
- export async function buildResponseForSchema ({ model, method, options }) {
98
- const { merge, cloneDeep } = this.app.lib._
99
- const { transformResult } = this.app.waibuRestApi
100
- const cfgWdb = this.app.waibuDb.config
101
- const { properties } = await buildPropsReqsForSchema.call(this, { model, method, options })
102
-
103
- async function buildData (keys) {
104
- const data = {}
105
- for (const k of keys) {
106
- const name = 'model' + model.name
107
- const props = cloneDeep(properties)
108
- await this.docSchemaLib(name, {
109
- type: 'object',
110
- properties: props
111
- })
112
- data[k] = { $ref: name + '#' }
113
- }
114
- return data
115
- }
116
-
117
- const result = {
118
- '2xx': {
119
- description: this.t('successfulResponse'),
120
- type: 'object'
121
- }
122
- }
123
- if (['create', 'update', 'replace'].includes(method)) {
124
- result['4xx'] = {
125
- description: this.t('docErrorResponse'),
126
- $ref: '4xxResp#'
127
- }
128
- }
129
- result['5xx'] = {
130
- description: this.t('generalErrorResponse'),
131
- $ref: '5xxResp#'
132
- }
133
- if (cfgWdb.dbModel.dataOnly) {
134
- if (method === 'find') {
135
- result['2xx'] = {
136
- type: 'array',
137
- items: (await buildData.call(this, ['data'])).data
138
- }
139
- } else if (method === 'get') result['2xx'] = (await buildData.call(this, ['data'])).data
140
- else result['2xx'] = (await buildData.call(this, ['data'], true)).data
141
- return result
142
- }
143
- const success = { type: 'boolean', default: true }
144
- const statusCode = { type: 'integer', default: 200 }
145
- if (method === 'get') {
146
- result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['data']), { success, statusCode }) })
147
- } else if (method === 'create') {
148
- statusCode.default = 201
149
- result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['data']), { success, statusCode }) })
150
- } else if (['update', 'replace'].includes(method)) {
151
- result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['data', 'oldData']), { success, statusCode }) })
152
- } else if (method === 'remove') {
153
- result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['oldData']), { success, statusCode }) })
154
- } else if (method === 'find') {
155
- result['2xx'].properties = transformResult({
156
- data: await this.docSchemaForFind({ type: 'object', properties }),
157
- options: { forFind: true }
158
- })
159
- }
160
- return result
161
- }
1
+ export function extractHeaders (req, options) {
2
+ const { parseObject } = this.app.lib
3
+ const { isSet } = this.app.lib.aneka
4
+ options.count = true
5
+ options.refs = []
6
+ const headers = parseObject(req.headers, { parseValue: true })
7
+ if (headers['x-no-count']) options.count = false
8
+ if (isSet(headers['x-refs'])) options.refs = headers['x-refs']
9
+ if (typeof options.refs === 'string' && !['*', 'all'].includes(options.refs)) options.refs = [options.refs]
10
+ if (headers['x-warnings']) options.showWarnings = true
11
+ if (headers['x-formatted'] || headers['x-fmt']) options.fmt = true
12
+ }
13
+
14
+ export async function handleResponseXml (req, reply, payload) {
15
+ const { importPkg } = this.app.bajo
16
+ const { XMLBuilder } = await importPkg('bajoExtra:fast-xml-parser')
17
+ const { get, set, isPlainObject, isArray } = this.app.lib._
18
+ const { wrapper, valueAsAttributes, declaration } = this.config.format.xml.response
19
+
20
+ reply.type('application/xml; charset=utf-8')
21
+ const wrapped = set({}, wrapper, JSON.parse(payload))
22
+ const opts = {
23
+ attributeValueProcessor: function (k, v) {
24
+ return v === 'null' ? '' : v
25
+ }
26
+ }
27
+ const dataKey = this.config.responseKey.data
28
+ if (valueAsAttributes) {
29
+ const dataValue = get(wrapped, `${wrapper}.${dataKey}`)
30
+ opts.attributesGroupName = '_attrs'
31
+ if (isPlainObject(dataValue)) {
32
+ delete wrapped[wrapper][dataKey]
33
+ set(wrapped[wrapper], `${dataKey}._attrs`, dataValue)
34
+ } else if (isArray(dataValue)) {
35
+ delete wrapped[wrapper][dataKey]
36
+ const recs = []
37
+ for (const d of dataValue) {
38
+ recs.push(set({}, '_attrs', d))
39
+ }
40
+ set(wrapped[wrapper], dataKey, recs)
41
+ }
42
+ }
43
+ const builder = new XMLBuilder(opts)
44
+ let content = builder.build(wrapped)
45
+ if (declaration) content = '<?xml version="1.0" encoding="UTF-8" ?>' + content
46
+ return content
47
+ }
48
+
49
+ function getType (input) {
50
+ let type = 'string'
51
+ if (['float', 'double'].includes(input)) type = 'number'
52
+ if (['boolean'].includes(input)) type = 'boolean'
53
+ if (['integer', 'smallint'].includes(input)) type = 'integer'
54
+ if (['object'].includes(input)) type = 'object'
55
+ if (['array'].includes(input)) type = 'array'
56
+ return type
57
+ }
58
+
59
+ export async function buildPropsReqsForSchema ({ model, method, options = {} }) {
60
+ const properties = {}
61
+ const required = []
62
+ const refs = {}
63
+ const hidden = [...model.hidden, ...(options.hidden ?? [])] ?? []
64
+ for (const p of model.properties) {
65
+ if (hidden.includes(p.name)) continue
66
+ properties[p.name] = { type: getType(p.type) }
67
+ if (properties[p.name].type === 'object') {
68
+ properties[p.name].additionalProperties = true
69
+ }
70
+ if (!p.required) properties[p.name].nullable = true
71
+ else if (method === 'create' && p.name !== 'id') required.push(p.name)
72
+ if (['datetime'].includes(p.type)) properties[p.name].format = 'date-time'
73
+ if (p.ref) {
74
+ for (const key in p.ref) {
75
+ const val = p.ref[key]
76
+ if (val.fields.length === 0) continue
77
+ const props = { type: 'object', properties: {} }
78
+ const rModel = this.app.dobo.getModel(val.model)
79
+ for (const f of val.fields) {
80
+ const item = rModel.properties.find(s => s.name === f)
81
+ props.properties[item.name] = { type: getType(item.type) }
82
+ }
83
+ if (Object.keys(props.properties).length > 0) {
84
+ if (val.type === '1:n') {
85
+ refs[key] = { type: 'array', items: props }
86
+ } else if (val.type === '1:1') {
87
+ refs[key] = props
88
+ }
89
+ }
90
+ }
91
+ }
92
+ }
93
+ if (Object.keys(refs).length > 0) properties._ref = { type: 'object', properties: refs }
94
+ return { properties, required }
95
+ }
96
+
97
+ export async function buildResponseForSchema ({ model, method, options }) {
98
+ const { merge, cloneDeep } = this.app.lib._
99
+ const { transformResult } = this.app.waibuRestApi
100
+ const cfgWdb = this.app.waibuDb.config
101
+ const { properties } = await buildPropsReqsForSchema.call(this, { model, method, options })
102
+
103
+ async function buildData (keys) {
104
+ const data = {}
105
+ for (const k of keys) {
106
+ const name = 'model' + model.name
107
+ const props = cloneDeep(properties)
108
+ await this.docSchemaLib(name, {
109
+ type: 'object',
110
+ properties: props
111
+ })
112
+ data[k] = { $ref: name + '#' }
113
+ }
114
+ return data
115
+ }
116
+
117
+ const result = {
118
+ '2xx': {
119
+ description: this.t('successfulResponse'),
120
+ type: 'object'
121
+ }
122
+ }
123
+ if (['create', 'update', 'replace'].includes(method)) {
124
+ result['4xx'] = {
125
+ description: this.t('docErrorResponse'),
126
+ $ref: '4xxResp#'
127
+ }
128
+ }
129
+ result['5xx'] = {
130
+ description: this.t('generalErrorResponse'),
131
+ $ref: '5xxResp#'
132
+ }
133
+ if (cfgWdb.dbModel.dataOnly) {
134
+ if (method === 'find') {
135
+ result['2xx'] = {
136
+ type: 'array',
137
+ items: (await buildData.call(this, ['data'])).data
138
+ }
139
+ } else if (method === 'get') result['2xx'] = (await buildData.call(this, ['data'])).data
140
+ else result['2xx'] = (await buildData.call(this, ['data'], true)).data
141
+ return result
142
+ }
143
+ const success = { type: 'boolean', default: true }
144
+ const statusCode = { type: 'integer', default: 200 }
145
+ if (method === 'get') {
146
+ result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['data']), { success, statusCode }) })
147
+ } else if (method === 'create') {
148
+ statusCode.default = 201
149
+ result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['data']), { success, statusCode }) })
150
+ } else if (['update', 'replace'].includes(method)) {
151
+ result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['data', 'oldData']), { success, statusCode }) })
152
+ } else if (method === 'remove') {
153
+ result['2xx'].properties = transformResult({ data: merge({}, await buildData.call(this, ['oldData']), { success, statusCode }) })
154
+ } else if (method === 'find') {
155
+ result['2xx'].properties = transformResult({
156
+ data: await this.docSchemaForFind({ type: 'object', properties }),
157
+ options: { forFind: true }
158
+ })
159
+ }
160
+ return result
161
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "waibu-rest-api",
3
- "version": "2.14.1",
3
+ "version": "2.14.2",
4
4
  "description": "REST API for Waibu",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/wiki/CHANGES.md CHANGED
@@ -1,95 +1,99 @@
1
- # Changes
2
-
3
- ## 2026-07-08
4
-
5
- - [2.14.1] Bug fix in `boot.js`
6
-
7
- ## 2026-07-04
8
-
9
- - [2.14.0] Reorganize projects to reduce boot time
10
-
11
- ## 2026-06-10
12
-
13
- - [2.13.0] Remove route redirects because now directly handled by ```waibu```
14
-
15
- ## 2026-05-28
16
-
17
- - [2.12.0] Change hooks to be written in one ```hook.js``` file
18
-
19
- ## 2026-05-22
20
-
21
- - [2.11.1] Bug fix in ```serve-route.js```
22
-
23
- ## 2026-04-25
24
-
25
- - [2.11.0] Change options to format value using the new key set by dobo
26
- - [2.11.0] Remove ```options.retainOriginalValue``` since it is not needed anymore
27
- - [2.11.0] Change related header to ```X-Fmt```
28
-
29
- ## 2026-04-11
30
-
31
- - [2.10.0] Add support to format output values using header ```X-Format-Value```
32
- - [2.10.0] Add support to retain original value using header ```X-Retain-Original``` if above key is ```true```
33
-
34
- ## 2026-04-02
35
-
36
- - [2.9.1] Add missing ```hardCapped``` key
37
-
38
- ## 2026-03-30
39
-
40
- - [2.8.0] Add inter site module support
41
- - [2.8.1] Bug fix in ```options.limit```, removed due to use ```findAllRecords()```
42
- - [2.9.0] Add support to show warnings through headers ```X-Warnings```
43
- - [2.9.0] Add support for ```dobo.hardCap``` when ```count``` is requested
44
- - [2.9.0] By default now ALWAYS request ```count``` which can be turned off with through headers ```X-NoCount```
45
-
46
-
47
- ## 2026-03-22
48
-
49
- - [2.7.1] bug fix in reference records
50
- - [2.7.2] Bug fix in applying routes to ```webCtx```
51
-
52
- ## 2026-03-14
53
-
54
- - [2.7.0] Accept model's name from ```req.params``` in ```route-by-model-builder.js```
55
-
56
- ## 2026-03-06
57
-
58
- - [2.6.1] Bug fix on schema enforcement. Only apply when it's stated explicitely in route handler
59
-
60
- ## 2026-03-05
61
-
62
- - [2.6.0] Add transaction support by setting property ```transaction: true``` on model's route handler definition
63
-
64
- ## 2026-02-23
65
-
66
- - [2.5.1] Bug fix on ```transformResult()```
67
-
68
- ## 2026-02-22
69
-
70
- - [2.5.0] Add warnings to the response objects
71
-
72
- ## 2026-02-09
73
-
74
- - [2.4.0] Add error & not found handlers
75
-
76
- ## 2026-02-08
77
-
78
- - [2.3.0] Simplify webApp context through ```plugin.webAppCtx```
79
-
80
- ## 2026-01-30
81
-
82
- - [2.2.1] Bug fix if output format is in xml
83
-
84
- ## 2026-01-24
85
-
86
- - [2.2.0] Add ```hooks``` property to model builder that will be considered as dynamic hoooks by models
87
-
88
- ## 2026-01-16
89
-
90
- - [2.1.1] Bug fix on model references
91
-
92
- ## 2025-12-28
93
-
94
- - [2.1.0] Ported to ```bajo@2.2.x``` specs
95
- - [2.1.0] Add waibuRestApi end point ```/api/db/:model/stat/:stat```
1
+ # Changes
2
+
3
+ ## 2026-09-05
4
+
5
+ - [2.14.2] Bug fix in `_routeByModelBuilder()` for aggregate/histogram endpoint
6
+
7
+ ## 2026-07-08
8
+
9
+ - [2.14.1] Bug fix in `boot.js`
10
+
11
+ ## 2026-07-04
12
+
13
+ - [2.14.0] Reorganize projects to reduce boot time
14
+
15
+ ## 2026-06-10
16
+
17
+ - [2.13.0] Remove route redirects because now directly handled by ```waibu```
18
+
19
+ ## 2026-05-28
20
+
21
+ - [2.12.0] Change hooks to be written in one ```hook.js``` file
22
+
23
+ ## 2026-05-22
24
+
25
+ - [2.11.1] Bug fix in ```serve-route.js```
26
+
27
+ ## 2026-04-25
28
+
29
+ - [2.11.0] Change options to format value using the new key set by dobo
30
+ - [2.11.0] Remove ```options.retainOriginalValue``` since it is not needed anymore
31
+ - [2.11.0] Change related header to ```X-Fmt```
32
+
33
+ ## 2026-04-11
34
+
35
+ - [2.10.0] Add support to format output values using header ```X-Format-Value```
36
+ - [2.10.0] Add support to retain original value using header ```X-Retain-Original``` if above key is ```true```
37
+
38
+ ## 2026-04-02
39
+
40
+ - [2.9.1] Add missing ```hardCapped``` key
41
+
42
+ ## 2026-03-30
43
+
44
+ - [2.8.0] Add inter site module support
45
+ - [2.8.1] Bug fix in ```options.limit```, removed due to use ```findAllRecords()```
46
+ - [2.9.0] Add support to show warnings through headers ```X-Warnings```
47
+ - [2.9.0] Add support for ```dobo.hardCap``` when ```count``` is requested
48
+ - [2.9.0] By default now ALWAYS request ```count``` which can be turned off with through headers ```X-NoCount```
49
+
50
+
51
+ ## 2026-03-22
52
+
53
+ - [2.7.1] bug fix in reference records
54
+ - [2.7.2] Bug fix in applying routes to ```webCtx```
55
+
56
+ ## 2026-03-14
57
+
58
+ - [2.7.0] Accept model's name from ```req.params``` in ```route-by-model-builder.js```
59
+
60
+ ## 2026-03-06
61
+
62
+ - [2.6.1] Bug fix on schema enforcement. Only apply when it's stated explicitely in route handler
63
+
64
+ ## 2026-03-05
65
+
66
+ - [2.6.0] Add transaction support by setting property ```transaction: true``` on model's route handler definition
67
+
68
+ ## 2026-02-23
69
+
70
+ - [2.5.1] Bug fix on ```transformResult()```
71
+
72
+ ## 2026-02-22
73
+
74
+ - [2.5.0] Add warnings to the response objects
75
+
76
+ ## 2026-02-09
77
+
78
+ - [2.4.0] Add error & not found handlers
79
+
80
+ ## 2026-02-08
81
+
82
+ - [2.3.0] Simplify webApp context through ```plugin.webAppCtx```
83
+
84
+ ## 2026-01-30
85
+
86
+ - [2.2.1] Bug fix if output format is in xml
87
+
88
+ ## 2026-01-24
89
+
90
+ - [2.2.0] Add ```hooks``` property to model builder that will be considered as dynamic hoooks by models
91
+
92
+ ## 2026-01-16
93
+
94
+ - [2.1.1] Bug fix on model references
95
+
96
+ ## 2025-12-28
97
+
98
+ - [2.1.0] Ported to ```bajo@2.2.x``` specs
99
+ - [2.1.0] Add waibuRestApi end point ```/api/db/:model/stat/:stat```
package/wiki/CONFIG.md CHANGED
File without changes
File without changes