1
1
/* eslint-disable no-await-in-loop */
2
2
// This script scans `examples` folder for `data/seed.js` files and run them for seeding DB.
3
3
4
- import { MongoClient } from 'mongodb' ;
4
+ import { MongoClient , Db } from 'mongodb' ;
5
5
import fs from 'fs' ;
6
6
import { getExampleNames , resolveExamplePath , MONGODB_URI } from '../config' ;
7
7
@@ -11,26 +11,22 @@ function getDBName(uri: string) {
11
11
return 'graphql-compose-mongoose' ;
12
12
}
13
13
14
- let con ;
15
- let db ;
16
-
17
- async function mongoConnect ( ) {
14
+ export async function mongoConnect ( ) : Promise < Db & { con ?: MongoClient } > {
15
+ let db : Db & { con ?: MongoClient } ;
18
16
if ( ! db ) {
19
- con = await MongoClient . connect ( MONGODB_URI , {
17
+ const con = await MongoClient . connect ( MONGODB_URI , {
20
18
useNewUrlParser : true ,
21
19
useUnifiedTopology : true ,
22
20
} ) ;
23
21
db = con . db ( getDBName ( MONGODB_URI ) ) ;
22
+ db . con = con ;
24
23
}
25
24
return db ;
26
25
}
27
26
28
- async function mongoDisconnect ( ) {
29
- if ( con ) {
30
- const oldCon = con ;
31
- con = undefined ;
32
- db = undefined ;
33
- await oldCon . close ( ) ;
27
+ export async function mongoDisconnect ( db : Db & { con ?: MongoClient } ) {
28
+ if ( db ?. con ) {
29
+ await db ?. con . close ( ) ;
34
30
}
35
31
}
36
32
@@ -56,9 +52,9 @@ export async function seedByName(name: string) {
56
52
57
53
// eslint-disable-next-line @typescript-eslint/no-var-requires
58
54
const seedFn = require ( seedFile ) . default ;
59
- await mongoConnect ( ) ;
55
+ const db = await mongoConnect ( ) ;
60
56
await seedFn ( db ) ;
61
- await mongoDisconnect ( ) ;
57
+ await mongoDisconnect ( db ) ;
62
58
} catch ( e ) {
63
59
if ( e . code === 'MODULE_NOT_FOUND' || e . code === 'ENOENT' ) {
64
60
console . log ( ` file '${ seedFile } ' not found. Skipping...` ) ;
0 commit comments