新增一个编辑内容接口
- 在api目录下test.js 新增 put 方法
//编辑内容需要一个对应的id ,type
ContentApi.put('/:id',async (ctx)=>{
//调用校验层
const v = await new EditContentValidator().validate(ctx);
//调用服务层
const id = v.get('path.id');
const parma = v.get('body');
await contentService.editcontent(id, parma);
// 返回成功信息
ctx.success({
message:'编辑信息成功'
})
})
2.新增一个校验器
// 编辑 继承了新增时的校验类
class EditContentValidator extends ContentValidator {
constructor () {
super();
this.id = new Rule('isNotEmpty', 'id不能为空');
}
}
- 新增dao层
//修改数据时先验证 数据是否存在
// 编辑数据
static async editcontent (v, params) {
// 先验证一下数据
const movie = await MovieModel.findByPk(v); //返回的movie 模型
if (!movie) {
// 不存在该数据
throw new NotFound({ message: '无对应数据' });
}
await movie.update(params);
}
- 服务层调用
// 编辑数据方法
static async editcontent (id, params) {
// 判断 他的type 是否又被修改呢了
switch (params['type']) {
case 100:
MusicDao.editcontent(id, params);
break;
case 200:
delete params['url'];
MovieDao.editcontent(id, params);
break;
case 300:
delete params['url'];
SentenceDao.editcontent(id, params);
break;
default:
throw new NotFound({ message: '对应类型没有找到' });
}
}
新增删除接口
- 在api目录下test.js 新增 del 方法
// 删除期刊数据 (传指定ID 和对应的type)
ContentApi.delete('/:id', async ctx => {
const v = await new DelteContentValidator().validate(ctx);
const id = v.get('path.id');
const type = parseInt(v.get('query.type'));
await contentService.delcontent(id, type);
ctx.success({
message: '删除期刊数据成功'
});
});
- 添加校验器
// 删除 继承lin的验证器
class DelteContentValidator extends LinValidator {
constructor () {
super();
this.id = new Rule('isNotEmpty', 'iD不能为空');
this.type = new Rule('isNotEmpty', '类型不能为空');
}
}
3.添加dao层
// 删除数据 、接收对应的ID
static async delcontent (id) {
await MovieModel.destroy({ where: { id: id } });
}
4.服务层调用
// 删除数据 、、根据type 类型调用不同的dao层
static async delcontent (id, type) {
switch (type) {
case 100:
await MusicDao.delcontent(id);
break;
case 200:
await MovieDao.delcontent(id);
break;
case 300:
await SentenceDao.delcontent(id);
break;
default:
throw new NotFound({ message: '类型没有找到' });
}
}
现在尝试调用一下接口吧!
3.接口添加权限管理
import { logger } from '../../middleware/logger';
import { adminRequired } from '../../middleware/jwt';
将post,get方法 替换成 lin提供的方法即可
post -----> linPost
del -----> linDel
get -----> linGet
put -----> linPut
在红图下面配置 api 所属模块
const contentApi =new LinRouter({
prefix: '/v1/content',
moudle:'内容管理' //也可以在对应的方法中指定所属模块
})
//example :
contentApi.linPost(
'addcontent', //唯一标识
'/' , //url路径
contentApi.permission('添加期刊内容',true), // 名称 ,第二个参数:是否挂载 ,默认true
loginRequired // 权限等级 (login ,group ,admin)在middleware/jwt 中引入
logger('{user.username}新增了数据') //启用行为日志 {} 里面是变量 user模型 在中间件中引入logger
//也可以第二种写法
{
permission:'添加期刊内容',
moudle: '模块',
mount:true
}
ctx=>{
ctx.json('返回消息')
}
)