budibase/packages/server/src/appMigrations/index.ts

69 lines
1.6 KiB
TypeScript
Raw Normal View History

import { getAppMigrationQueue } from "./queue"
2023-12-11 10:50:13 +01:00
import { Next } from "koa"
2023-11-29 13:28:52 +01:00
import { getAppMigrationVersion } from "./appMigrationMetadata"
2023-11-27 15:40:37 +01:00
import { MIGRATIONS } from "./migrations"
2023-12-11 10:50:13 +01:00
import { UserCtx } from "@budibase/types"
import { Header } from "@budibase/backend-core"
2023-11-27 15:40:37 +01:00
export * from "./appMigrationMetadata"
2023-12-05 15:29:11 +01:00
export type AppMigration = {
id: string
func: () => Promise<void>
// disabled so that by default all migrations listed are enabled
disabled?: boolean
2023-12-05 15:29:11 +01:00
}
2024-06-06 17:49:03 +02:00
export function getLatestEnabledMigrationId(migrations?: AppMigration[]) {
let latestMigrationId: string | undefined
if (!migrations) {
migrations = MIGRATIONS
}
for (let migration of migrations) {
// if a migration is disabled, all migrations after it are disabled
if (migration.disabled) {
break
}
latestMigrationId = migration.id
}
return latestMigrationId
}
2023-11-27 15:40:37 +01:00
function getTimestamp(versionId: string) {
return versionId?.split("_")[0] || ""
}
2023-12-11 10:50:13 +01:00
export async function checkMissingMigrations(
ctx: UserCtx,
next: Next,
appId: string
) {
const latestMigration = getLatestEnabledMigrationId()
// no migrations set - edge case, don't try to do anything
if (!latestMigration) {
2024-06-11 00:11:53 +02:00
return next()
}
const currentVersion = await getAppMigrationVersion(appId)
const queue = getAppMigrationQueue()
2023-11-27 15:40:37 +01:00
if (
latestMigration &&
getTimestamp(currentVersion) < getTimestamp(latestMigration)
) {
2023-11-27 15:40:37 +01:00
await queue.add(
{
appId,
2023-11-27 16:23:57 +01:00
},
{
2023-11-29 11:03:33 +01:00
jobId: `${appId}_${latestMigration}`,
2023-11-27 15:40:37 +01:00
}
)
2023-12-11 10:50:13 +01:00
ctx.response.set(Header.MIGRATING_APP, appId)
2023-11-27 15:40:37 +01:00
}
2023-12-11 10:50:13 +01:00
return next()
2023-11-27 15:40:37 +01:00
}