budibase/packages/server/src/app.ts

97 lines
2.2 KiB
TypeScript
Raw Normal View History

// need to load environment first
import { ExtendableContext } from "koa"
const env = require("./environment")
2021-04-15 17:57:01 +02:00
const CouchDB = require("./db")
require("@budibase/backend-core").init(CouchDB)
const Koa = require("koa")
const destroyable = require("server-destroy")
const koaBody = require("koa-body")
2021-05-28 11:09:32 +02:00
const pino = require("koa-pino-logger")
2020-05-14 16:12:30 +02:00
const http = require("http")
const api = require("./api")
2020-05-31 18:12:52 +02:00
const eventEmitter = require("./events")
const automations = require("./automations/index")
2020-07-14 17:00:58 +02:00
const Sentry = require("@sentry/node")
const fileSystem = require("./utilities/fileSystem")
const bullboard = require("./automations/bullboard")
2021-05-12 18:37:09 +02:00
const redis = require("./utilities/redis")
2020-05-07 15:04:32 +02:00
const app = new Koa()
2019-06-14 11:05:46 +02:00
2020-05-07 15:04:32 +02:00
// set up top level koa middleware
2021-02-09 19:49:12 +01:00
app.use(
koaBody({
multipart: true,
formLimit: "10mb",
jsonLimit: "10mb",
textLimit: "10mb",
enableTypes: ["json", "form", "text"],
parsedMethods: ["POST", "PUT", "PATCH", "DELETE"],
2021-02-09 19:49:12 +01:00
})
)
2020-05-14 16:12:30 +02:00
2021-06-01 21:17:06 +02:00
app.use(
pino({
prettyPrint: {
levelFirst: true,
},
level: env.LOG_LEVEL || "error",
})
)
2020-05-04 18:13:57 +02:00
if (!env.isTest()) {
const plugin = bullboard.init()
app.use(plugin)
}
2020-05-31 18:12:52 +02:00
app.context.eventEmitter = eventEmitter
app.context.auth = {}
2020-05-24 23:54:08 +02:00
2020-05-07 15:04:32 +02:00
// api routes
app.use(api.routes())
2020-05-04 18:13:57 +02:00
if (env.isProd()) {
env._set("NODE_ENV", "production")
2020-07-14 17:00:58 +02:00
Sentry.init()
app.on("error", (err: any, ctx: ExtendableContext) => {
Sentry.withScope(function (scope: any) {
scope.addEventProcessor(function (event: any) {
2020-07-14 17:00:58 +02:00
return Sentry.Handlers.parseRequest(event, ctx.request)
})
Sentry.captureException(err)
})
})
}
2020-07-16 15:27:27 +02:00
const server = http.createServer(app.callback())
destroyable(server)
2020-07-16 15:27:27 +02:00
server.on("close", async () => {
if (env.NODE_ENV !== "jest") {
console.log("Server Closed")
}
await redis.shutdown()
})
module.exports = server.listen(env.PORT || 0, async () => {
2020-07-16 15:27:27 +02:00
console.log(`Budibase running on ${JSON.stringify(server.address())}`)
env._set("PORT", server.address().port)
eventEmitter.emitPort(env.PORT)
fileSystem.init()
2021-05-12 18:37:09 +02:00
await redis.init()
await automations.init()
2020-07-16 16:19:46 +02:00
})
2021-05-04 12:32:22 +02:00
process.on("uncaughtException", err => {
console.error(err)
server.close()
server.destroy()
})
process.on("SIGTERM", () => {
server.close()
server.destroy()
})