Created
January 23, 2020 21:40
-
-
Save sibelius/f7320cdbb28bf078f56fb67308df723e to your computer and use it in GitHub Desktop.
getSchemaParam to build a complex querystring filter param to use use-query-params
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const dateRangeDefinition = { | |
begin: MomentParam, | |
end: MomentParam, | |
}; | |
const DateRangeParam = getSchemaParam(dateRangeDefinition); | |
const decoded = FilterParam.decode('begin-2019-05-19T03:00:00.000Z_end-2019-05-19T03:00:00.000Z'); | |
const decoded = { | |
begin: moment('2019-05-19T03:00:00.000Z'), | |
end: moment('2019-05-19T03:00:00.000Z'), | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const getSchemaParam = (objParam: QueryParamConfig<any>): QueryParamConfig<any> => { | |
return { | |
encode(input: object) { | |
const objEncoded = Object.keys(input).reduce((acc, key) => { | |
const value = input[key]; | |
const param = objParam[key]; | |
// is it a QueryParam? | |
if (param && param.encode && param.decode) { | |
return { | |
...acc, | |
[key]: param.encode(value), | |
}; | |
} | |
return { | |
...acc, | |
[key]: value, | |
}; | |
}, {}); | |
return encodeObject(objEncoded); | |
}, | |
decode(input: string | string[] | undefined): object | undefined { | |
if (input == null || !input.length) { | |
return undefined; | |
} | |
const obj = decodeObject(input); | |
return Object.keys(obj).reduce((acc, key) => { | |
const value = obj[key]; | |
const param = objParam[key]; | |
// is it a QueryParam? | |
if (param && param.encode && param.decode) { | |
return { | |
...acc, | |
[key]: param.decode(value), | |
}; | |
} | |
return { | |
...acc, | |
[key]: value, | |
}; | |
}, {}); | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment