Created
August 14, 2019 14:50
-
-
Save prateekkathal/afc22d9cfbf64751d66222a23157684f to your computer and use it in GitHub Desktop.
Seeding Databases Using NestJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const languages: ILanguage[] = [ | |
{ name: 'English' }, | |
{ name: 'French' }, | |
{ name: 'Spanish' }, | |
{ name: 'Russian' }, | |
// ... and others ... | |
]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Entity Schema for Languages. | |
* | |
* @class | |
*/ | |
@Entity({ | |
name: 'languages', | |
}) | |
export class Language implements ILanguage { | |
@PrimaryGeneratedColumn() | |
id: number; | |
@Column() | |
name: string; | |
@Column({ | |
type: 'timestamp', | |
default: () => 'CURRENT_TIMESTAMP', | |
}) | |
createdAt: string; | |
@Column({ | |
type: 'timestamp', | |
default: () => 'CURRENT_TIMESTAMP', | |
}) | |
updatedAt: string; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Language variable type declaration. | |
* | |
* @interface | |
*/ | |
export interface ILanguage { | |
name: string; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Import and provide seeder classes for languages. | |
* | |
* @module | |
*/ | |
@Module({ | |
imports: [TypeOrmModule.forFeature([Language])], | |
providers: [LanguageSeederService], | |
exports: [LanguageSeederService], | |
}) | |
export class LanguageSeederModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Service dealing with language based operations. | |
* | |
* @class | |
*/ | |
@Injectable() | |
export class LanguageSeederService { | |
/** | |
* Create an instance of class. | |
* | |
* @constructs | |
* | |
* @param {Repository<Language>} languageRepository | |
*/ | |
constructor( | |
@InjectRepository(Language) | |
private readonly languageRepository: Repository<Language>, | |
) {} | |
/** | |
* Seed all languages. | |
* | |
* @function | |
*/ | |
create(): Array<Promise<Language>> { | |
return languages.map(async (language: ILanguage) => { | |
return await this.languageRepository | |
.findOne({ name: language.name }) | |
.exec() | |
.then(async dbLangauge => { | |
// We check if a language already exists. | |
// If it does don't create a new one. | |
if (dbLangauge) { | |
return Promise.resolve(null); | |
} | |
return Promise.resolve( | |
await this.languageRepository.create(language), | |
); | |
}) | |
.catch(error => Promise.reject(error)); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Import and provide base typeorm (mysql) related classes. | |
* | |
* @module | |
*/ | |
@Module({ | |
imports: [ | |
TypeOrmModule.forRootAsync({ | |
imports: [MysqlConfigModule], | |
useFactory: async (mysqlConfigService: MysqlConfigService) => ({ | |
type: 'mysql' as DatabaseType, | |
host: mysqlConfigService.host, | |
port: mysqlConfigService.port, | |
username: mysqlConfigService.username, | |
password: mysqlConfigService.password, | |
database: mysqlConfigService.database, | |
entities: [Language], | |
synchronize: true, | |
}), | |
inject: [MysqlConfigService], | |
} as TypeOrmModuleAsyncOptions), | |
], | |
}) | |
export class MysqlDatabaseProviderModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function bootstrap() { | |
NestFactory.createApplicationContext(SeederModule) | |
.then(appContext => { | |
const logger = appContext.get(Logger); | |
const seeder = appContext.get(Seeder); | |
seeder | |
.seed() | |
.then(() => { | |
logger.debug('Seeding complete!'); | |
}) | |
.catch(error => { | |
logger.error('Seeding failed!'); | |
throw error; | |
}) | |
.finally(() => appContext.close()); | |
}) | |
.catch(error => { | |
throw error; | |
}); | |
} | |
bootstrap(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Import and provide seeder classes. | |
* | |
* @module | |
*/ | |
@Module({ | |
imports: [MysqlDatabaseProviderModule, LanguageSeederModule], | |
providers: [MysqlSeederService, Logger, Seeder], | |
}) | |
export class SeederModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Injectable() | |
export class Seeder { | |
constructor( | |
private readonly logger: Logger, | |
private readonly languageSeederService: LanguageSeederService, | |
) {} | |
async seed() { | |
await this.languages() | |
.then(completed => { | |
this.logger.debug('Successfuly completed seeding users...'); | |
Promise.resolve(completed); | |
}) | |
.catch(error => { | |
this.logger.error('Failed seeding users...'); | |
Promise.reject(error); | |
}); | |
} | |
async languages() { | |
return await Promise.all(this.languageSeederService.create()) | |
.then(createdLanguages => { | |
// Can also use this.logger.verbose('...'); | |
this.logger.debug( | |
'No. of languages created : ' + | |
// Remove all null values and return only created languages. | |
createdLanguages.filter( | |
nullValueOrCreatedLanguage => nullValueOrCreatedLanguage, | |
).length, | |
); | |
return Promise.resolve(true); | |
}) | |
.catch(error => Promise.reject(error)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment