Query.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import type { Query as PiniaOrmQuery } from 'pinia-orm'
  2. import type { ApiFilter } 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. /**
  12. * Add an ApiFilter to the query
  13. *
  14. * @param filter
  15. */
  16. public add(filter: ApiFilter): this {
  17. this.filters.push(filter)
  18. return this
  19. }
  20. /**
  21. * Returns the URL's query in the Api Platform format.
  22. *
  23. * @see https://api-platform.com/docs/core/filters/
  24. */
  25. public getUrlQuery(): string {
  26. const queryParts: string[] = ['page=1']
  27. this.filters.forEach((filter) => {
  28. const queryPart = filter.getApiQueryPart()
  29. queryParts.push(queryPart)
  30. })
  31. // console.log(queryParts)
  32. return queryParts.join('&')
  33. }
  34. /**
  35. * Apply this query to the pinia orm query and return it.
  36. *
  37. * @see https://pinia-orm.codedredd.de/guide/repository/retrieving-data
  38. * @param query
  39. */
  40. public applyToPiniaOrmQuery(
  41. query: PiniaOrmQuery<ApiResource>,
  42. ): PiniaOrmQuery<ApiResource> {
  43. this.filters.forEach((filter) => {
  44. query = filter.applyToPiniaOrmQuery(query)
  45. })
  46. // console.log(query)
  47. return query
  48. }
  49. }