@jorgebodega/typeorm-seeding 5.0.1 → 6.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +24 -266
  3. package/dist/cli.d.ts +1 -1
  4. package/dist/cli.js +2 -12
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/seed.command.d.ts +1 -25
  7. package/dist/commands/seed.command.js +50 -131
  8. package/dist/commands/seed.command.js.map +1 -1
  9. package/dist/datasource/DataSourceManager.d.ts +1 -1
  10. package/dist/datasource/DataSourceManager.js +1 -1
  11. package/dist/datasource/DataSourceManager.js.map +1 -1
  12. package/dist/errors/DataSourceImportationError.d.ts +2 -0
  13. package/dist/errors/DataSourceImportationError.js +7 -0
  14. package/dist/errors/DataSourceImportationError.js.map +1 -0
  15. package/dist/errors/SeederExecutionError.d.ts +2 -0
  16. package/dist/errors/SeederExecutionError.js +7 -0
  17. package/dist/errors/SeederExecutionError.js.map +1 -0
  18. package/dist/errors/SeederImportationError.d.ts +0 -1
  19. package/dist/errors/SeederImportationError.js +0 -3
  20. package/dist/errors/SeederImportationError.js.map +1 -1
  21. package/dist/errors/index.d.ts +2 -0
  22. package/dist/errors/index.js +2 -0
  23. package/dist/errors/index.js.map +1 -1
  24. package/dist/helpers/useDataSource.js +1 -1
  25. package/dist/helpers/useDataSource.js.map +1 -1
  26. package/dist/index.d.ts +0 -4
  27. package/dist/index.js +0 -4
  28. package/dist/index.js.map +1 -1
  29. package/dist/types.d.ts +3 -7
  30. package/dist/utils/commandUtils.d.ts +7 -0
  31. package/dist/utils/commandUtils.js +52 -0
  32. package/dist/utils/commandUtils.js.map +1 -0
  33. package/dist/utils/fileHandling.js +2 -2
  34. package/dist/utils/fileHandling.js.map +1 -1
  35. package/dist/utils/index.d.ts +2 -0
  36. package/dist/utils/index.js +6 -0
  37. package/dist/utils/index.js.map +1 -0
  38. package/package.json +4 -9
  39. package/pnpm-lock.yaml +31 -6
  40. package/dist/factory.d.ts +0 -28
  41. package/dist/factory.js +0 -87
  42. package/dist/factory.js.map +0 -1
  43. package/dist/instanceAttribute.d.ts +0 -3
  44. package/dist/instanceAttribute.js +0 -8
  45. package/dist/instanceAttribute.js.map +0 -1
  46. package/dist/lazyAttribute.d.ts +0 -6
  47. package/dist/lazyAttribute.js +0 -13
  48. package/dist/lazyAttribute.js.map +0 -1
  49. package/dist/lazyInstanceAttribute.d.ts +0 -3
  50. package/dist/lazyInstanceAttribute.js +0 -8
  51. package/dist/lazyInstanceAttribute.js.map +0 -1
  52. package/dist/subfactory.d.ts +0 -13
  53. package/dist/subfactory.js +0 -24
  54. package/dist/subfactory.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,33 @@
1
+ # [6.0.0-next.1](https://github.com/jorgebodega/typeorm-seeding/compare/v5.0.1-next.1...v6.0.0-next.1) (2022-08-18)
2
+
3
+
4
+ ### chore
5
+
6
+ * remove factory definitions ([f2ede7c](https://github.com/jorgebodega/typeorm-seeding/commit/f2ede7c952a106db98ef817e6c9fc34a1a79dd96))
7
+
8
+
9
+ ### Features
10
+
11
+ * force major version ([73ade47](https://github.com/jorgebodega/typeorm-seeding/commit/73ade475e1a1f44764d4090b04fe2abf9fcbe61b))
12
+
13
+
14
+ ### BREAKING CHANGES
15
+
16
+ * Force version 6
17
+ * remove all factory related code in favor of @jorgebodega/typeorm-factory
18
+
19
+ ## [5.0.1-next.2](https://github.com/jorgebodega/typeorm-seeding/compare/v5.0.1-next.1...v5.0.1-next.2) (2022-08-18)
20
+
21
+
22
+ ### chore
23
+
24
+ * remove factory definitions ([f2ede7c](https://github.com/jorgebodega/typeorm-seeding/commit/f2ede7c952a106db98ef817e6c9fc34a1a79dd96))
25
+
26
+
27
+ ### BREAKING CHANGES
28
+
29
+ * remove all factory related code in favor of @jorgebodega/typeorm-factory
30
+
1
31
  ## [5.0.1](https://github.com/jorgebodega/typeorm-seeding/compare/v5.0.0...v5.0.1) (2022-08-18)
2
32
 
3
33
 
package/README.md CHANGED
@@ -4,33 +4,16 @@
4
4
  <h1 align="center" style="text-align: center;">TypeORM Seeding</h1>
5
5
 
6
6
  <p align="center">
7
- <img alt="NPM" src="https://img.shields.io/npm/l/@jorgebodega/typeorm-seeding?style=for-the-badge">
8
- <a href="https://www.npmjs.com/package/@jorgebodega/typeorm-seeding">
9
- <img alt="NPM latest version" src="https://img.shields.io/npm/v/@jorgebodega/typeorm-seeding/latest?style=for-the-badge">
10
- </a>
11
- <a href="https://www.npmjs.com/package/@jorgebodega/typeorm-seeding/v/next">
12
- <img alt="NPM next version" src="https://img.shields.io/npm/v/@jorgebodega/typeorm-seeding/next?style=for-the-badge">
13
- </a>
7
+ <img alt="License" src="https://img.shields.io/npm/l/@jorgebodega/typeorm-seeding?style=for-the-badge">
14
8
  <a href="https://github.com/semantic-release/semantic-release">
15
9
  <img src="https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release&style=for-the-badge" alt="Semantic release" />
16
10
  </a>
17
- </p>
18
-
19
- <p align="center">
20
11
  <a href='https://coveralls.io/github/jorgebodega/typeorm-seeding'>
21
12
  <img alt="Coveralls master branch" src="https://img.shields.io/coveralls/github/jorgebodega/typeorm-seeding/master?style=for-the-badge">
22
13
  </a>
23
- <a href='https://coveralls.io/github/jorgebodega/typeorm-seeding?branch=next'>
24
- <img alt="Coveralls next branch" src="https://img.shields.io/coveralls/github/jorgebodega/typeorm-seeding/next?style=for-the-badge&label=coverage%40next">
25
- </a>
26
14
  </p>
27
15
 
28
- <p align="center">
29
- <img alt="Checks for master branch" src="https://img.shields.io/github/checks-status/jorgebodega/typeorm-seeding/master?style=for-the-badge">
30
- <a href='https://coveralls.io/github/jorgebodega/typeorm-seeding'>
31
- <img alt="Checks for next branch" src="https://img.shields.io/github/checks-status/jorgebodega/typeorm-seeding/next?label=checks%40next&style=for-the-badge">
32
- </a>
33
- </p>
16
+
34
17
 
35
18
  <p align="center">
36
19
  <b>A delightful way to seed test data into your database.</b></br>
@@ -45,15 +28,6 @@
45
28
 
46
29
  # Contents
47
30
 
48
- - [Factory](#factory-1)
49
- - [attrs](#attrs)
50
- - [Simple value](#simple-value)
51
- - [Function](#function)
52
- - [InstanceAttribute](#instanceattribute)
53
- - [LazyInstanceAttribute](#lazyinstanceattribute)
54
- - [Subfactory](#subfactory)
55
- - [make & makeMany](#make--makemany)
56
- - [create & createMany](#create--createmany)
57
31
  - [Seeder](#seeder-1)
58
32
  - [run](#run)
59
33
  - [CLI](#cli-configuration)
@@ -72,27 +46,6 @@ yarn add [-D] @jorgebodega/typeorm-seeding
72
46
  pnpm add [-D] @jorgebodega/typeorm-seeding
73
47
  ```
74
48
 
75
- ## Configuration
76
-
77
- To configure the path to your seeders extends the TypeORM config file or use environment variables like TypeORM. If both are used the environment variables will be prioritized.
78
-
79
- **ormconfig.js**
80
-
81
- ```typescript
82
- module.exports = {
83
- ...
84
- seeders: ['src/seeds/**/*{.ts,.js}'],
85
- defaultSeeder: RootSeeder,
86
- ...
87
- }
88
- ```
89
-
90
- **.env**
91
-
92
- ```
93
- TYPEORM_SEEDING_SEEDERS=src/seeds/**/*{.ts,.js}
94
- TYPEORM_SEEDING_DEFAULT_SEEDER=RootSeeder
95
- ```
96
49
 
97
50
  # Introduction
98
51
 
@@ -126,226 +79,24 @@ class User {
126
79
  }
127
80
  ```
128
81
 
129
- ### Factory
130
-
131
- ```typescript
132
- class UserFactory extends Factory<User> {
133
- protected entity = User
134
- protected attrs: FactorizedAttrs<User> = {
135
- name: faker.name.firstName(),
136
- lastName: async () => faker.name.lastName(),
137
- email: new InstanceAttribute((instance) =>
138
- [instance.name.toLowerCase(), instance.lastName.toLowerCase(), '@email.com'].join(''),
139
- ),
140
- country: new Subfactory(CountryFactory),
141
- }
142
- }
143
- ```
144
-
145
82
  ### Seeder
146
83
 
147
84
  ```typescript
148
85
  class UserSeeder extends Seeder {
149
- async run(connection: Connection) {
150
- await new UserFactory().createMany(10)
151
-
152
- await this.call(connection, [PetSeeder])
153
- }
154
- }
155
- ```
156
-
157
- # Factory
158
-
159
- Factory is how we provide a way to simplify entities creation, implementing a [factory creational pattern](https://refactoring.guru/design-patterns/factory-method). It is defined as an abstract class with generic typing, so you have to extend over it.
160
-
161
- ```typescript
162
- class UserFactory extends Factory<User> {
163
- protected entity = User
164
- protected attrs: FactorizedAttrs<User> = {
165
- ...
86
+ async run(dataSource: DataSource) {
87
+ const users: User[] = [...]
88
+ await dataSource.createEntityManager().save<User>(users)
166
89
  }
167
90
  }
168
91
  ```
169
92
 
170
- ## `attrs`
171
-
172
- Attributes objects are superset from the original entity attributes.
173
-
174
- ```typescript
175
- protected attrs: FactorizedAttrs<User> = {
176
- name: faker.name.firstName(),
177
- lastName: async () => faker.name.lastName(),
178
- email: new InstanceAttribute((instance) =>
179
- [instance.name.toLowerCase(), instance.lastName.toLowerCase(), '@email.com'].join(''),
180
- ),
181
- country: new Subfactory(CountryFactory),
182
- }
183
- ```
184
-
185
- Those factorized attributes resolves to the value of the original attribute, and could be one of the following types:
186
-
187
- - [Simple value](#simple-value)
188
- - [Function](#function)
189
- - [InstanceAttribute](#instanceattribute)
190
- - [LazyInstanceAttribute](#lazyinstanceattribute)
191
- - [Subfactory](#subfactory)
192
-
193
- ### Simple value
194
-
195
- Nothing special, just a value with same type.
196
-
197
- ```typescript
198
- protected attrs: FactorizedAttrs<User> = {
199
- name: faker.name.firstName(),
200
- }
201
- ```
202
-
203
- ### Function
204
-
205
- Function that could be sync or async, and return a value of the same type. This function will be executed once per entity.
206
-
207
- ```typescript
208
- protected attrs: FactorizedAttrs<User> = {
209
- lastName: async () => faker.name.lastName(),
210
- }
211
- ```
212
-
213
- ### `InstanceAttribute`
214
-
215
- ```typescript
216
- class InstanceAttribute<T, V> {
217
- constructor(private callback: (entity: T) => V) {}
218
-
219
- ...
220
- }
221
- ```
222
-
223
- Class with a function that receive the current instance and returns a value of the same type. It is ideal for attributes that could depend on some others to be computed.
224
-
225
- Will be executed after the entity has been created and the rest of the attributes have been calculated, but before persistance (in case of `create` or `createMany`).
226
-
227
- ```typescript
228
- protected attrs: FactorizedAttrs<User> = {
229
- name: faker.name.firstName(),
230
- lastName: async () => faker.name.lastName(),
231
- email: new InstanceAttribute((instance) =>
232
- [instance.name.toLowerCase(), instance.lastName.toLowerCase(), '@email.com'].join(''),
233
- ),
234
- }
235
- ```
236
-
237
- In this simple case, if `name` or `lastName` override the value in any way, the `email` attribute will be affected too.
238
-
239
- ### `LazyInstanceAttribute`
240
-
241
- ```typescript
242
- class LazyInstanceAttribute<T, V> {
243
- constructor(private callback: (entity: T) => V) {}
244
-
245
- ...
246
- }
247
- ```
248
-
249
- Class with similar functionality than `InstanceAttribute`, but it will be executed only after persistance. This is useful for attributes that depends on the database id, like relations.
250
-
251
- Just remember that, if you use `make` or `makeMany`, the only difference between `InstanceAttribute` and `LazyInstanceAttribute` is that `LazyInstanceAttribute` will be processed the last.
252
-
253
- ```typescript
254
- protected attrs: FactorizedAttrs<User> = {
255
- name: faker.name.firstName(),
256
- email: new LazyInstanceAttribute((instance) =>
257
- [instance.name.toLowerCase(), instance.id, '@email.com'].join(''),
258
- ),
259
- }
260
- ```
261
-
262
- ### `Subfactory`
263
-
264
- ```typescript
265
- export class Subfactory<T> {
266
- constructor(factory: Constructable<Factory<T>>)
267
- constructor(factory: Constructable<Factory<T>>, values?: Partial<FactorizedAttrs<T>>)
268
- constructor(factory: Constructable<Factory<T>>, count?: number)
269
- constructor(factory: Constructable<Factory<T>>, values?: Partial<FactorizedAttrs<T>>, count?: number)
270
-
271
- ...
272
- }
273
- ```
274
-
275
- Subfactories are just a wrapper of another factory, to avoid explicit operations that could lead to unexpected results over that factory, like
276
-
277
- ```typescript
278
- protected attrs: FactorizedAttrs<User> = {
279
- country: async () => new CountryFactory().create({
280
- name: faker.address.country(),
281
- }),
282
- }
283
- ```
284
-
285
- instead of
286
-
287
- ```typescript
288
- protected attrs: FactorizedAttrs<User> = {
289
- country: new Subfactory(CountryFactory, {
290
- name: faker.address.country(),
291
- }),
292
- }
293
- ```
294
-
295
- Subfactory just execute the same kind of operation (`make` or `create`) over the factory. If `count` param is provided, it will execute `makeMany`/`createMany` instead of `make`/`create`, and returns an array.
296
-
297
- ## `make` & `makeMany`
298
-
299
- Make and makeMany executes the factory functions and return a new instance of the given entity. The instance is filled with the generated values from the factory function, but not saved in the database.
300
-
301
- - **overrideParams** - Override some of the attributes of the entity.
302
-
303
- ```typescript
304
- make(overrideParams: Partial<FactorizedAttrs<T>> = {}): Promise<T>
305
- makeMany(amount: number, overrideParams: Partial<FactorizedAttrs<T>> = {}): Promise<T[]>
306
- ```
307
-
308
- ```typescript
309
- new UserFactory().make()
310
- new UserFactory().makeMany(10)
311
-
312
- // override the email
313
- new UserFactory().make({ email: 'other@mail.com' })
314
- new UserFactory().makeMany(10, { email: 'other@mail.com' })
315
- ```
316
-
317
- ## `create` & `createMany`
318
-
319
- the create and createMany method is similar to the make and makeMany method, but at the end the created entity instance gets persisted in the database using TypeORM entity manager.
320
-
321
- - **overrideParams** - Override some of the attributes of the entity.
322
- - **saveOptions** - [Save options](https://github.com/typeorm/typeorm/blob/master/src/repository/SaveOptions.ts) from TypeORM
323
-
324
- ```typescript
325
- create(overrideParams: Partial<FactorizedAttrs<T>> = {}, saveOptions?: SaveOptions): Promise<T>
326
- createMany(amount: number, overrideParams: Partial<FactorizedAttrs<T>> = {}, saveOptions?: SaveOptions): Promise<T[]>
327
- ```
328
-
329
- ```typescript
330
- new UserFactory().create()
331
- new UserFactory().createMany(10)
332
-
333
- // override the email
334
- new UserFactory().create({ email: 'other@mail.com' })
335
- new UserFactory().createMany(10, { email: 'other@mail.com' })
336
-
337
- // using save options
338
- new UserFactory().create({ email: 'other@mail.com' }, { listeners: false })
339
- new UserFactory().createMany(10, { email: 'other@mail.com' }, { listeners: false })
340
- ```
341
-
342
93
  # Seeder
343
94
 
344
95
  Seeder class is how we provide a way to insert data into databases, and could be executed by the command line or by helper method. Is an abstract class with one method to be implemented, and a helper function to run some more seeder sequentially.
345
96
 
346
97
  ```typescript
347
98
  class UserSeeder extends Seeder {
348
- async run(connection: Connection) {
99
+ async run(dataSource: DataSource) {
349
100
  ...
350
101
  }
351
102
  }
@@ -353,42 +104,45 @@ class UserSeeder extends Seeder {
353
104
 
354
105
  ## `run`
355
106
 
356
- This function is the one that needs to be defined when extending the class. Could use `call` to run some other seeders.
107
+ This function is the one that needs to be defined when extending the class.
357
108
 
358
109
  ```typescript
359
- run(connection: Connection): Promise<void>
110
+ run(dataSource: DataSource): Promise<void>
360
111
  ```
361
112
 
362
113
  ```typescript
363
- async run(connection: Connection) {
364
- await new UserFactory().createMany(10)
365
-
366
- await this.call(connection, [PetSeeder])
114
+ async run(dataSource: DataSource) {
115
+ const users: User[] = [...]
116
+ await dataSource.createEntityManager().save<User>(users)
367
117
  }
368
118
  ```
369
119
 
370
120
  # CLI Configuration
371
121
 
372
- There are two possible commands to execute, one to see the current configuration and one to run a seeder.
122
+ There is a command that allows you to execute multiple seeders from cli.
123
+
124
+ ```bash
125
+ typeorm-seeding seed -d path/to/datasource src/seeders/*.ts
126
+ ```
373
127
 
374
- Add the following scripts to your `package.json` file to configure them.
128
+ Add the following script to your `package.json` file to configure them.
375
129
 
376
130
  ```json
377
131
  "scripts": {
378
- "seed:run": "typeorm-seeding seed",
132
+ "seed:run": "typeorm-seeding seed -d path/to/datasource",
379
133
  ...
380
134
  }
381
135
  ```
382
136
 
383
137
  ## `seed`
384
138
 
385
- This command execute a seeder, that could be specified as a parameter.
139
+ This command execute a seeder, that could be specified as a parameter. Glob pattern is supported.
386
140
 
387
141
  ```bash
388
142
  typeorm-seeding seed <path>
389
143
  ```
390
144
 
391
- The name of the seeder to execute (either set with the `--seed` option or with default in [configs](#configuration)) must be the seeder's class name, and thus, the seeder must be exported with a named export. Please avoid default export for seeders: it may imply unwanted behavior. (See [\#75](https://github.com/jorgebodega/typeorm-seeding/issues/75)).
145
+ CLI command only executes default seeders.
392
146
 
393
147
  ##### Options
394
148
 
@@ -427,3 +181,7 @@ useDataSource(
427
181
  forceInitialization: boolean,
428
182
  ): Promise<void>
429
183
  ```
184
+
185
+ # Factory
186
+
187
+ Factory related code has been removed from this package, now on [@jorgebodega/typeorm-factory](https://github.com/jorgebodega/typeorm-factory).
package/dist/cli.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import 'reflect-metadata';
2
+ export {};
package/dist/cli.js CHANGED
@@ -1,17 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- const tslib_1 = require("tslib");
5
- /* istanbul ignore file */
6
- require("reflect-metadata");
7
- const yargs_1 = tslib_1.__importDefault(require("yargs"));
8
4
  const seed_command_1 = require("./commands/seed.command");
9
- yargs_1.default
10
- .usage('Usage: $0 <command> [options]')
11
- .command(new seed_command_1.SeedCommand())
12
- .recommendCommands()
13
- .demandCommand(1)
14
- .strict()
15
- .help('h')
16
- .alias('h', 'help').argv;
5
+ /* istanbul ignore file */
6
+ (0, seed_command_1.bootstrap)(process.argv);
17
7
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;AACA,0BAA0B;AAC1B,4BAAyB;AACzB,0DAAyB;AACzB,0DAAqD;AAErD,eAAK;KACF,KAAK,CAAC,+BAA+B,CAAC;KACtC,OAAO,CAAC,IAAI,0BAAW,EAAE,CAAC;KAC1B,iBAAiB,EAAE;KACnB,aAAa,CAAC,CAAC,CAAC;KAChB,MAAM,EAAE;KACR,IAAI,CAAC,GAAG,CAAC;KACT,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,IAAI,CAAA"}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;AACA,0DAAmD;AACnD,0BAA0B;AAC1B,IAAA,wBAAS,EAAC,OAAO,CAAC,IAAI,CAAC,CAAA"}
@@ -1,25 +1 @@
1
- import { DataSource } from 'typeorm';
2
- import { Arguments, Argv, CommandModule } from 'yargs';
3
- import { Seeder } from '../seeder';
4
- import type { Constructable } from '../types';
5
- interface SeedCommandArguments extends Arguments {
6
- dataSource?: string;
7
- path?: string;
8
- }
9
- export declare class SeedCommand implements CommandModule {
10
- command: string;
11
- describe: string;
12
- /**
13
- * @inheritdoc
14
- */
15
- builder(args: Argv): Argv<{
16
- d: string;
17
- }>;
18
- /**
19
- * @inheritdoc
20
- */
21
- handler(args: SeedCommandArguments): Promise<void>;
22
- static loadDataSource(dataSourceFilePath: string): Promise<DataSource>;
23
- static loadSeeders(seederPaths: string[]): Promise<Constructable<Seeder>[]>;
24
- }
25
- export {};
1
+ export declare function bootstrap(argv: string[]): Promise<void>;
@@ -1,145 +1,64 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SeedCommand = void 0;
3
+ exports.bootstrap = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const node_path_1 = require("node:path");
6
+ const commander_1 = require("commander");
6
7
  const ora_1 = tslib_1.__importDefault(require("ora"));
7
- const typeorm_1 = require("typeorm");
8
- const yargs_1 = require("yargs");
9
- const seeder_1 = require("../seeder");
10
- const useSeeders_1 = require("../helpers/useSeeders");
11
- const fileHandling_1 = require("../utils/fileHandling");
8
+ const errors_1 = require("../errors");
9
+ const DataSourceImportationError_1 = require("../errors/DataSourceImportationError");
10
+ const SeederExecutionError_1 = require("../errors/SeederExecutionError");
12
11
  const helpers_1 = require("../helpers");
13
- class SeedCommand {
14
- constructor() {
15
- this.command = 'seed <path>';
16
- this.describe = 'Runs the seeders';
12
+ const utils_1 = require("../utils");
13
+ async function run(path) {
14
+ const opts = seedCommand.opts();
15
+ const spinner = (0, ora_1.default)({ isSilent: process.env.NODE_ENV === 'test' }).start();
16
+ spinner.start('Loading datasource');
17
+ let dataSource;
18
+ try {
19
+ const dataSourcePath = (0, node_path_1.resolve)(process.cwd(), opts.dataSource);
20
+ dataSource = await utils_1.CommandUtils.loadDataSource(dataSourcePath);
21
+ spinner.succeed('Datasource loaded');
17
22
  }
18
- /**
19
- * @inheritdoc
20
- */
21
- builder(args) {
22
- return args
23
- .option('d', {
24
- alias: 'dataSource',
25
- type: 'string',
26
- describe: 'Path to the file where your DataSource instance is defined.',
27
- required: true,
28
- })
29
- .fail((message, error) => {
30
- if (error)
31
- throw error; // preserve stack
32
- else {
33
- console.error(message);
34
- (0, yargs_1.showHelp)();
35
- }
36
- });
23
+ catch (error) {
24
+ spinner.fail('Could not load the data source!');
25
+ throw new DataSourceImportationError_1.DataSourceImportationError('Could not load the data source!', { cause: error });
37
26
  }
38
- /**
39
- * @inheritdoc
40
- */
41
- async handler(args) {
42
- const spinner = (0, ora_1.default)({ isSilent: process.env.NODE_ENV === 'test' }).start();
43
- spinner.start('Loading datasource');
44
- let dataSource;
45
- try {
46
- const dataSourcePath = (0, node_path_1.resolve)(process.cwd(), args.dataSource);
47
- dataSource = await SeedCommand.loadDataSource(dataSourcePath);
48
- spinner.succeed('Datasource loaded');
49
- }
50
- catch (error) {
51
- spinner.fail('Could not load the data source!');
52
- throw error;
53
- }
54
- spinner.start('Importing seeders');
55
- let seeders;
56
- try {
57
- const absolutePath = (0, node_path_1.resolve)(process.cwd(), args.path);
58
- const seederFiles = (0, fileHandling_1.calculateFilePath)(absolutePath);
59
- seeders = await SeedCommand.loadSeeders(seederFiles);
60
- spinner.succeed('Seeder imported');
61
- }
62
- catch (error) {
63
- spinner.fail('Could not load seeders!');
64
- await dataSource.destroy();
65
- throw error;
66
- }
67
- // Run seeder
68
- spinner.start(`Executing seeders`);
69
- try {
70
- await (0, helpers_1.useDataSource)(dataSource);
71
- for (const seeder of seeders) {
72
- await (0, useSeeders_1.useSeeders)(seeder);
73
- spinner.succeed(`Seeder ${seeder.name} executed`);
74
- }
75
- }
76
- catch (error) {
77
- spinner.fail('Could not execute seeder!');
78
- await dataSource.destroy();
79
- throw error;
80
- }
81
- spinner.succeed('Finished seeding');
82
- await dataSource.destroy();
27
+ spinner.start('Importing seeders');
28
+ let seeders;
29
+ try {
30
+ const seederFiles = (0, utils_1.calculateFilePath)(path);
31
+ seeders = await utils_1.CommandUtils.loadSeeders(seederFiles);
32
+ spinner.succeed('Seeder imported');
83
33
  }
84
- static async loadDataSource(dataSourceFilePath) {
85
- let dataSourceFileExports;
86
- try {
87
- dataSourceFileExports = await Promise.resolve().then(() => tslib_1.__importStar(require(dataSourceFilePath)));
88
- }
89
- catch (err) {
90
- throw new Error(`Unable to open file: "${dataSourceFilePath}"`);
91
- }
92
- if (!dataSourceFileExports || typeof dataSourceFileExports !== 'object') {
93
- throw new Error(`Given data source file must contain export of a DataSource instance`);
94
- }
95
- const dataSourceExports = [];
96
- for (const fileExport in dataSourceFileExports) {
97
- const dataSourceExport = dataSourceFileExports[fileExport];
98
- if (dataSourceExport instanceof typeorm_1.DataSource) {
99
- dataSourceExports.push(dataSourceExport);
100
- }
101
- }
102
- if (dataSourceExports.length === 0) {
103
- throw new Error(`Given data source file must contain export of a DataSource instance`);
104
- }
105
- if (dataSourceExports.length > 1) {
106
- throw new Error(`Given data source file must contain only one export of DataSource instance`);
107
- }
108
- const dataSource = dataSourceExports[0];
109
- dataSource.setOptions({
110
- synchronize: false,
111
- migrationsRun: false,
112
- dropSchema: false,
113
- logging: false,
114
- });
115
- await dataSource.initialize();
116
- return dataSource;
34
+ catch (error) {
35
+ spinner.fail('Could not load seeders!');
36
+ throw new errors_1.SeederImportationError('Could not load seeders!', { cause: error });
117
37
  }
118
- static async loadSeeders(seederPaths) {
119
- let seederFileExports;
120
- try {
121
- seederFileExports = await Promise.all(seederPaths.map((seederFile) => Promise.resolve().then(() => tslib_1.__importStar(require(seederFile))))).then((seederExports) => {
122
- return seederExports
123
- .map((seederExport) => seederExport.default)
124
- .filter((seederExport) => Boolean(seederExport));
125
- });
126
- }
127
- catch (err) {
128
- throw new Error(`Unable to open files ${err.message}`);
129
- }
130
- if (seederFileExports.length === 0) {
131
- throw new Error(`No default seeders found`);
38
+ spinner.info(`Executing seeders...`);
39
+ try {
40
+ await (0, helpers_1.useDataSource)(dataSource, true);
41
+ for (const seeder of seeders) {
42
+ spinner.start(`Executing ${seeder.name}`);
43
+ await (0, helpers_1.useSeeders)(seeder);
44
+ spinner.succeed(`Seeder ${seeder.name} executed`);
132
45
  }
133
- const seeders = [];
134
- for (const fileExport in seederFileExports) {
135
- const seederExport = seederFileExports[fileExport];
136
- const instance = new seederExport();
137
- if (instance instanceof seeder_1.Seeder) {
138
- seeders.push(seederExport);
139
- }
140
- }
141
- return seeders;
142
46
  }
47
+ catch (error) {
48
+ spinner.fail('Could not execute seeder!');
49
+ await dataSource.destroy();
50
+ throw new SeederExecutionError_1.SeederExecutionError('Could not execute seeder!', { cause: error });
51
+ }
52
+ spinner.succeed('Finished seeding');
53
+ await dataSource.destroy();
54
+ }
55
+ const seedCommand = new commander_1.Command('seed')
56
+ .description('Run the seeders specified by the path. Glob pattern is allowed.')
57
+ .requiredOption('-d, --dataSource <dataSourcePath>', 'Path to the file where your DataSource instance is defined.', './datasource.ts')
58
+ .argument('<path>', 'Path to the seeders. Glob pattern is allowed.')
59
+ .action(run);
60
+ async function bootstrap(argv) {
61
+ await seedCommand.parseAsync(argv);
143
62
  }
144
- exports.SeedCommand = SeedCommand;
63
+ exports.bootstrap = bootstrap;
145
64
  //# sourceMappingURL=seed.command.js.map