budibase/packages/server/src/middleware/cleanup.ts

34 lines
781 B
TypeScript
Raw Normal View History

import { Ctx } from "@budibase/types"
import { context } from "@budibase/backend-core"
import { tracer } from "dd-trace"
export default async (ctx: Ctx, next: any) => {
2024-02-21 16:26:26 +01:00
const resp = await next()
const current = context.getCurrentContext()
2024-02-21 16:26:26 +01:00
if (!current || !current.cleanup) {
return resp
}
let errors = []
for (let fn of current.cleanup) {
try {
2024-03-20 12:46:39 +01:00
await tracer.trace("cleanup", async () => {
await fn()
})
2024-02-21 16:26:26 +01:00
} catch (e) {
// We catch errors here to ensure we at least attempt to run all cleanup
// functions. We'll throw the first error we encounter after all cleanup
// functions have been run.
errors.push(e)
}
2024-02-21 16:26:26 +01:00
}
delete current.cleanup
if (errors.length > 0) {
throw errors[0]
}
return resp
}