操作数据库
在 src 下创建 serve 文件夹,创建一个ts文件用于操作刚才创建的数据,例子内容如下(下一章介绍操作数据库常用的方法):
import { Provide } from '@midwayjs/decorator'; import { Schema } from '../entity/schema'; import { InjectEntityModel } from '@midwayjs/orm'; import { Repository } from 'typeorm'; @Provide() export class SchemaServe { @InjectEntityModel(Schema) schemaModel: Repository<Schema>; // 获取一条 async getOne() { const firstSchame = await this.schemaModel.findOne({ where: { id: 1 }, }); return firstSchame; } // 保存 async save(schemaObj) { // create a entity object const schema = new Schema(); schema.content = schemaObj.content; schema.creater = schemaObj.creater; schema.creatAt = schemaObj.creatAt; schema.address = schemaObj.address; // save entity const schemaResult = await this.schemaModel.save(schema); return schemaResult; } }
使用自定义操作数据库的方法
在 src/function 下引入刚才在serve中的文件,例子如下:
import { Provide, Inject, Get, Post, Controller, Body, } from '@midwayjs/decorator'; import { Validate } from '@midwayjs/validate'; import { Context } from '@midwayjs/faas'; import { SchemaServe } from '../serve/schema'; import { SchamaDTO } from '../dto/schema'; import { getStandardResponse } from '../util/common'; @Provide() @Controller('/api/schema/') export class SchemaCtrol { @Inject() ctx: Context; @Inject() SchemaServe: SchemaServe; @Get('/getSchema') async getSchema() { try { const result = await this.SchemaServe.getOne(); return getStandardResponse(true, result); } catch (error) { return getStandardResponse(false, null, error.toString()); } } @Post('/save') @Validate() async saveSchema(@Body() bodyObj: SchamaDTO) { try { const result = await this.SchemaServe.save(bodyObj); return getStandardResponse(true, result); } catch (error) { return getStandardResponse(false, null, error.toString()); } } }