1
0
Fork 0
mirror of synced 2024-06-29 03:20:34 +12:00
budibase/packages/server/src/api/index.js

100 lines
2.3 KiB
JavaScript
Raw Normal View History

const Router = require("@koa/router")
const { buildAuthMiddleware, auditLog, buildTenancyMiddleware } =
require("@budibase/auth").auth
const currentApp = require("../middleware/currentapp")
2020-05-07 21:53:34 +12:00
const compress = require("koa-compress")
const zlib = require("zlib")
const { mainRoutes, staticRoutes } = require("./routes")
2021-01-28 02:55:46 +13:00
const pkg = require("../../package.json")
const env = require("../environment")
2021-03-27 03:56:34 +13:00
2020-05-08 01:04:32 +12:00
const router = new Router()
const NO_TENANCY_ENDPOINTS = [
{
route: "/api/analytics",
method: "GET",
},
{
route: "/builder",
method: "GET",
},
// when using this locally there can be pass through, need
// to allow all pass through endpoints to go without tenancy
{
route: "/api/global",
method: "ALL",
},
{
route: "/api/system",
method: "ALL",
},
]
2020-05-08 01:04:32 +12:00
router
.use(
compress({
threshold: 2048,
gzip: {
2021-03-30 03:06:00 +13:00
flush: zlib.constants.Z_SYNC_FLUSH,
2020-05-08 01:04:32 +12:00
},
deflate: {
2021-03-30 03:06:00 +13:00
flush: zlib.constants.Z_SYNC_FLUSH,
2020-05-08 01:04:32 +12:00
},
2020-05-19 01:58:39 +12:00
br: false,
2020-05-07 07:29:47 +12:00
})
2020-05-08 01:04:32 +12:00
)
.use(async (ctx, next) => {
ctx.config = {
2020-05-15 02:12:30 +12:00
jwtSecret: env.JWT_SECRET,
useAppRootPath: true,
2020-04-09 03:57:27 +12:00
}
2020-05-08 01:04:32 +12:00
await next()
2020-05-07 21:53:34 +12:00
})
2021-05-04 22:32:22 +12:00
.use("/health", ctx => (ctx.status = 200))
.use("/version", ctx => (ctx.body = pkg.version))
.use(
buildAuthMiddleware(null, {
publicAllowed: true,
})
)
// nothing in the server should allow query string tenants
.use(buildTenancyMiddleware(null, NO_TENANCY_ENDPOINTS))
.use(currentApp)
2021-05-28 21:09:32 +12:00
.use(auditLog)
2020-05-08 01:04:32 +12:00
// error handling middleware
router.use(async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = err.status || err.statusCode || 500
ctx.body = {
message: err.message,
status: ctx.status,
2021-08-17 08:07:15 +12:00
validationErrors: err.validation,
2020-05-08 01:04:32 +12:00
}
if (env.NODE_ENV !== "jest") {
ctx.log.error(err)
console.trace(err)
}
2020-05-08 01:04:32 +12:00
}
})
2020-04-09 03:57:27 +12:00
2021-05-04 22:32:22 +12:00
router.get("/health", ctx => (ctx.status = 200))
2020-05-08 01:04:32 +12:00
// authenticated routes
for (let route of mainRoutes) {
router.use(route.routes())
router.use(route.allowedMethods())
}
// WARNING - static routes will catch everything else after them this must be last
2020-05-08 01:04:32 +12:00
router.use(staticRoutes.routes())
router.use(staticRoutes.allowedMethods())
2020-04-07 01:05:57 +12:00
// add a redirect for when hitting server directly
router.redirect("/", "/builder")
2020-05-08 01:04:32 +12:00
module.exports = router