Skip to content

Instantly share code, notes, and snippets.

@iansan5653
Created February 11, 2020 22:44
Show Gist options
  • Save iansan5653/aa8b6d99508a1a8a9331fe8a0f89260c to your computer and use it in GitHub Desktop.
Save iansan5653/aa8b6d99508a1a8a9331fe8a0f89260c to your computer and use it in GitHub Desktop.
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