curd.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import http from '@/lib/http'
  2. export interface ModelBase {
  3. id: number
  4. created_at: string
  5. updated_at: string
  6. }
  7. export interface Pagination {
  8. total: number
  9. per_page: number
  10. current_page: number
  11. total_pages: number
  12. }
  13. export interface IGetListResponse<T> {
  14. data: T[]
  15. pagination: Pagination
  16. }
  17. class Curd<T> {
  18. protected readonly baseUrl: string
  19. protected readonly plural: string
  20. get_list = this._get_list.bind(this)
  21. get = this._get.bind(this)
  22. save = this._save.bind(this)
  23. destroy = this._destroy.bind(this)
  24. recover = this._recover.bind(this)
  25. update_order = this._update_order.bind(this)
  26. constructor(baseUrl: string, plural: string | null = null) {
  27. this.baseUrl = baseUrl
  28. this.plural = plural ?? `${this.baseUrl}s`
  29. }
  30. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  31. _get_list(params: any = null): Promise<IGetListResponse<T>> {
  32. return http.get(this.plural, { params })
  33. }
  34. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  35. _get(id: any = null, params: any = {}): Promise<T> {
  36. return http.get(this.baseUrl + (id ? `/${id}` : ''), { params })
  37. }
  38. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  39. _save(id: any = null, data: any, config: any = undefined): Promise<T> {
  40. return http.post(this.baseUrl + (id ? `/${id}` : ''), data, config)
  41. }
  42. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  43. _destroy(id: any = null) {
  44. return http.delete(`${this.baseUrl}/${id}`)
  45. }
  46. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  47. _recover(id: any = null) {
  48. return http.patch(`${this.baseUrl}/${id}`)
  49. }
  50. _update_order(data: {
  51. target_id: number
  52. direction: number
  53. affected_ids: number[]
  54. }) {
  55. return http.post(`${this.plural}/order`, data)
  56. }
  57. }
  58. export default Curd