UNPKG

@opengis/fastify-table

Version:

core-plugins

61 lines (60 loc) 2.3 kB
/* eslint-disable no-console */ import path from "node:path"; import { readdirSync, existsSync } from "node:fs"; import config from "../../../config.js"; import execSql from "./exec.sql.js"; import pgClients from "../pg/pgClients.js"; const time = Date.now(); const debug = config.debug || config.local; export default async function execMigrations(dirPath, pg = pgClients.client, iscore = false) { if (!dirPath) { const txt = "migrations skip: path not specified"; if (debug) console.warn(`⚠️ ${txt}`); return txt; } if (config.migrationsCore === false && iscore) { const txt = `migrations skip: core - ${dirPath}`; if (debug) console.warn(`⚠️ ${txt}`); return txt; } if (config.migrations === false && !iscore) { const txt = `migrations skip: path - ${dirPath}`; if (debug) console.warn(`⚠️ ${txt}`); return txt; } if (process.env.NODE_ENV !== "production" && !process.env.MIGRATE && !(iscore ? config.migrationsCore : config.migrations)) { const txt = `migrations skip: not a production environment - ${iscore ? "core" : "path"} : ${dirPath}`; if (debug) console.warn(`⚠️ ${txt}`); return txt; } if (debug) console.log("migrations start", dirPath, Date.now() - time); const exists = existsSync(dirPath); if (!exists) { const txt = `migrations skip: directory not found - ${dirPath}`; if (debug) console.warn(`⚠️ ${txt}`); return txt; } // get directory sql file list const content = readdirSync(dirPath, { withFileTypes: true }) ?.filter((el) => el.isFile() && path.extname(el.name) === ".sql") ?.map((el) => el.name) || []; // execute sql files if (!content?.length) { const txt = `migrations skip: no sql in specified directory - ${dirPath}`; if (debug) console.warn(`⚠️ ${txt}`); return txt; } await content.reduce((promise, filename) => promise.then(() => execSql(path.join(dirPath, filename), pg)), Promise.resolve()); if (debug) console.log("migrations success", dirPath, exists, Date.now() - time); return "success"; }