Created
May 12, 2022 11:20
-
-
Save sunnyy02/c391ed94a22753c220fc71b6bdd25d3e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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