Skip to content

Instantly share code, notes, and snippets.

@sunnyy02
Created May 12, 2022 11:20
Show Gist options
  • Save sunnyy02/c391ed94a22753c220fc71b6bdd25d3e to your computer and use it in GitHub Desktop.
Save sunnyy02/c391ed94a22753c220fc71b6bdd25d3e to your computer and use it in GitHub Desktop.
// Firstly, we setup Database Connection
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'postgres',
entities: [Cat],
synchronize: true, // Sync the entities with the database every time the application runs
}),
CatsModule,
],
})
// Then you can define the data entity
@Entity()
export class Cat {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
breed: string;
}
// We can use repository design pattern which means each entity has its own repository.
// Here, we inject the catRepository into your service
export class CatsService {
constructor(
@InjectRepository(Cat)
private catsRepository: Repository<Cat>,
) {}
// Then you can use the injected repo to perform database operation
this.catsRepository.find();
this.catsRepository.save<Cat>(cat);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment