Skip to content

Instantly share code, notes, and snippets.

@realmayus
Created May 18, 2023 12:43
Show Gist options
  • Save realmayus/07929110aa1c031521116193f411be18 to your computer and use it in GitHub Desktop.
Save realmayus/07929110aa1c031521116193f411be18 to your computer and use it in GitHub Desktop.
A handy function that allows you to easily validate user input and generate a response with minimal code in the actual endpoints.
export const checkInput = (input: any, requiredKeys: string[], validator: {[key: string]: (arg0: any) => boolean | string | Response}): Response | true => {
for (const key of requiredKeys) {
if (!(key in input) || input[key] == null ) {
return new Response(JSON.stringify({error: `${key}-not-specified`}), {status: 400});
}
if (key in validator) {
const res = validator[key](input[key]);
if (typeof res === "string") {
return new Response(JSON.stringify({error: `${key}-${res}`}), {status: 400});
} else if (typeof res === "boolean" && !res) {
return new Response(JSON.stringify({error: `${key}-invalid`}), {status: 400});
} else if (typeof res === "object" && "statusText" in res) { // Response
return res;
}
}
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment