mongodb-migrations icon indicating copy to clipboard operation
mongodb-migrations copied to clipboard

It would be really cool if we could write migrations in typescript

Open vadim82 opened this issue 8 years ago • 3 comments

A nice advantage of this is, we would then be able to get the @typings for mongodb and get intellisense for the entire mongo api.

vadim82 avatar Jan 30 '17 20:01 vadim82

I like TS myself but there are dozens of compile-to-JS languages and it would be impractical to have special handling for each of them. CoffeeScript is an exception historically but I consider dropping its support in v1 or v2.

Instead I'm interested in discussing the possibilities of writing your migrations in any language and making the module recognize them. Right now I see three options:

a) programmatic usage of the module with a bit of extra config. If TS has a register mode similar to require('coffee-script/register') you would be able to configure the extensions to recognize and Node's require will just be able to pick the modules.

b) add a simple wrapper script that builds the migrations in place (.ts -> .js) and then use the binary as is

c) support --compiler option as mocha does.

emirotin avatar Jan 30 '17 21:01 emirotin

There's another option, which is the absolute minimum:

  • Give the very basic type support for up and down functions
  • The user will care about building the project

Now I use this:

import * as mongoose from 'mongoose';

interface Migrator {
	db: mongoose.Connection;
	log: Function;
}

interface DoneCallback {
	(): void;
	(error: any): void;
}

export const id = 'ProposalPrice';

export function up (this: Migrator, done: DoneCallback) {
	// use this.db for MongoDB communication, and this.log() for logging
};

export function down (this: Migrator, done: DoneCallback) {
	// use this.db for MongoDB communication, and this.log() for logging
	done();
};

Of course the types can be generated to migrations/types.d.ts, then the migration files should only contain import { Migrator, DoneCallback } from './types'.

igabesz avatar Feb 25 '17 12:02 igabesz

Right now I have the following project structure:

  • migrations
    • migrations
      • <migration scripts: TS + JS (built)>
      • types.d.ts (see above)
    • generate-config.ts (script to generate mm-config.json)
    • generate-config.js (built)
    • mm-config.json (generated)
    • tsconfig.json
  • package.json

And I have the following npm scripts:

  • "build:migrate": "cd migrations && tsc"
  • "migrate": "cd migrations && node generate-config.js && mm migrate"

Just an example for using typed migration scripts + my own build system.

igabesz avatar Feb 25 '17 22:02 igabesz