Skip to content

Instantly share code, notes, and snippets.

@rylnd
Last active August 6, 2020 19:30
Show Gist options
  • Select an option

  • Save rylnd/0d6fb56153858ba2e88dc395e9b96119 to your computer and use it in GitHub Desktop.

Select an option

Save rylnd/0d6fb56153858ba2e88dc395e9b96119 to your computer and use it in GitHub Desktop.
Proposal: Using io-ts to validate request/response
type I = unknown;
type A = RequestOverWire // snake case, optionals
type O = RequestToUse // camelCase, all keys present, values defaulted
// frontend
const request: I = { id: 'my-id' };
const payload: A = requestSchema.decode(request);
if (isLeft(payload)) {
displayErrors(payload);
} else {
makeApiCall(payload);
}
// backend
const payload: A = requestSchema.decode(request);
if (isLeft(payload)) {
return errorResponse(payload);
}
const requestToUse: O = requestSchema.encode(payload);
@rylnd
Copy link
Author

rylnd commented Aug 6, 2020

Notes:

  • type A represents the request that’s sent/received: snake_cased, optional keys
  • decode should do no transformation of I (except to trim keys with exact)
  • sender is responsible for getting decode to succeed (converting to snake_case, making query params strings, etc.)
  • type O represents the request to be consumed by the application: camelCased, all keys present
  • encode is where most of the processing should go: snake_case to camelCase, setting of default values

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment