Created
February 11, 2020 22:44
-
-
Save iansan5653/aa8b6d99508a1a8a9331fe8a0f89260c to your computer and use it in GitHub Desktop.
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
type JSONValue = | |
| string | |
| number | |
| boolean | |
| null | |
| JSONValue[] | |
| {[key: string]: JSONValue}; | |
type ParsedJSON = {[key: string]: JSONValue}; | |
function assertMatchesSchema<Schema extends yup.ObjectSchema>( | |
json: ParsedJSON, | |
schema: Schema | |
): asserts json is yup.InferType<Schema> { | |
try { | |
schema.validateSync(json); | |
} catch (error) { | |
if (error instanceof yup.ValidationError) { | |
throw new TypeError( | |
`API response is missing fields or has invalid members. Details: ${error}` | |
); | |
} else { | |
throw error; | |
} | |
} | |
} | |
async function sendAndValidateRequest<Schema extends yup.ObjectSchema>( | |
url: string, | |
validationSchema: Schema | |
): Promise<yup.InferType<Schema>> { | |
const response = await (await fetch(url)).json(); | |
assertMatchesSchema(response, validationSchema); | |
return response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment