Created
May 18, 2023 12:43
-
-
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.
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 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