api-adapter

1.1.0 • Public • Published

npm version

api-adapter

Decouple the shape of your data on the client and server.

Allows you to easily convert unfortunately named properties on server responses so that they're most pleasant to work with on the client. Even supports deep flattening and nesting of values.

Defining the mapping of server to client data in a single spot means no more renaming in hundreds of files when someone changes the property names on the backend.

Installation

npm install api-adapter

Usage

The helper createAdapter takes an object with keys equal to unwanted https://lodash.com/docs#get in your API response, and values equal to desired property paths to use in your client.

import { createAdapter } from 'api-adapter';
const adapter = createAdapter({
  name: 'title',
  'other.band': 'artist',
});

The fromApi method will then convert your data into a pleasant format you can use in the client.

const clientData = adapter.fromApi({
  name: 'Blue in Green',
  other: {
    band: 'Bill Evans',
  },
});
 
console.log(clientData);
// { artist: 'Bill Evans', title: 'Blue in Green' }

Then, the toApi method will then convert back to the API structure when you're ready to send an update to the server.

const apiData = adapter.toApi({
  artist: 'Bill Evans',
  title: 'Blue in Green',
});
 
console.log(apiData);
// { name: 'Blue in Green', other: { band: 'Bill Evans' } }

Both methods can also handle arrays!

const clientData = adapter.fromApi([
  { name: 'Blue in Green', other: { band: 'Bill Evans' } },
  { name: 'マイワールド', other: { band: 'ASIAN KUNG-FU GENERATION' } },
]);
 
console.log(clientData);
// [
//   { artist: 'Bill Evans', title: 'Blue in Green' },
//   { artist: 'ASIAN KUNG-FU GENERATION', title: 'マイワールド' },
// ]

Readme

Keywords

none

Package Sidebar

Install

npm i api-adapter

Weekly Downloads

0

Version

1.1.0

License

ISC

Last publish

Collaborators

  • nickjohnson-dev