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 addObjectParams (params: HttpParams, object: { [ name: string ]: any }) {
48 for (const name of Object.keys(object)) {
49 const value = object[name]
50 if (value === undefined || value === null) continue
52 if (Array.isArray(value)) {
53 for (const v of value) params = params.append(name, v)
55 params = params.append(name, value)
62 componentPaginationToRestPagination (componentPagination: ComponentPaginationLight): RestPagination {
63 const start: number = (componentPagination.currentPage - 1) * componentPagination.itemsPerPage
64 const count: number = componentPagination.itemsPerPage
66 return { start, count }
69 parseQueryStringFilter (q: string, prefixes: QueryStringFilterPrefixes): ParseQueryStringFilterResult {
72 // Tokenize the strings using spaces that are not in quotes
73 const tokens = q.match(/(?:[^\s"]+|"[^"]*")+/g)
74 .filter(token => !!token)
77 const prefixeStrings = Object.values(prefixes)
80 // Search is the querystring minus defined filters
81 const searchTokens = tokens.filter(t => {
82 return prefixeStrings.every(prefixString => t.startsWith(prefixString) === false)
85 const additionalFilters: ParseQueryStringFilterResult = {}
87 for (const prefixKey of Object.keys(prefixes)) {
88 const prefixObj = prefixes[prefixKey]
89 const prefix = prefixObj.prefix
91 const matchedTokens = tokens.filter(t => t.startsWith(prefix))
92 .map(t => t.slice(prefix.length)) // Keep the value filter
93 .map(t => t.replace(/^"|"$/g, '')) // Remove ""
95 if (prefixObj.handler) return prefixObj.handler(t)
97 if (prefixObj.isBoolean) {
98 if (t === 'true') return true
99 if (t === 'false') return false
106 .filter(t => t !== null && t !== undefined)
108 if (matchedTokens.length === 0) continue
110 additionalFilters[prefixKey] = prefixObj.multiple === true
116 search: searchTokens.join(' ') || undefined,