UNPKG

kanel-knex

Version:
56 lines (55 loc) 2.25 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const kanel_1 = require("kanel"); const knex_1 = __importDefault(require("knex")); const path_1 = require("path"); const knexImport_1 = __importDefault(require("./knexImport")); const generateMigrationCheck = async (outputAcc, _context) => { const { config } = (0, kanel_1.useKanelContext)(); const connection = config.connection; const db = (0, knex_1.default)({ client: "postgres", connection }); const [{ name: sourceMigration }] = await db .select("name") .from("knex_migrations") .orderBy("migration_time", "DESC") .limit(1); db.destroy(); const typeImports = [knexImport_1.default]; const lines = [ "/** This is the migration that was set when the types were generated. */", `export const sourceMigration = '${sourceMigration}';`, "", "/** Gets the migration in the live database */", "export const getCurrentMigration = async (knex: Knex): Promise<string> => {", " const [{ name }] = await knex", " .select('name')", " .from('knex_migrations')", " .orderBy('migration_time', 'DESC')", " .limit(1);", " return name;", "};", "", "/** Check that the migration in the live database matches the code */", "export const validateMigration = async (knex: Knex): Promise<void> => {", " const currentMigration = await getCurrentMigration(knex);", " if (currentMigration !== sourceMigration) {", " throw new Error(`Current migration is ${currentMigration}, but source migration is ${sourceMigration}`);", " }", "};", ]; const declaration = { declarationType: "generic", typeImports, lines, }; const outputPath = config.outputPath ?? ""; const path = (0, path_1.join)(outputPath, "migration-check"); return { ...outputAcc, [path]: { fileType: "typescript", declarations: [declaration] }, }; }; exports.default = generateMigrationCheck;