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:
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

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more