budibase/packages/server/src/api/index.js

69 lines
1.6 KiB
JavaScript
Raw Normal View History

const Router = require("@koa/router")
2020-05-07 11:53:34 +02:00
const authenticated = require("../middleware/authenticated")
const compress = require("koa-compress")
const zlib = require("zlib")
2020-05-11 16:42:42 +02:00
const { budibaseAppsDir } = require("../utilities/budibaseDir")
const { isDev } = require("../utilities")
2020-11-17 19:13:21 +01:00
const { mainRoutes, authRoutes, staticRoutes } = require("./routes")
2019-06-28 23:59:27 +02:00
2020-05-07 15:04:32 +02:00
const router = new Router()
2020-05-14 16:12:30 +02:00
const env = require("../environment")
2020-05-07 15:04:32 +02:00
router
.use(
compress({
threshold: 2048,
gzip: {
flush: zlib.Z_SYNC_FLUSH,
},
deflate: {
flush: zlib.Z_SYNC_FLUSH,
},
2020-05-18 15:58:39 +02:00
br: false,
2020-05-06 21:29:47 +02:00
})
2020-05-07 15:04:32 +02:00
)
.use(async (ctx, next) => {
ctx.config = {
2020-05-11 16:42:42 +02:00
latestPackagesFolder: budibaseAppsDir(),
2020-05-14 16:12:30 +02:00
jwtSecret: env.JWT_SECRET,
useAppRootPath: true,
2020-04-08 17:57:27 +02:00
}
ctx.isDev = isDev()
2020-05-07 15:04:32 +02:00
await next()
2020-05-07 11:53:34 +02:00
})
.use("/health", ctx => (ctx.status = 200))
2020-05-07 15:04:32 +02:00
.use(authenticated)
// error handling middleware
router.use(async (ctx, next) => {
try {
await next()
} catch (err) {
2020-05-18 16:46:38 +02:00
ctx.log.error(err)
2020-05-07 15:04:32 +02:00
ctx.status = err.status || err.statusCode || 500
ctx.body = {
message: err.message,
status: ctx.status,
}
}
})
2020-04-08 17:57:27 +02:00
router.get("/health", ctx => (ctx.status = 200))
2020-05-07 15:04:32 +02:00
router.use(authRoutes.routes())
router.use(authRoutes.allowedMethods())
2020-05-04 18:13:57 +02:00
2020-05-07 15:04:32 +02: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-07 15:04:32 +02:00
router.use(staticRoutes.routes())
router.use(staticRoutes.allowedMethods())
2020-04-06 15:05:57 +02:00
2020-05-07 15:04:32 +02:00
router.redirect("/", "/_builder")
2019-06-28 23:59:27 +02:00
2020-05-07 15:04:32 +02:00
module.exports = router