2022-04-19 20:42:52 +02:00
|
|
|
const { setTenantId, setGlobalDB, getGlobalDB } = require("../tenancy")
|
2022-04-20 19:07:48 +02:00
|
|
|
const { closeDB } = require("../db")
|
2022-01-31 18:53:19 +01:00
|
|
|
const ContextFactory = require("../context/FunctionContext")
|
2021-08-05 10:59:08 +02:00
|
|
|
const { buildMatcherRegex, matches } = require("./matchers")
|
|
|
|
|
2021-09-09 14:27:18 +02:00
|
|
|
module.exports = (
|
|
|
|
allowQueryStringPatterns,
|
|
|
|
noTenancyPatterns,
|
|
|
|
opts = { noTenancyRequired: false }
|
|
|
|
) => {
|
2021-08-05 10:59:08 +02:00
|
|
|
const allowQsOptions = buildMatcherRegex(allowQueryStringPatterns)
|
|
|
|
const noTenancyOptions = buildMatcherRegex(noTenancyPatterns)
|
|
|
|
|
2022-04-19 20:42:52 +02:00
|
|
|
const updateCtxFn = ctx => {
|
2021-09-06 17:24:51 +02:00
|
|
|
const allowNoTenant =
|
|
|
|
opts.noTenancyRequired || !!matches(ctx, noTenancyOptions)
|
2021-08-05 10:59:08 +02:00
|
|
|
const allowQs = !!matches(ctx, allowQsOptions)
|
2022-04-19 20:42:52 +02:00
|
|
|
const tenantId = setTenantId(ctx, { allowQs, allowNoTenant })
|
|
|
|
setGlobalDB(tenantId)
|
|
|
|
}
|
|
|
|
const destroyFn = async () => {
|
2022-04-20 19:07:48 +02:00
|
|
|
const db = getGlobalDB()
|
|
|
|
await closeDB(db)
|
2022-04-19 20:42:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return ContextFactory.getMiddleware(updateCtxFn, destroyFn)
|
2021-08-05 10:59:08 +02:00
|
|
|
}
|