11/* eslint-disable no-await-in-loop */
22// This script scans `examples` folder for `data/seed.js` files and run them for seeding DB.
33
4- import { MongoClient } from 'mongodb' ;
4+ import { MongoClient , Db } from 'mongodb' ;
55import fs from 'fs' ;
66import { getExampleNames , resolveExamplePath , MONGODB_URI } from '../config' ;
77
@@ -11,26 +11,22 @@ function getDBName(uri: string) {
1111 return 'graphql-compose-mongoose' ;
1212}
1313
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 } ;
1816 if ( ! db ) {
19- con = await MongoClient . connect ( MONGODB_URI , {
17+ const con = await MongoClient . connect ( MONGODB_URI , {
2018 useNewUrlParser : true ,
2119 useUnifiedTopology : true ,
2220 } ) ;
2321 db = con . db ( getDBName ( MONGODB_URI ) ) ;
22+ db . con = con ;
2423 }
2524 return db ;
2625}
2726
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 ( ) ;
3430 }
3531}
3632
@@ -56,9 +52,9 @@ export async function seedByName(name: string) {
5652
5753 // eslint-disable-next-line @typescript-eslint/no-var-requires
5854 const seedFn = require ( seedFile ) . default ;
59- await mongoConnect ( ) ;
55+ const db = await mongoConnect ( ) ;
6056 await seedFn ( db ) ;
61- await mongoDisconnect ( ) ;
57+ await mongoDisconnect ( db ) ;
6258 } catch ( e ) {
6359 if ( e . code === 'MODULE_NOT_FOUND' || e . code === 'ENOENT' ) {
6460 console . log ( ` file '${ seedFile } ' not found. Skipping...` ) ;
0 commit comments