BaseModel.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import http from './Axios';
  2. import { Method } from 'axios';
  3. type findParamsType = {
  4. method?: Method;
  5. path: string;
  6. params: { [x: string]: any };
  7. };
  8. type updateParamsType = {
  9. path: string;
  10. data?: any;
  11. };
  12. export default class BaseModel {
  13. constructor(props: any) {
  14. return this;
  15. }
  16. static async findAll(data: findParamsType) {
  17. const { params = {}, path = '', method = 'get' } = data;
  18. const type = method === 'post' ? 'data' : 'params';
  19. const httpConfig = {
  20. method,
  21. url: path,
  22. [type]: { ...params },
  23. };
  24. const res = await http(httpConfig);
  25. let list = res.data.data || [];
  26. if (!Array.isArray(list)) {
  27. return list;
  28. }
  29. return Object.assign(
  30. list.map(v => new this(v)),
  31. {
  32. _total: res.data.data.total_count || list.length,
  33. }
  34. );
  35. }
  36. static async search(data: findParamsType) {
  37. const { method = 'get', params = {}, path = '' } = data;
  38. const res = await http({
  39. method,
  40. url: path,
  41. params,
  42. });
  43. return res.data.data;
  44. }
  45. /**
  46. * Create instance in database
  47. */
  48. static async create(options: updateParamsType) {
  49. const { path, data } = options;
  50. const res = await http.post(path, data);
  51. return new this(res.data.data || {});
  52. }
  53. static async update(options: updateParamsType) {
  54. const { path, data } = options;
  55. const res = await http.put(path, data);
  56. return new this(res.data.data || {});
  57. }
  58. static async delete(options: updateParamsType) {
  59. const { path } = options;
  60. const res = await http.delete(path);
  61. return res.data;
  62. }
  63. static async batchDelete(options: updateParamsType) {
  64. const { path, data } = options;
  65. const res = await http.post(path, data);
  66. return res.data;
  67. }
  68. static async query(options: updateParamsType) {
  69. const { path, data } = options;
  70. const res = await http.post(path, data);
  71. return res.data.data;
  72. }
  73. }