Guard migration

This commit is contained in:
Adria Navarro 2023-12-01 10:39:44 +01:00
parent 14fc91d58a
commit 7f52a1e28c
2 changed files with 68 additions and 3 deletions

View File

@ -99,6 +99,8 @@ function updateContext(updates: ContextMap): ContextMap {
}
async function newContext<T>(updates: ContextMap, task: () => T) {
guardMigration()
// see if there already is a context setup
let context: ContextMap = updateContext(updates)
return Context.run(context, task)
@ -186,13 +188,22 @@ export async function doInIdentityContext<T>(
return newContext(context, task)
}
function guardMigration() {
const context = Context.get()
if (context?.isMigrating) {
throw new Error(
"The context cannot be change, a migration is currently running"
)
}
}
export async function doInAppMigrationContext<T>(
appId: string,
task: () => T
): Promise<T> {
return _doInAppContext(appId, task, {
isMigrating: true,
})
return _doInAppContext(appId, task, {
isMigrating: true,
})
}
export function getIdentity(): IdentityContext | undefined {

View File

@ -5,6 +5,7 @@ import { structures } from "../../../tests"
import { db } from "../.."
import Context from "../Context"
import { ContextMap } from "../types"
import { IdentityType } from "@budibase/types"
describe("context", () => {
describe("doInTenant", () => {
@ -197,5 +198,58 @@ describe("context", () => {
expect(Context.get()).toBeUndefined()
})
it.each([
[
"doInAppMigrationContext",
() => context.doInAppMigrationContext(db.generateAppID(), () => {}),
],
[
"doInAppContext",
() => context.doInAppContext(db.generateAppID(), () => {}),
],
[
"doInAutomationContext",
() =>
context.doInAutomationContext({
appId: db.generateAppID(),
automationId: structures.generator.guid(),
task: () => {},
}),
],
["doInContext", () => context.doInContext(db.generateAppID(), () => {})],
[
"doInEnvironmentContext",
() => context.doInEnvironmentContext({}, () => {}),
],
[
"doInIdentityContext",
() =>
context.doInIdentityContext(
{
account: undefined,
type: IdentityType.USER,
_id: structures.users.user()._id!,
},
() => {}
),
],
["doInScimContext", () => context.doInScimContext(() => {})],
[
"doInTenant",
() => context.doInTenant(structures.tenant.id(), () => {}),
],
])(
"a nested context.%s function cannot run",
async (_, otherContextCall: () => Promise<void>) => {
await expect(
context.doInAppMigrationContext(db.generateAppID(), async () => {
await otherContextCall()
})
).rejects.toThrowError(
"The context cannot be change, a migration is currently running"
)
}
)
})
})