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.

77 lines
2.5 KiB

2 years ago
2 years ago
2 years ago
  1. import { CommentItem } from '@/domain/models/comment/comment'
  2. import { Page } from '@/domain/models/page'
  3. import ApiService from '@/services/api.service'
  4. export type SearchOption = { [key: string]: string | (string | null)[] }
  5. function toModel(item: { [key: string]: any }): CommentItem {
  6. return new CommentItem(
  7. item.id,
  8. item.user,
  9. item.username,
  10. item.example,
  11. item.text,
  12. item.created_at
  13. )
  14. }
  15. function toPayload(item: CommentItem): { [key: string]: any } {
  16. return {
  17. id: item.id,
  18. user: item.user,
  19. text: item.text
  20. }
  21. }
  22. export class APICommentRepository {
  23. constructor(private readonly request = ApiService) {}
  24. async listAll(
  25. projectId: string,
  26. { limit = '10', offset = '0', q = '', sortBy = '', sortDesc = '' }: SearchOption
  27. ): Promise<Page<CommentItem>> {
  28. const ordering = sortDesc === 'true' ? `-${sortBy}` : `${sortBy}`
  29. const url = `/projects/${projectId}/comments?q=${q}&limit=${limit}&offset=${offset}&ordering=${ordering}`
  30. const response = await this.request.get(url)
  31. return new Page(
  32. response.data.count,
  33. response.data.next,
  34. response.data.previous,
  35. response.data.results.map((item: { [key: string]: any }) => toModel(item))
  36. )
  37. }
  38. async list(projectId: string, exampleId: number): Promise<CommentItem[]> {
  39. const url = `/projects/${projectId}/comments?example=${exampleId}&limit=100`
  40. const response = await this.request.get(url)
  41. return response.data.results.map((item: { [key: string]: any }) => toModel(item))
  42. }
  43. async create(projectId: string, exampleId: number, text: string): Promise<CommentItem> {
  44. const url = `/projects/${projectId}/comments?example=${exampleId}`
  45. const response = await this.request.post(url, {
  46. projectId,
  47. exampleId,
  48. text
  49. })
  50. return toModel(response.data)
  51. }
  52. async update(projectId: string, comment: CommentItem): Promise<CommentItem> {
  53. const url = `/projects/${projectId}/comments/${comment.id}`
  54. const payload = toPayload(comment)
  55. const response = await this.request.put(url, payload)
  56. return toModel(response.data)
  57. }
  58. async delete(projectId: string, comment: CommentItem): Promise<void> {
  59. const url = `/projects/${projectId}/comments/${comment.id}`
  60. await this.request.delete(url)
  61. }
  62. async deleteBulk(projectId: string, comments: CommentItem[]): Promise<void> {
  63. const url = `/projects/${projectId}/comments`
  64. const ids = comments.map((comment) => comment.id)
  65. await this.request.delete(url, { ids })
  66. }
  67. }