Skip to content

Commit

Permalink
feat(xo-server/rest-api): provide a way to extend it
Browse files Browse the repository at this point in the history
  • Loading branch information
julien-f committed Jun 30, 2023
1 parent db082bf commit c68630e
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions packages/xo-server/src/xo-mixins/rest-api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ function wrap(middleware, handleNoSuchObject = false) {
}

export default class RestApi {
#api

constructor(app, { express }) {
// don't setup the API if express is not present
//
Expand All @@ -110,6 +112,7 @@ export default class RestApi {
}

const api = subRouter(express, '/rest/v0')
this.#api = api

api.use(({ cookies }, res, next) => {
app.authenticateUser({ token: cookies.authenticationToken ?? cookies.token }).then(
Expand Down Expand Up @@ -494,4 +497,33 @@ export default class RestApi {
})
)
}

registerRestApi(spec, base = '/') {
for (const path of Object.keys(spec)) {
if (path[0] === '_') {
const handler = spec[path]
this.#api[path.slice(1)](base, json(), async (req, res, next) => {
try {
const result = await handler(req, res, next)
if (result !== undefined) {
const isIterable =
result !== null && typeof (result[Symbol.iterator] ?? result[Symbol.asyncIterator]) === 'function'
if (isIterable) {
await sendObjects(result, req, res)
} else {
res.json(result)
}
}
} catch (error) {
next(error)
}
})
} else {
this.registerRestApi(spec[path], join(base, path))
}
}
return () => {
throw new Error('not implemented')
}
}
}

0 comments on commit c68630e

Please sign in to comment.