RestFulMapper
RestFulMapper 是对 Restful 接口的简化类,提供了常用的增删改查方法。
- 基础了基类 BaseMapper
- 提供方法:findById、findAll、save、update、delete
- 需要传入的参数:
- T 实体类型
- ID 索引类型 默认 number
- R 返回值类型(除联合查询外,一般与实体类型一致) 默认 any
/**
* RestFulMapper RestFul风格的Mapper基类
* @param T 实体类型
* @param [ID] {number} 索引类型
* @param [R] {any} 返回值类型(除联结类型外,一般与实体类型一致)
*/
export class RestFulMapper<T, ID = number, R = any> extends BaseMapper {
/**
* 根据索引获取
* @param id 索引
*/
@GetMapping('/{id}')
findById(id: ID): Promise<ThatAxiosResponse<R>> {
return Promise.resolve({} as ThatAxiosResponse<R>);
}
/**
* 根据条件获取列表
* @param entity 条件实体
*/
@GetMapping('/list')
findAll(entity: Partial<T> = {} as Partial<T>): Promise<ThatAxiosResponse<R[]>> {
return Promise.resolve({} as ThatAxiosResponse<R[]>);
}
/**
* 保存
* @param entity 创建实体
*/
@PostMapping('')
save(entity: T): Promise<ThatAxiosResponse<R>> {
return Promise.resolve({} as ThatAxiosResponse<R>);
}
/**
* 更新
* @param entity 更新实体
*/
@PutMapping('')
update(entity: T): Promise<ThatAxiosResponse<R>> {
return Promise.resolve({} as ThatAxiosResponse<R>);
}
/**
* 删除
* @param id 索引
*/
@DeleteMapping('/{id}')
delete(id: ID): Promise<ThatAxiosResponse<R>> {
return Promise.resolve({} as ThatAxiosResponse<R>);
}
}
使用
定义接口
RESTFul API 的特别支持,继承RestFulMapper即可得到自动生成如下方法: findById, findAll, save, update, delete, findByXxx
import Shop from "@/types/ShopCard";
import { RequestMapping, RestFulMapper } from "@thatcompany/axios";
@RequestMapping('/proxy/service/know/shop')
export class ShopMapper extends RestFulMapper<Shop, number> {}
export default new ShopMapper();
使用接口
import shopMapper from "@/api/mapper/ShopMapper";
async function test() {
const firstShop = await shopMapper.findById(1);
firstShop.name = 'axios';
await shopMapper.update(firstShop);
const priceIsHundredShopsA = await shopMapper.findAll({ price: 100 });
priceIsHundredShopsA.forEach(async (shop) => {
await shopMapper.delete(shop.id);
});
}