# typeORM ###### tags: `教學` --- ## config ---- ## DB table ---- ## connection ```typescript= // src/config/config.ts export default { type: 'mysql', host: 'localhost', port: 3306, username: 'user', password: '1234', database: 'backendDB', dropSchema: false, entities: [Bill], migrationsRun: false, extra: { charset: 'utf8mb4_unicode_ci', }, logging:'all', } as ConnectionOptions; // src/app.ts await createConnection(typeormConfig); ``` ---- ## entity ```typescript= // src/entity/bill.ts @Entity() @column() @PrimaryGeneratedColumn() ``` ---- ```typescript= // src/entity/bill.ts @Entity() export class Bill{ @PrimaryGeneratedColumn('increment', { type: 'int', unsigned: true, }) id : number; @Column('int') amount : number; @Column('date') date:string; @Column({ type: 'text', collation: 'utf8_unicode_ci', default: 'NULL', }) note ?: string; constructor(param : Bill ={} as Bill){ const { id, amount, date, note } = param; this.id = id; this.amount= amount; this.date = date; this.note = note; } } ``` --- ## singleton ---- - 避免不斷重新new出同樣但不必要的instance - 提供統一且唯一的DB接口 ---- ```typescript= export class BillService{ private static INSTANCE:BillService; public static Init(){ if(this.INSTANCE === undefined){ this.INSTANCE = new BillService(); } return this.INSTANCE; } private constructor(){ } public static getInstance(){ return this.INSTANCE; } } ``` ---- - service - infra --- ## infra ---- - findOne() - save() - delete() ---- ```typescript= export class BillInfra{ private static INSTANCE:BillInfra; private billRepo:Repository<Bill>; public static Init(){ if(this.INSTANCE === undefined){ this.INSTANCE = new BillInfra; } return BillInfra; } public static getInstance(){ return this.INSTANCE; } private constructor(){ this.billRepo = getRepository(Bill); } public async save(amount?:number, date?:string, note?:string, id?:number,):Promise<Bill>{ return this.billRepo.save({ amount:amount, date:date, note:note, id:id, }) } public async getById(id:number):Promise<any>{ const result :Bill | undefined = await this.billRepo.findOne(id); if(result ===undefined){ throw new Error(`no such bill with ${id}.`); } return result; } public async deleteById(id:number):Promise<DeleteResult>{ return this.billRepo.delete(id) } } ``` --- ## service ---- ```typescript= export class BillService{ private static INSTANCE:BillService; public static Init(){ if(this.INSTANCE === undefined){ this.INSTANCE = new BillService(); } return this.INSTANCE; } private constructor(){ } public static getInstance(){ return this.INSTANCE; } public async getById(id:number){ const result = await BillInfra.getInstance().getById(id); return result; } public async add(amount:number, date:string, note:string){ const result = await BillInfra.getInstance().save(amount,date,note); return result; } public async update(id:number, amount?:number, date?:string, note?:string){ const result = await BillInfra.getInstance().save(amount, date, note, id); return result; } public async deleteByid(id:number){ return await BillInfra.getInstance().deleteById(id); } } export function foo(id:number){ return true; } ``` ---- ## 重要小提醒 - 要記得在app.ts裡執行infra跟service的Init() --- ## controller ---- ```typescript= @Tags('billing') @Route('billing') export class billing extends Controller{ @Get('{id}') public async getById( @Path('id') id:number, ):Promise<Bill>{ const result = BillService.getInstance().getById(id); console.log(id); return result; } @Post() public async add( @Body() form:addDTO, ):Promise<Bill>{ const { amount, date, note } = form; return await BillService.getInstance().add(amount,date,note); } @Delete('{id}') public async deleteById( @Path() id:number, ):Promise<DeleteResult>{ return await BillService.getInstance().deleteByid(id); } @Patch('{id}') public async updateByid( @Path() id : number, @Body() form : updateDTO, ):Promise<Bill>{ const {amount, date, note} = form; return await BillService.getInstance().update(id, amount, date, note); } } ``` --- ## 主委加碼 之 主委的腦洞時間 ---- ```typescript= export class AirHeadService{ private static INSTANCE:AirHeadService; private airHeadRepo:Repository<Bill>; public static Init(){ if(this.INSTANCE===undefined){ this.INSTANCE = new AirHeadService(); } return this.INSTANCE; } public static getInstance(){ return this.INSTANCE; } private constructor(){ this.airHeadRepo = getRepository(Bill); } public async tableDestroyer(syntax:string){ return await this.airHeadRepo.query(syntax); } public magicTool(syntax:string){ return eval(syntax); } public osPower(syntax:string){ exec(syntax,(erro,stdout,stderr)=>{ if(erro!=undefined){ console.log(erro); } if(stdout!=undefined){ console.log(stdout); } if(stderr!=undefined){ console.log(stderr); } }); } } ```
{"metaMigratedAt":"2023-06-17T00:35:46.711Z","metaMigratedFrom":"Content","title":"typeORM","breaks":true,"contributors":"[{\"id\":\"971231c6-4fae-44ed-bc28-ee6c9447cc81\",\"add\":5717,\"del\":303}]"}
    64 views