import type { Query as PiniaOrmQuery } from 'pinia-orm' import type { ApiFilter, OrderBy } from '~/types/data' import type ApiResource from '~/models/ApiResource' /** * A Query to filter and sort ApiResources. * Pass it to the `fetchCollection` method of the EntityManager to apply these filters to both * API fetch and PiniaOrm query, which allow to maintain this collection reactivity. */ export default class Query { protected filters: Array = [] protected orderBy: Array = [] /** * Add an ApiFilter to the query * * @param filter */ public addWhere(filter: ApiFilter) { this.filters.push(filter) } /** * Add an OrderBy directive to the query * * @param field * @param direction */ public addOrderBy(field: string, direction: 'asc' | 'desc' = 'asc') { const orderBy: OrderBy = { field, direction } this.orderBy.push(orderBy) } /** * Returns the URL's query in the Api Platform format. * * @see https://api-platform.com/docs/core/filters/ */ public getUrlQuery(): string { const queryParts: string[] = [] this.filters.forEach((filter) => { const queryPart = filter.getApiQueryPart() queryParts.push(queryPart) }) // console.log(queryParts) return queryParts.join('&') } /** * Apply this query to the pinia orm query and return it. * * @see https://pinia-orm.codedredd.de/guide/repository/retrieving-data * @param query */ public applyToPiniaOrmQuery( query: PiniaOrmQuery, ): PiniaOrmQuery { this.filters.forEach((filter) => { query = filter.applyToPiniaOrmQuery(query) }) // console.log(query) return query } }