Skip to content

the-cookbook/mapper-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@cookbook/mapper-js

Fast, reliable and intuitive object mapping.

NPM Version CI Status Downloads Stats GitHub stars Known Vulnerabilities GitHub issues Awesome install size gzip size

Demo

Play around with mapper-js and experience the magic!

Edit @cookbook/mapper-js

Installation

npm install @cookbook/mapper-js --save
#or
yarn add @cookbook/mapper-js

How to use

1) Know the structure from your source data

Before we start, it is essential that we know your data structure so we can map it accordingly.

For this demo case, let's assume that we have the following object:

const source = {
  person: {
    name: {
      firstName: 'John',
      lastName: 'Doe',
    },
    age: 32,
    drinks: ['beer', 'whiskey'],
    address: [
      {
        street: 'Infinite Loop',
        city: 'Cupertino',
        state: 'CA',
        postalCode: 95014,
        country: 'United States',
      },
      {
        street: '1600 Amphitheatre',
        city: 'Mountain View',
        state: 'CA',
        postalCode: 94043,
        country: 'United States',
      },
    ],
  },
};

2) Create your mapping using dot notation

At this step, we need to create our mapping against our data source.

We will be using dot notation to create our final structure.

For more info about dot notation API, check out the documentation

With mapper, it is possible to get one or several values from our source and even transform it in the way we need.

For that, map() accepts single dot notation path or an array of dot notation paths. E.g.: map('person.name.firstName'), map([person.name.firstName, person.name.lastName]);'

Those values can be transformed by using the .transform() method, which expects a function as argument and provides the selected values as array in the parameter.

For more information about the usage, check the API Documentation.

Now let's create our mapping!

// mapping.ts
import mapper from '@cookbook/mapper-js';

...

const mapping = mapper((map) => ({
  'person.name': map('person.name')
                .transform(({ firstName, lastName }) => `${firstName} ${lastName}`)
                .value,
  'person.lastName': map('person.lastName').value,
  'person.isAllowedToDrive': map(['person.age', 'person.drinks'])
  				.transform((age, drinks) => age > 18 && drinks.includes('soft-drink'))
  				.value,
  address: map('person.address').value,
  defaultAddress: map('person.address[0]').value,
}));

3) Create your mapped object

import mapping from './mapping';
...

const result = mapping(source);
/* outputs
{
  person: {
    name: 'John Doe',
    isAllowedToDrive: false,
  },
  address: [
    {
      street: 'Infinite Loop',
      city: 'Cupertino',
      state: 'CA',
      postalCode: 95014,
      country: 'United States'
    },
    ...
  ],
  defaultAddress: {
    street: 'Infinite Loop',
    city: 'Cupertino',
    state: 'CA',
    postalCode: 95014,
    country: 'United States'
  }
}
*/

API Documentation

mapper

Type: function() Parameter: mapping: Mapping Return: <T>(source: object | object[], options?: Options) => T extends [] ? T[] : T, Signature: (mapping: Mapping) => <T>(source: object | object[], options?: Options) => T extends [] ? T[] : T

Description:

mapper() is the main method and responsible for mapping the values from your data source against the mapping instructions. It accepts dot notation path(s) as key(s).

Example:

// raw definition
const mapping = mapper((map) => ({
    ...
}));

// with map() query
const mapping = mapper((map) => ({
  'employee.name': map('person.name.firstName').value,
  'employee.age': map('person.name.age').value,
  'employee.address': map('person.address').value,
}));

As a result from the above implementation, mapper() return a new function to map and compile your source data against your mapping.

It accepts an extra (optional) argument defining the global mapping options.

Example:

...

mapping(source, options);

/* outputs
{
  employee: {
    name: 'John',
    age: 32,
    address: [
      {
        street: 'Infinite Loop',
        city: 'Cupertino',
        state: 'CA',
        postalCode: 95014,
        country: 'United States'
      },
      ...
    ],
  },
}
*/

map

Type: function Parameter: keys: string | string[], options?: Options Return: MapMethods<T>, Signature: <T = unknown>(keys: string | string[], options?: Options) => MapMethods<T>

Description:

root method retrieves values from your source data using dot notation path, it accepts a string or array of string.

It accepts an extra (optional) argument to define the mapping options for current entry, overriding the global mapping options.

Example:

map('person.name.firstName');
map(['person.name.firstName', 'person.name.lastName']);
map(['person.name.firstName', 'person.name.lastName'], options);

transform

Type: function Parameter: ...unknown[] Return: unknown | unknown[], Signature: (...args: unknown[]) => unknown | unknown[]

Description:

.transform method provides you the ability to transform the retrieved value(s) from map() according to your needs, and for that, it expects a return value.

.transform provides you as parameter, the retrieved value(s) in the same order as defined in the map() method, otherwise

Example:

// single value
map('person.name.firstName').transform((firstName) => firstName.toLoweCase());

// multiple values
map(['person.name.firstName', 'person.name.lastName']).transform((firstName, lastName) => `${firstName} ${lastName}`);

value

Type: readonly Return: T Description:

.value returns the value of your dot notation query. If transformed, returns the transformed value.

Example:

// single value
map('person.name.firstName').transform((firstName) => firstName.toLoweCase()).value;

// multiple values
map(['person.name.firstName', 'person.name.lastName']).transform((firstName, lastName) => `${firstName} ${lastName}`)
  .value;

Mapper Options

defaults

{
  omitNullUndefined: false,
  omitStrategy: () => false,
}

Details

omitNullUndefined

Type: boolean default value: false

Description:

Removes null or undefined entries from the mapped object.

Example:

/* source object
{
  person: {
    name: 'John',
    lastName: 'Doe',
    age: 32,
  },
}
*/
const mapping = mapper((map) => ({
  name: map('person.name').value,
  age: map('person.age').value,
  // source doesn't have property 'address',
  // therefore will return "undefined"
  address: map('person.address').value,
}));

mapping(source, { omitNullUndefined: true });
/* outputs 
{
  name: 'John',
  age: 32,
}
*/

omitStrategy

Type: function Parameter: value: unknown | unknown[] Return: boolean Signature: (value: unknown | unknown[]) => boolean

Description:

Defines a custom strategy to omit (suppress) entries from the mapped object.

Example:

/* source object
{
  person: {
    name: 'John',
    lastName: 'Doe',
    age: 32,
    address: {
      street: 'Infinite Loop',
      city: 'Cupertino',
      state: 'CA',
      postalCode: 95014,
      country: 'United States',
    }
  },
}
*/

const customOmitStrategy = (address: Record<string, string>): boolean => address && address.city === 'Cupertino';

const mapping = mapper((map) => ({
  name: map('person.name').value,
  age: map('person.age').value,
  address: map('person.address').value,
}));

mapping(source, { omitStrategy: customOmitStrategy });
/* outputs 
{
  name: 'John',
  age: 32,
}
*/