Skip to content

Instantly share code, notes, and snippets.

@sunnyy02
Created May 14, 2022 06:27
Show Gist options
  • Save sunnyy02/7b7ca6d04de7643c75d6125c18ca0168 to your computer and use it in GitHub Desktop.
Save sunnyy02/7b7ca6d04de7643c75d6125c18ca0168 to your computer and use it in GitHub Desktop.
//Firstly, we create a Sequelize instance with an options object
export const databaseProviders = [
{
provide: 'SEQUELIZE',
useFactory: async () => {
const sequelize = new Sequelize({
dialect: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'postgres',
});
sequelize.addModels([Cat]); // Add all models
await sequelize.sync(); // Sync database tables
return sequelize;
},
},
];
// Then, export the provider to make it accessible
@Module({
providers: [...databaseProviders],
exports: [...databaseProviders],
})
export class DatabaseModule {}
// Define model entity, each represent a table in the database
@Table
export class Cat extends Model {
@Column
name: string;
@Column
age: number;
@Column
breed: string;
}
// Create a repository provider
export const catsProviders = [
{
provide: 'CATS_REPOSITORY',
useValue: Cat,
},
];
// In service, we inject the repository
export const catsProviders = [
{
provide: 'CATS_REPOSITORY',
useValue: Cat,
},
];
// Then, we can perform database operations
this.catsRepository.findAll<Cat>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment