-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
runner.ts
97 lines (82 loc) · 2.52 KB
/
runner.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { Application } from '@adonisjs/core/app'
import { FileNode, QueryClientContract, SharedConfigNode } from '../types/database.js'
import { SeederConstructorContract, SeederFileNode } from '../types/seeder.js'
import { SeedersSource } from './source.js'
import { Database } from '../database/main.js'
/**
* Seeds Runner exposes the API to traverse seeders and execute them
* in bulk
*/
export class SeedsRunner {
private client: QueryClientContract
private config: SharedConfigNode
nodeEnvironment: string
constructor(
private db: Database,
private app: Application<any>,
private connectionName?: string
) {
this.client = this.db.connection(this.connectionName || this.db.primaryConnectionName)
this.config = this.db.getRawConnection(this.client.connectionName)!.config
this.nodeEnvironment = this.app.nodeEnvironment
}
/**
* Returns the seeder source by ensuring value is a class constructor
*/
private async getSeederSource(file: FileNode<unknown>): Promise<SeederConstructorContract> {
const source = await file.getSource()
if (typeof source === 'function') {
return source as SeederConstructorContract
}
throw new Error(`Invalid schema class exported by "${file.name}"`)
}
/**
* Returns an array of seeders
*/
async getList() {
return new SeedersSource(this.config, this.app).getSeeders()
}
/**
* Executes the seeder
*/
async run(file: FileNode<unknown>): Promise<SeederFileNode> {
const Source = await this.getSeederSource(file)
const seeder: SeederFileNode = {
status: 'pending',
file: file,
}
/**
* Ignore when the node environment is not the same as the seeder configuration.
*/
if (Source.environment && !Source.environment.includes(this.nodeEnvironment)) {
seeder.status = 'ignored'
return seeder
}
try {
const seederInstance = new Source(this.client)
if (typeof seederInstance.run !== 'function') {
throw new Error(`Missing method "run" on "${seeder.file.name}" seeder`)
}
await seederInstance.run()
seeder.status = 'completed'
} catch (error) {
seeder.status = 'failed'
seeder.error = error
}
return seeder
}
/**
* Close database connections
*/
async close() {
await this.db.manager.closeAll(true)
}
}