1
0
Fork 0
mirror of synced 2024-09-21 20:01:32 +12:00
budibase/packages/server/src/api/index.ts

90 lines
2.3 KiB
TypeScript
Raw Normal View History

import Router from "@koa/router"
import { errors, auth } from "@budibase/backend-core"
import currentApp from "../middleware/currentapp"
import zlib from "zlib"
import { mainRoutes, staticRoutes, publicRoutes } from "./routes"
import pkg from "../../package.json"
import env from "../environment"
import { middleware as pro } from "@budibase/pro"
export { shutdown } from "./routes/public"
2020-05-07 21:53:34 +12:00
const compress = require("koa-compress")
2021-03-27 03:56:34 +13:00
export const router: Router = new Router()
2022-03-25 03:24:56 +13:00
router.get("/health", ctx => (ctx.status = 200))
router.get("/version", ctx => (ctx.body = pkg.version))
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
})
// re-direct before any middlewares occur
.redirect("/", "/builder")
.use(
2022-11-27 04:10:41 +13:00
auth.buildAuthMiddleware([], {
publicAllowed: true,
})
)
// nothing in the server should allow query string tenants
// the server can be public anywhere, so nowhere should throw errors
// if the tenancy has not been set, it'll have to be discovered at application layer
.use(
2022-11-27 04:10:41 +13:00
auth.buildTenancyMiddleware([], [], {
noTenancyRequired: true,
})
)
.use(pro.licensing())
// @ts-ignore
.use(currentApp)
.use(auth.auditLog)
2020-05-08 01:04:32 +12:00
// error handling middleware
router.use(async (ctx, next) => {
try {
await next()
} catch (err: any) {
2020-05-08 01:04:32 +12:00
ctx.status = err.status || err.statusCode || 500
const error = errors.getPublicError(err)
2020-05-08 01:04:32 +12:00
ctx.body = {
message: err.message,
status: ctx.status,
2021-08-17 08:07:15 +12:00
validationErrors: err.validation,
error,
2020-05-08 01:04:32 +12:00
}
ctx.log.error(err)
// unauthorised errors don't provide a useful trace
if (!env.isTest()) {
console.trace(err)
}
2020-05-08 01:04:32 +12:00
}
})
2020-04-09 03:57:27 +12:00
2020-05-08 01:04:32 +12:00
// authenticated routes
for (let route of mainRoutes) {
router.use(route.routes())
router.use(route.allowedMethods())
}
2022-02-17 07:23:38 +13:00
router.use(publicRoutes.routes())
router.use(publicRoutes.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())