1 import { SortMeta } from 'primeng/api'
2 import { HttpParams } from '@angular/common/http'
3 import { Injectable } from '@angular/core'
4 import { ComponentPaginationLight } from './component-pagination.model'
5 import { RestPagination } from './rest-pagination'
7 interface QueryStringFilterPrefixes {
10 handler?: (v: string) => string | number
15 type ParseQueryStringFilterResult = {
16 [key: string]: string | number | (string | number)[]
20 export class RestService {
22 addRestGetParams (params: HttpParams, pagination?: RestPagination, sort?: SortMeta | string) {
23 let newParams = params
25 if (pagination !== undefined) {
26 newParams = newParams.set('start', pagination.start.toString())
27 .set('count', pagination.count.toString())
30 if (sort !== undefined) {
33 if (typeof sort === 'string') {
36 const sortPrefix = sort.order === 1 ? '' : '-'
37 sortString = sortPrefix + sort.field
40 newParams = newParams.set('sort', sortString)
46 addObjectParams (params: HttpParams, object: { [ name: string ]: any }) {
47 for (const name of Object.keys(object)) {
48 const value = object[name]
51 if (Array.isArray(value) && value.length !== 0) {
52 for (const v of value) params = params.append(name, v)
54 params = params.append(name, value)
61 componentPaginationToRestPagination (componentPagination: ComponentPaginationLight): RestPagination {
62 const start: number = (componentPagination.currentPage - 1) * componentPagination.itemsPerPage
63 const count: number = componentPagination.itemsPerPage
65 return { start, count }
68 parseQueryStringFilter (q: string, prefixes: QueryStringFilterPrefixes): ParseQueryStringFilterResult {
71 // Tokenize the strings using spaces
72 const tokens = q.split(' ').filter(token => !!token)
75 const prefixeStrings = Object.values(prefixes)
78 // Search is the querystring minus defined filters
79 const searchTokens = tokens.filter(t => {
80 return prefixeStrings.every(prefixString => t.startsWith(prefixString) === false)
83 const additionalFilters: ParseQueryStringFilterResult = {}
85 for (const prefixKey of Object.keys(prefixes)) {
86 const prefixObj = prefixes[prefixKey]
87 const prefix = prefixObj.prefix
89 const matchedTokens = tokens.filter(t => t.startsWith(prefix))
90 .map(t => t.slice(prefix.length)) // Keep the value filter
92 if (prefixObj.handler) return prefixObj.handler(t)
98 if (matchedTokens.length === 0) continue
100 additionalFilters[prefixKey] = prefixObj.multiple === true
106 search: searchTokens.join(' '),