Today I Learned - Rocky Kev

TIL tips for making a API Wrapper

POSTED ON:

TAGS:

On Reddit, a poster u/Revelnova asks about advice with publishing their first NPM package.

Via u/Revelnova:

The objective for the client is to make transforming and fetching content data super easy for developers using the CMS platform.

Their stance was that by making the client as simple as possible, I’m not locking users into the use cases I imagine but instead leaves room for developers to build features on top of the client.

The feedback via r/ecafyelims:

In my experience, the best API wrappers are the ones that are so thin, they're transparent.

You might already do this, but just some suggestions:

This is all great.

r/ecafyelims has one big one:

Aim so that if the API is updated to allow a new endpoint or parameter, the wrapper will already work because the endpoints are not hard-coded.

For example:

// This method:
// hardcodes params and endpoints
const products = await apiWrapper.getProducts(categoryId, colorName);


// This method:
// opens up more flexibility
const products = await apiWrapper('products').get({categoryId, colorName});

// that way, you can also do this
const stores = await apiWrapper('stores').get({nearZipCode});

That way, if the API is updated later to add a new endpoint (e.g. "stores"), you don't have to touch the wrapper. It'll just work.


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.