Skip to content

Instantly share code, notes, and snippets.

@igrek8
Last active November 26, 2019 10:58
Show Gist options
  • Select an option

  • Save igrek8/7ae5f58b929d81dd683a342dc7cf148a to your computer and use it in GitHub Desktop.

Select an option

Save igrek8/7ae5f58b929d81dd683a342dc7cf148a to your computer and use it in GitHub Desktop.
knex.js typescrips migrations (fix the migration directory is corrupt)

TypeScript migrations for knex.js

Fix the migration directory is corrupt

Migrations will work in both production/development environments. You may also have declrations/source maps generated in the migrations directory and the migration source will skip them.

import Knex from "knex";
import path from "path";
import { MigrationSource } from "./migration-source";
const migrationDir = path.resolve(__dirname, "migrations");
export const knex = Knex({
migrations: {
migrationSource: new MigrationSource(migrationDir),
},
});
import fs from "fs";
import path from "path";
import { promisify } from "util";
export class MigrationSource {
constructor(protected migrationDir: string) {}
async getMigrations() {
const dir = await promisify(fs.readdir)(this.migrationDir);
const migrations = dir.filter(fileName => !/(\.d\.ts|\.map)$/.test(fileName));
return migrations;
}
getMigrationName(migrationName: string) {
const migrationId = migrationName.replace(/\.(js|ts)$/, "");
return migrationId;
}
getMigration(migrationName: string) {
const migrationFilePath = path.resolve(this.migrationDir, migrationName);
const migration = require(migrationFilePath);
return migration;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment