Giter Club home page Giter Club logo

mapper-js's Introduction

NOTICE

@arg-def/mapper-js has been move to @cookbook/mapper-js

In this process, there was a breaking change in the API and therefore is recommended you to read the documentation.

Got no time for this?

Short summary about the breaking changes

Before:

import mapper from '@arg-def/mapper-js';

const mapping = mapper.mapping((map) => ({ ... }));
const result = mapper(source, mapping);

After:

import mapper from '@cookbook/mapper-js';

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

const result = mapping(source);

Mapper Options

Before:

{
  suppressNullUndefined: false,
  suppressionStrategy: () => false,
}

After:

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

@arg-def/mapper-js

Fast, reliable and intuitive object mapping.

NPM Version Build 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 @arg-def/mapper-js

Installation

npm install @arg-def/mapper-js --save
#or
yarn add @arg-def/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!

import mapper from '@arg-def/mapper-js';

...

const mapping = mapper.mapping((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 mapper from '@arg-def/mapper-js';
...

const result = mapper(source, mapping);
/* 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: source: object, mapping: IMapping, options?: IMapperOptions

Description:

mapper() mappes your source data against your mapping.

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

Example:

mapper(source, mapping, options);

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

mapper.mapping

Type: function() Parameter: map Signature: (callback: IMapping): IMapping => callback;

Description:

mapper.mapping() is the method responsible for mapping the values from your source data against your object shape. It accepts dot notation path as key.

Example:

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

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

map

Type: function Parameter: paths: string|string[], option?: IMapperOptions Signature: <T>(key: string | string[], options?: IMapperOptions) => IMapMethods<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[] Signature: (callback: (...args: unknown[]) => T) => IMapMethods<T>

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

{
  suppressNullUndefined: false,
  suppressionStrategy: () => false,
}

Details

suppressNullUndefined

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.mapping((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,
}));

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

suppressionStrategy

Type: function Parameter: value: unknown Signature: (value: unknown) => boolean

Description:

Defines a custom strategy to 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 customSuppressionStrategy = (address: ISource): boolean => address && address.city === 'Cupertino';

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

mapper(source, mapping, { suppressionStrategy: customSuppressionStrategy );
/* outputs 
{
  name: 'John',
  age: 32,
}
*/

mapper-js's People

Contributors

dependabot[bot] avatar themgoncalves avatar

Stargazers

 avatar  avatar

Watchers

 avatar

mapper-js's Issues

null values

First want to say this is a really great library! It's helped alot with one of our projects.

One question. When assigning a value, is there a way to prevent it from creating the new mapping if the mapped object is null or undefined?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.