64 lines
2.1 KiB
TypeScript
64 lines
2.1 KiB
TypeScript
import { Hono } from 'hono'
|
|
import { APIClient } from '@d8d-appcontainer/api'
|
|
import type { Variables, WithAuth } from "./middlewares.ts";
|
|
import { loadMigrations } from './migrations.ts'
|
|
import debug from "debug";
|
|
const log = {
|
|
api: debug("api:migrations"),
|
|
};
|
|
|
|
export function createMigrationsRoutes(withAuth: WithAuth) {
|
|
const migrationsRoutes = new Hono<{ Variables: Variables }>()
|
|
|
|
migrationsRoutes.get('/', async (c) => {
|
|
const apiClient = c.get('apiClient')
|
|
log.api('正在执行数据库迁移...')
|
|
const migrations = await loadMigrations()
|
|
const migrationsResult = await apiClient.database.executeLiveMigrations(migrations)
|
|
// log.app('数据库迁移完成 %O',migrationsResult)
|
|
|
|
const failedResult = migrationsResult?.find((migration) => migration.status === 'failed')
|
|
if (failedResult) {
|
|
log.api('数据库迁移失败 %O', failedResult)
|
|
return c.json({ error: '数据库迁移失败', failedResult }, 500)
|
|
}
|
|
|
|
return c.json({ success: true })
|
|
})
|
|
|
|
|
|
migrationsRoutes.get('/history', async (c) => {
|
|
const apiClient = c.get('apiClient')
|
|
log.api('正在执行数据库迁移...')
|
|
const MIRGRATIONS_TABLE = 'knex_migrations'
|
|
const hasTable = await apiClient.database.schema.hasTable(MIRGRATIONS_TABLE);
|
|
|
|
let history = []
|
|
|
|
if(hasTable)
|
|
history = await apiClient.database.table(MIRGRATIONS_TABLE).orderBy('id', 'desc')
|
|
|
|
return c.json({
|
|
success: true,
|
|
history
|
|
})
|
|
})
|
|
|
|
migrationsRoutes.get('/rollback', async (c) => {
|
|
const apiClient = c.get('apiClient')
|
|
const all = c.req.query('all') === 'true'
|
|
log.api('正在执行数据库回滚...')
|
|
const migrations = await loadMigrations()
|
|
const rollbackResult = await apiClient.database.rollbackLiveMigrations(migrations, all)
|
|
|
|
const failedResult = rollbackResult?.find((migration) => migration.status === 'failed')
|
|
if (failedResult) {
|
|
log.api('数据库回滚失败 %O', failedResult)
|
|
return c.json({ error: '数据库回滚失败', failedResult }, 500)
|
|
}
|
|
|
|
return c.json({ success: true })
|
|
})
|
|
|
|
return migrationsRoutes
|
|
} |