Skip to content

Commit

Permalink
fix: require ts optimistically (#388)
Browse files Browse the repository at this point in the history
  • Loading branch information
mmkal committed Nov 19, 2020
1 parent 59c7311 commit 89ed877
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/umzug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,10 @@ export class Umzug<Ctx> extends EventEmitter {
}

const ext = path.extname(filepath);
const canRequire = ext === '.js' || ext in require.extensions;
const canRequire = ext === '.js' || ext === '.ts';
const languageSpecificHelp: Record<string, string> = {
'.ts':
"You can use the default resolver with typescript files by adding `ts-node` as a dependency and calling `require('ts-node/register')` at the program entrypoint before running migrations.",
"TypeScript files can be required by adding `ts-node` as a dependency and calling `require('ts-node/register')` at the program entrypoint before running migrations.",
'.sql': 'Try writing a resolver which reads file content and executes it as a sql query.',
};
if (!canRequire) {
Expand All @@ -183,7 +183,17 @@ export class Umzug<Ctx> extends EventEmitter {
throw new Error(errorParts.filter(Boolean).join(' '));
}

const getModule = () => require(filepath);
const getModule = () => {
try {
return require(filepath);
} catch (e: unknown) {
if (e instanceof Error && filepath.endsWith('.ts')) {
e.message += '\n\n' + languageSpecificHelp['.ts'];
}

throw e;
}
};

return {
name,
Expand Down
27 changes: 27 additions & 0 deletions test/umzug.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,33 @@ describe('alternate migration inputs', () => {
expect(spy).toHaveBeenNthCalledWith(1, 'migration1-up');
});

test('typescript migration files', async () => {
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/typescript'), {
'm1.ts': `export const up = () => {}; export const down = () => {}`,
'm2.ts': `throw Error('Error to simulate typescript modules not being registered')`,
});
syncer.sync();

const umzug = new Umzug({
migrations: {
glob: ['*.ts', { cwd: syncer.baseDir }],
},
logger: undefined,
});

expect([names(await umzug.pending()), names(await umzug.executed())]).toEqual([['m1.ts', 'm2.ts'], []]);

await umzug.up({ to: 'm1.ts' });

expect([names(await umzug.pending()), names(await umzug.executed())]).toEqual([['m2.ts'], ['m1.ts']]);

await expect(umzug.up()).rejects.toThrowErrorMatchingInlineSnapshot(`
"Error to simulate typescript modules not being registered
TypeScript files can be required by adding \`ts-node\` as a dependency and calling \`require('ts-node/register')\` at the program entrypoint before running migrations."
`);
});

test('with custom file globbing options', async () => {
const spy = jest.fn();

Expand Down

0 comments on commit 89ed877

Please sign in to comment.