fix(striker-ui-api): add fallback to sanitize

main
Tsu-ba-me 2 years ago
parent d1b53b4a2c
commit efc8832321
  1. 19
      striker-ui-api/src/lib/sanitize.ts

@ -12,6 +12,7 @@ type MapToReturnFunction = {
[ReturnTypeName in keyof MapToReturnType]: ( [ReturnTypeName in keyof MapToReturnType]: (
value: unknown, value: unknown,
modifier: (unmodified: unknown) => string, modifier: (unmodified: unknown) => string,
fallback?: MapToReturnType[ReturnTypeName],
) => MapToReturnType[ReturnTypeName]; ) => MapToReturnType[ReturnTypeName];
}; };
@ -29,10 +30,10 @@ const MAP_TO_MODIFIER_FUNCTION: MapToModifierFunction = {
const MAP_TO_RETURN_FUNCTION: MapToReturnFunction = { const MAP_TO_RETURN_FUNCTION: MapToReturnFunction = {
boolean: (value) => value !== undefined, boolean: (value) => value !== undefined,
number: (value) => parseFloat(String(value)) || 0, number: (value, mod, fallback = 0) => parseFloat(String(value)) || fallback,
string: (value, mod) => (value ? mod(value) : ''), string: (value, mod, fallback = '') => (value ? mod(value) : fallback),
'string[]': (value, mod) => { 'string[]': (value, mod, fallback = []) => {
let result: string[] = []; let result: string[] = fallback;
if (value instanceof Array) { if (value instanceof Array) {
result = value.reduce<string[]>((reduceContainer, element) => { result = value.reduce<string[]>((reduceContainer, element) => {
@ -54,18 +55,24 @@ export const sanitize = <ReturnTypeName extends keyof MapToReturnType>(
value: unknown, value: unknown,
returnType: ReturnTypeName, returnType: ReturnTypeName,
{ {
fallback,
modifierType = 'none', modifierType = 'none',
modifier = MAP_TO_MODIFIER_FUNCTION[modifierType], modifier = MAP_TO_MODIFIER_FUNCTION[modifierType],
}: { }: {
fallback?: MapToReturnType[ReturnTypeName];
modifier?: ModifierFunction; modifier?: ModifierFunction;
modifierType?: keyof MapToModifierFunction; modifierType?: keyof MapToModifierFunction;
} = {}, } = {},
): MapToReturnType[ReturnTypeName] => ): MapToReturnType[ReturnTypeName] =>
MAP_TO_RETURN_FUNCTION[returnType](value, (unmodified: unknown) => { MAP_TO_RETURN_FUNCTION[returnType](
value,
(unmodified: unknown) => {
const input = String(unmodified); const input = String(unmodified);
return call<string>(modifier, { return call<string>(modifier, {
notCallableReturn: input, notCallableReturn: input,
parameters: [input], parameters: [input],
}); });
}) as MapToReturnType[ReturnTypeName]; },
fallback,
) as MapToReturnType[ReturnTypeName];

Loading…
Cancel
Save