creating and publishing npm package "fwap", a typescript fetch wrapper
Browser fetch is a simple well supported built in http api which we use for some apps at Opentable.
But fetch has some differences to typical fetch libraries:
- it does not throw for 4xx and 5xx responses, you have to check the ok property and if not true then it's a failed error code
- you have to call async json() on the response to convert to json (tiny tedium)
So a simple wrapper facade over fetch to take care of these would be nice eh!
And how about we use Typescript and use built in http types like RequestInit and Response as well as generics.
That's what fwap is! and it's now available on npm.
Of course our code has unit tests.
Yes it's yet another fetch wrapper (yafwap was another name I considered) but it's also a good learning experience (it's the journey as much as the destination maaannnn)
All my references are at the bottom of this post and I'm much indebted to those authors
How I created:
- git init and npm init
- confirm fwap not already used
- add typescript
- src code in /src (outDir)
- build output in /build (rootDir)
- add eslint
- add jest
- jest supports typescript via babel so need to follow the jest instructions for jest, typescript and babel
- involves adding babel.config.js
- add jest-fetch-mock npm
- write code and unit tests
- test locally with test app
- publish to npm
See the npm package here. Go play with it.
Future improvements:
- add better handling for non json api responses: some apis will return a string in the payload, would be nice to handle that and return that as json.
- I could change to have callers pass the body as separate param instead of they adding to the init object
- add source maps support
References:
- https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
- https://eckertalex.dev/blog/typescript-fetch-wrapper
- https://khalilstemmler.com/blogs/typescript/eslint-for-typescript/
- https://www.leighhalliday.com/mock-fetch-jest
- https://bugfender.com/blog/how-to-create-an-npm-package/
- https://itnext.io/step-by-step-building-and-publishing-an-npm-typescript-package-44fe7164964c
Comments
Post a Comment