Created
October 6, 2020 19:27
-
-
Save silesky/ee67b324394448c9a2f905cf21b0406a to your computer and use it in GitHub Desktop.
io-ts with promises
This file contains 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
import * as t from 'io-ts'; | |
import { PathReporter } from 'io-ts/lib/PathReporter'; | |
import * as tPromise from 'io-ts-promise'; | |
// [io-ts][https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts) | |
// [Take control of unexpected data at runtime with TypeScript](https://blog.logrocket.com/using-typescript-to-stop-unexpected-data-from-breaking-your-app/) | |
const fetchProduct = () => { | |
return Promise.resolve({ | |
id: '123', | |
name: '15mg cbd pen', | |
category: ['vapes'], | |
location: {}, // error | |
}); | |
}; | |
// Product is now a "codec" -- a runtime representation of the static type "Product" | |
const Product = t.type({ | |
id: t.string, | |
name: t.string, | |
category: t.array(t.string), | |
location: t.type({ | |
warehouses: t.array(t.string), | |
}), | |
}); | |
// this special t.typeOf operator gives us the vanilla | |
type Product = t.TypeOf<typeof Product>; | |
const getProduct = async (): Promise<Product | void> => { | |
try { | |
const product = await fetchProduct().then(tPromise.decode(Product)); | |
return product; | |
} catch (err) { | |
if (tPromise.isDecodeError(err)) { | |
console.log('error due to decoding issue'); | |
} else { | |
console.log('error due to network issue'); | |
} | |
return; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment