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
16 type ParseQueryStringFilterResult = {
17 [key: string]: string | number | boolean | (string | number | boolean)[]
21 export class RestService {
23 addRestGetParams (params: HttpParams, pagination?: RestPagination, sort?: SortMeta | string) {
24 let newParams = params
26 if (pagination !== undefined) {
27 newParams = newParams.set('start', pagination.start.toString())
28 .set('count', pagination.count.toString())
31 if (sort !== undefined) {
34 if (typeof sort === 'string') {
37 const sortPrefix = sort.order === 1 ? '' : '-'
38 sortString = sortPrefix + sort.field
41 newParams = newParams.set('sort', sortString)
47 addArrayParams (params: HttpParams, name: string, values: (string | number)[]) {
48 for (const v of values) {
49 params = params.append(name, v)
55 addObjectParams (params: HttpParams, object: { [ name: string ]: any }) {
56 for (const name of Object.keys(object)) {
57 const value = object[name]
58 if (value === undefined || value === null) continue
60 if (Array.isArray(value)) {
61 params = this.addArrayParams(params, name, value)
63 params = params.append(name, value)
70 componentPaginationToRestPagination (componentPagination: ComponentPaginationLight): RestPagination {
71 const start: number = (componentPagination.currentPage - 1) * componentPagination.itemsPerPage
72 const count: number = componentPagination.itemsPerPage
74 return { start, count }
77 parseQueryStringFilter (q: string, prefixes: QueryStringFilterPrefixes): ParseQueryStringFilterResult {
80 // Tokenize the strings using spaces that are not in quotes
81 const tokens = q.match(/(?:[^\s"]+|"[^"]*")+/g)
82 .filter(token => !!token)
85 const prefixeStrings = Object.values(prefixes)
88 // Search is the querystring minus defined filters
89 const searchTokens = tokens.filter(t => {
90 return prefixeStrings.every(prefixString => t.startsWith(prefixString) === false)
93 const additionalFilters: ParseQueryStringFilterResult = {}
95 for (const prefixKey of Object.keys(prefixes)) {
96 const prefixObj = prefixes[prefixKey]
97 const prefix = prefixObj.prefix
99 const matchedTokens = tokens.filter(t => t.startsWith(prefix))
100 .map(t => t.slice(prefix.length)) // Keep the value filter
101 .map(t => t.replace(/^"|"$/g, '')) // Remove ""
103 if (prefixObj.handler) return prefixObj.handler(t)
105 if (prefixObj.isBoolean) {
106 if (t === 'true') return true
107 if (t === 'false') return false
114 .filter(t => t !== null && t !== undefined)
116 if (matchedTokens.length === 0) continue
118 additionalFilters[prefixKey] = prefixObj.multiple === true
124 search: searchTokens.join(' ') || undefined,