-
Notifications
You must be signed in to change notification settings - Fork 5
/
ts-file-migration-provider.mts
75 lines (60 loc) · 1.97 KB
/
ts-file-migration-provider.mts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { consola } from 'consola'
import type { Migration, MigrationProvider } from 'kysely'
import { join } from 'pathe'
import { filename } from 'pathe/utils'
import { getFileType } from '../utils/get-file-type.mjs'
import { importTSFile } from '../utils/import-ts-file.mjs'
import { safeReaddir } from '../utils/safe-readdir.mjs'
/**
* An opinionated migration provider that reads migrations from TypeScript files.
* Same as `FileMigrationProvider` but works in ESM/CJS without loader flag/s,
* and on Windows too.
*/
export class TSFileMigrationProvider implements MigrationProvider {
readonly #props: TSFileMigrationProviderProps
constructor(props: TSFileMigrationProviderProps) {
this.#props = props
}
async getMigrations(): Promise<Record<string, Migration>> {
const migrations: Record<string, Migration> = {}
const files = await safeReaddir(this.#props.migrationFolder)
for (const fileName of files) {
const fileType = getFileType(fileName)
const isTS = fileType === 'TS'
if (!isTS) {
if (!this.#props.allowJS) {
consola.warn(`Ignoring \`${fileName}\` - not a TS file.`)
continue
}
if (fileType !== 'JS') {
consola.warn(`Ignoring \`${fileName}\` - not a TS/JS file.`)
continue
}
}
const filePath = join(this.#props.migrationFolder, fileName)
const migration = await (isTS ? importTSFile(filePath) : import(filePath))
const migrationKey = filename(fileName)
if (isMigration(migration?.default)) {
migrations[migrationKey] = migration.default
} else if (isMigration(migration)) {
migrations[migrationKey] = migration
} else {
consola.warn(`Ignoring \`${fileName}\` - not a migration.`)
}
}
return migrations
}
}
function isMigration(obj: unknown): obj is Migration {
return (
typeof obj === 'object' &&
obj !== null &&
!Array.isArray(obj) &&
'up' in obj &&
typeof obj.up === 'function'
)
}
export interface TSFileMigrationProviderProps {
allowJS?: boolean
migrationFolder: string
}