You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.5 KiB

2 years ago
2 years ago
  1. import ApiService from '@/services/api.service'
  2. import { LabelRepository } from '@/domain/models/label/labelRepository'
  3. import { LabelItem } from '@/domain/models/label/label'
  4. function toModel(item: { [key: string]: any }): LabelItem {
  5. return new LabelItem(
  6. item.id,
  7. item.text,
  8. item.prefix_key,
  9. item.suffix_key,
  10. item.background_color,
  11. item.text_color
  12. )
  13. }
  14. function toPayload(item: LabelItem): { [key: string]: any } {
  15. return {
  16. id: item.id,
  17. text: item.text,
  18. prefix_key: item.prefixKey,
  19. suffix_key: item.suffixKey,
  20. background_color: item.backgroundColor,
  21. text_color: item.textColor
  22. }
  23. }
  24. export class APILabelRepository implements LabelRepository {
  25. constructor(private readonly baseUrl = 'label', private readonly request = ApiService) {}
  26. async list(projectId: string): Promise<LabelItem[]> {
  27. const url = `/projects/${projectId}/${this.baseUrl}s`
  28. const response = await this.request.get(url)
  29. return response.data.map((item: { [key: string]: any }) => toModel(item))
  30. }
  31. async findById(projectId: string, labelId: number): Promise<LabelItem> {
  32. const url = `/projects/${projectId}/${this.baseUrl}s/${labelId}`
  33. const response = await this.request.get(url)
  34. return toModel(response.data)
  35. }
  36. async create(projectId: string, item: LabelItem): Promise<LabelItem> {
  37. const url = `/projects/${projectId}/${this.baseUrl}s`
  38. const payload = toPayload(item)
  39. const response = await this.request.post(url, payload)
  40. return toModel(response.data)
  41. }
  42. async update(projectId: string, item: LabelItem): Promise<LabelItem> {
  43. const url = `/projects/${projectId}/${this.baseUrl}s/${item.id}`
  44. const payload = toPayload(item)
  45. const response = await this.request.patch(url, payload)
  46. return toModel(response.data)
  47. }
  48. async bulkDelete(projectId: string, labelIds: number[]): Promise<void> {
  49. const url = `/projects/${projectId}/${this.baseUrl}s`
  50. await this.request.delete(url, { ids: labelIds })
  51. }
  52. async uploadFile(projectId: string, payload: FormData): Promise<void> {
  53. const url = `/projects/${projectId}/${this.baseUrl}-upload`
  54. const config = {
  55. headers: {
  56. 'Content-Type': 'multipart/form-data'
  57. }
  58. }
  59. try {
  60. await this.request.post(url, payload, config)
  61. } catch (e: any) {
  62. const data = e.response.data
  63. if ('detail' in data) {
  64. throw new Error(data.detail)
  65. } else {
  66. throw new Error('Text field is required')
  67. }
  68. }
  69. }
  70. }