Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created January 23, 2020 21:40
Show Gist options
  • Save sibelius/f7320cdbb28bf078f56fb67308df723e to your computer and use it in GitHub Desktop.
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
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'),
};
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