Query.ts 1.5 KB

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