1 |
|
2 | const fs = require('./utils/fs')
|
3 | const path = require('path')
|
4 |
|
5 | exports.getSampleConfig = async () => {
|
6 | return fs.readFile(path.resolve(__dirname, './templates/config.js'), 'utf8')
|
7 | }
|
8 |
|
9 | exports.findConfig = async () => {
|
10 | const configName = 'exodus.config.js'
|
11 | const targetConfig = await fs.findUpwardsFile(configName)
|
12 | if (!targetConfig) {
|
13 | const err = new Error(`Could not find ${configName} in this or any parent directories.`)
|
14 | err.code = 'NOCONFIG'
|
15 | throw err
|
16 | }
|
17 | return targetConfig
|
18 | }
|
19 |
|
20 | let _config
|
21 | let _context
|
22 | let _state
|
23 | exports.getConfig = async () => {
|
24 | if (!_config) {
|
25 | const targetConfig = await this.findConfig()
|
26 |
|
27 | const externalConfig = require(targetConfig)
|
28 | _config = {
|
29 | ...defaultConfig,
|
30 | ...externalConfig,
|
31 | }
|
32 |
|
33 | const configDir = path.dirname(targetConfig)
|
34 | _config.migrationsDirectory = path.resolve(
|
35 | configDir,
|
36 | _config.migrationsDirectory
|
37 | )
|
38 |
|
39 |
|
40 | if (!_config.storeState) {
|
41 | const statePath = path.join(configDir, 'exodus.state.json')
|
42 | _config.storeState = async (state) => {
|
43 | return fs.writeFile(statePath, JSON.stringify(state, null, 2), 'utf8')
|
44 | }
|
45 | }
|
46 | if (!_config.fetchState) {
|
47 | _config.fetchState = async () => {
|
48 | const statePath = path.join(configDir, 'exodus.state.json')
|
49 | try {
|
50 | return JSON.parse(await fs.readFile(statePath, 'utf8'))
|
51 | } catch (err) {
|
52 | if (err.code !== 'ENOENT') throw err
|
53 | return {}
|
54 | }
|
55 | }
|
56 | }
|
57 |
|
58 |
|
59 | const originalStateGetter = _config.fetchState
|
60 | _config.fetchState = async (...args) => {
|
61 | if (!_state) {
|
62 | _state = await originalStateGetter(...args)
|
63 | if (!_state) _state = {}
|
64 | _state.history = _state.history || []
|
65 | }
|
66 | return _state
|
67 | }
|
68 |
|
69 |
|
70 | const originalContextGetter = _config.context
|
71 | _config.context = async (...args) => {
|
72 | if (!_context) {
|
73 | _context = await originalContextGetter(...args)
|
74 | }
|
75 | return _context
|
76 | }
|
77 | }
|
78 | return _config
|
79 | }
|
80 |
|
81 | const defaultConfig = {
|
82 | |
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 | migrationsDirectory: './migrations',
|
89 |
|
90 | |
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 | context: async () => {
|
100 | return {}
|
101 | },
|
102 |
|
103 | |
104 |
|
105 |
|
106 |
|
107 |
|
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|
115 | |
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 | beforeAll: async (pendingMigrations) => {},
|
129 |
|
130 |
|
131 | beforeEach: async (migrationJob) => {},
|
132 |
|
133 |
|
134 | afterEach: async (migrationJob) => {},
|
135 |
|
136 |
|
137 | afterAll: async (pendingMigrations) => {},
|
138 |
|
139 | }
|