import urls from 'url' ; import express from 'express' ; import { parseObjectProperties , ParseObjectPropertiesOptions } from '@mds-core/mds-utils' ; interface PagingParams { skip : number ; take : number ; } const jsonApiLink = ( req , skip , take ) : string => urls . format ( { protocol : req . get ( 'x-forwarded-proto' ) || req . protocol , host : req . get ( 'host' ) , pathname : req . path , query : { ... req . query , skip , take } } ) ; export type JsonApiLinks = Partial < { first : string ; prev : string ; next : string ; last : string ; } > | undefined ; export const asJsonApiLinks = ( req , skip , take , count ) : JsonApiLinks => { if ( skip > 0 || take < count ) { const first = skip > 0 ? jsonApiLink ( req , 0 , take ) : undefined ; const prev = skip - take >= 0 && skip - take < count ? jsonApiLink ( req , skip - take , take ) : undefined ; const next = skip + take < count ? jsonApiLink ( req , skip + take , take ) : undefined ; const last = skip + take < count ? jsonApiLink ( req , count - ( count % take || take ) , take ) : undefined ; return { first , prev , next , last } ; } return undefined ; } ; export const parseRequest = < T = string > ( req , options ? ) => { const { keys : query } = parseObjectProperties < T > ( req . query , options ) ; const { keys : params } = parseObjectProperties < T > ( req . params , options ) ; return { params , query } ; } ; export const parsePagingQueryParams = ( req ) => { const [ DEFAULT_PAGE_SIZE , MAX_PAGE_SIZE ] = [ 100 , 1000 ] ; const { skip = 0 , take = DEFAULT_PAGE_SIZE } = parseRequest ( req , { parser : Number } ) . query ( 'skip' , 'take' ) ; return { skip : Number . isNaN ( skip ) ? 0 : Math . max ( 0 , skip ) , take : Number . isNaN ( take ) ? DEFAULT_PAGE_SIZE : Math . min ( take , MAX_PAGE_SIZE ) } ; } ;