Client - refactoring pagination query

This commit is contained in:
Sam
2021-11-02 10:58:25 +01:00
parent 73a0b53dd7
commit c5428c28a6
4 changed files with 304 additions and 37 deletions

View File

@ -0,0 +1,50 @@
import { LocationQuery } from 'vue-router'
import { IQueryOptions, TPaginationPayload } from '@/types/api'
export const sortList: string[] = ['asc', 'desc']
export const defaultPage = 1
export const defaultPerPage = 10
export const getNumberQueryValue = (
queryValue: string | (string | null)[] | null,
defaultValue: number
): number => {
return queryValue && typeof queryValue === 'string' && +queryValue > 0
? +queryValue
: defaultValue
}
export const getStringQueryValue = (
queryValue: string | (string | null)[] | null,
availableValues: string[],
defaultValue: string
): string => {
return queryValue &&
typeof queryValue === 'string' &&
availableValues.includes(queryValue)
? queryValue
: defaultValue
}
export const getQuery = (
locationQuery: LocationQuery,
orderByList: string[],
defaultOrderBy: string,
options?: IQueryOptions
): TPaginationPayload => {
const queryOptions = options || {}
const defaultSort = queryOptions.defaultSort || 'asc'
const query = queryOptions.query || <TPaginationPayload>{}
query.page = getNumberQueryValue(locationQuery.page, defaultPage)
query.per_page = getNumberQueryValue(locationQuery.per_page, defaultPerPage)
query.order = getStringQueryValue(locationQuery.order, sortList, defaultSort)
query.order_by = getStringQueryValue(
locationQuery.order_by,
orderByList,
defaultOrderBy
)
return query
}