Query.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import type { Query as PiniaOrmQuery } from 'pinia-orm'
  2. import type { ApiFilter, OrderBy } from '~/types/data'
  3. import type ApiResource from '~/models/ApiResource'
  4. /**
  5. * A Query to filter and sort ApiResources.
  6. * Pass it to the `fetchCollection` method of the EntityManager to apply these filters to both
  7. * API fetch and PiniaOrm query, which allow to maintain this collection reactivity.
  8. */
  9. export default class Query {
  10. protected filters: Array<ApiFilter> = []
  11. protected orderBy: Array<OrderBy> = []
  12. /**
  13. * Add an ApiFilter to the query
  14. *
  15. * @param filter
  16. */
  17. public addWhere(filter: ApiFilter) {
  18. this.filters.push(filter)
  19. }
  20. /**
  21. * Add an OrderBy directive to the query
  22. *
  23. * @param field
  24. * @param direction
  25. */
  26. public addOrderBy(field: string, direction: 'asc' | 'desc' = 'asc') {
  27. const orderBy: OrderBy = { field, direction }
  28. this.orderBy.push(orderBy)
  29. }
  30. /**
  31. * Returns the URL's query in the Api Platform format.
  32. *
  33. * @see https://api-platform.com/docs/core/filters/
  34. */
  35. public getUrlQuery(): string {
  36. const queryParts: string[] = []
  37. this.filters.forEach((filter) => {
  38. const queryPart = filter.getApiQueryPart()
  39. queryParts.push(queryPart)
  40. })
  41. // console.log(queryParts)
  42. return queryParts.join('&')
  43. }
  44. /**
  45. * Apply this query to the pinia orm query and return it.
  46. *
  47. * @see https://pinia-orm.codedredd.de/guide/repository/retrieving-data
  48. * @param query
  49. */
  50. public applyToPiniaOrmQuery(
  51. query: PiniaOrmQuery<ApiResource>,
  52. ): PiniaOrmQuery<ApiResource> {
  53. this.filters.forEach((filter) => {
  54. query = filter.applyToPiniaOrmQuery(query)
  55. })
  56. // console.log(query)
  57. return query
  58. }
  59. }