UNPKG

1.89 kBJavaScriptView Raw
1const {
2 findConfig,
3 getConfig,
4 getSampleConfig,
5} = require('./config')
6const {
7 getSampleMigration,
8 runPendingMigrations,
9} = require('./migrations')
10const {
11 mkdir,
12 writeFile,
13} = require('./utils/fs')
14const path = require('path')
15const slugify = require('slugify')
16
17exports.getConfig = getConfig
18
19/**
20 * Create a sample configuration in the supplied path
21 */
22exports.init = async (targetPath) => {
23 const existingConfigPath = await findConfig()
24 .catch(err => {
25 if (err.code === 'NOCONFIG') return false
26 throw err
27 })
28 const sampleConfig = await getSampleConfig()
29 if (existingConfigPath) {
30 const err = new Error(`A configuration already exists in "${existingConfigPath}"`)
31 err.code = 'INITEXISTS'
32 throw err
33 }
34 return writeFile(targetPath, sampleConfig)
35}
36
37/**
38 * Create a migration file in the migrations directory
39 */
40exports.create = async (name) => {
41 const config = await getConfig()
42
43 // Make sure migrationsDirectory exists, otherwise create it.
44 const targetDir = config.migrationsDirectory
45 await mkdir(targetDir, { recursive: true })
46
47 const targetName = `${Date.now()}-${slugify(name, { lower: true })}.js`
48 const targetPath = path.join(targetDir, targetName)
49 const template = await getSampleMigration()
50 await writeFile(targetPath, template, 'utf8')
51 return targetPath
52}
53
54/**
55 * Run all unprocessed migrations
56 */
57exports.migrate = async () => {
58 // find the config
59 const config = await getConfig()
60
61 // Initialize context and load history
62 const context = config.context ? await config.context() : {}
63
64 const ranMigrations = await runPendingMigrations()
65
66 const state = await config.fetchState(context)
67 return { state, ranMigrations }
68}
69/**
70 * TODO: Remove in ^2.0.0
71 *
72 * @deprecated
73 */
74exports.run = this.migrate
75
76exports.rollback = async () => {}
77
78exports.up = async () => {}
79
80exports.down = async () => {}