@cmath10/js-mapper

中文文档
1.2.2发布于 2022/04/06MITTypeScriptESM + CJS零依赖近 30 天下载 1万

Mapper

原始使用文档
文档目录5 节
  1. Installation
  2. API
  3. Extractors
  4. Filters
  5. Injectors

JsMapper - JavaScript mapping helper

The component helps transform objects into each other by reusable maps. One of the main use cases - converting JSON API responses into appropriate form.

Usage example:

import JsMapper, { JsMap } from '@cmath10/js-mapper'

const mapper = new JsMapper()
  .set('StudioPayload', new JsMap()
    .route('name', '_name')
  )
  .set('FilmPayload', new JsMap()
    .route('id', '_id')
    .route('name', '_name')
  )
  .set('FilmCollectionPayload', new JsMap()
    .route('studio', '_studio')
    .filter('studio', 'StudioPayload')
    .route('films', '_films')
    .filter('films', '[FilmPayload]')
  )

const collection = mapper.map('FilmCollectionPayload', {
  _studio: { _name: 'Lucasfilm Ltd. LLC' },
  _films: [{
    _id: 1,
    _name: 'Star Wars. Episode IV: A New Hope',
  }, {
    _id: 6,
    _name: 'Star Wars. Episode III. Revenge of the Sith',
  }],
})

result is

{
  "studio": { "name": "Lucasfilm Ltd. LLC" },
  "films": [{
    "id": 1,
    "name": "Star Wars. Episode IV: A New Hope"
  }, {
    "id": 6,
    "name": "Star Wars. Episode III. Revenge of the Sith"
  }]
}

Installation

yarn add @cmath10/js-mapper

or

npm i @cmath10/js-mapper

API

JsMapper - helper class that maps objects:

import JsMapper from '@cmath10/js-mapper'

Methods:

  • map(typeOrMap, source, destination = undefined) — maps source object to destination object, if destination object not specified, it will be created; you are also able to supply map instance instead of map type to use map without registration;
  • set(type, map) — sets map instance by type name (adds if type name not registered yet);
  • get(type, clone = true) — returns map instance by type name, if flag clone is set will return copy of map;
  • unset(type) — removes map by type name from mapper instance;

Important note: you are able to map arrays of objects with map method, just register a map for single object with a name for example MapTypeName and use method like mapper.map('[MapTypeName]', %array of objects%)

JsMap - map class, accumulates mapping information:

import { JsMap } from '@cmath10/js-mapper'
  • destination(destination) — sets factory for a destination, default factory is () => ({});
  • route(destinationMember, sourceMember, fallback = undefined) — sets path extractor by source member; source member could be a deep route like path.to.source.property; if the path is not reachable and fallback is defined, fallback will be used as extracted value;
  • forMember(destinationMember, extractor) — sets a custom extractor for a destination member;
  • filter(destinationMember, filter) — sets a custom filter for value processing;
  • inject(destinationMember, injector) — sets a custom injector for a destination member;
  • exclude(destinationMember) — removes destination member from a map;
  • clone() — creates copy of map;

Extractors

Extractors are used for extracting value from a source. Available extractors:

import {
  JsMapCallbackExtractor,
  JsMapExtractor,
  JsMapPathExtractor,
} from '@cmath10/js-mapper'

JsMapExtractor

JsMapExtractor is the basic extractor class. Extracts nothing, just throws an error (like abstract class without implementation). All other extractors should extend this class and implement its extract method.

JsMapPathExtractor

Extracts value from source by property path. Throws an error if path is not valid and fallback is undefined. Used by default.

JsMapCallbackExtractor

Extracts value by callback function like (source: unknown) => unknown:

const mapper = new JsMapper()
  .set('Demo', new JsMap()
    .forMember('text', new JsMapCallbackExtractor(source => source._text))
  )

mapper.map('Demo', { _text: 'text' }) // { text: 'text' }

Sugar:

const map = new JsMap()
  .forMember('text', source => source._text)

Filters

Filters are used for processing value before injecting it into a destination. Available filters:

import {
  JsMapCallbackFilter,
  JsMapFilter,
  JsMapFilterChain,
  JsMapMappingFilter,
} from '@cmath10/js-mapper'

JsMapFilter

JsMapFilter is the basic filter class, that used by default and actually just returns source value. JsMapper instance is being injected into each JsMapFilter instance, so it is possible to create filters with complicated processing chains with nested mapping. All other filters should extend this class.

JsMapCallbackFilter

This is a simple filter is using a callback function to process value:

const mapper = new JsMapper()
  .set('Demo', new JsMap()
    .route('text', 'text')
    .filter('text', new JsMapCallbackFilter(value => {
      if (typeof value === 'string') {
        return value.toUpperCase()
      }

      throw new Error()
    }))
  )

mapper.map('Demo', { text: 'text' }) // { text: 'TEXT' }

Callback function is presumed as (value: unknown) => unknown. Sugar:

const map = new JsMap()
    .route('text', 'text')
    .filter('text', value => {
      if (typeof value === 'string') {
        return value.toUpperCase()
      }

      throw new Error()
    })

JsMapMappingFilter

This filter is using map type to apply maps to a value (nested mapping opportunity):

const mapper = new JsMapper()
  .set('FilmPayload', new JsMap()
    .route('id', '_id')
    .route('name', '_name')
  )
  .set('Demo', new JsMap()
    .route('film', '_film')
    .filter('film', new JsMapMappingFilter('FilmPayload'))
  )

mapper.map('Demo', { _film: {
  _id: 1,
  _name: 'Star Wars. Episode IV: A New Hope',
} }) // { film: { id: 1, name: 'Star Wars. Episode IV: A New Hope' } }

Sugar:

const map = new JsMap()
    .route('film', '_film')
    .filter('film', 'FilmPayload')

JsMapFilterChain

This filter provides opportunity to create filtering pipelines:

const mapper = new JsMapper()
  .set('FilmPayload', new JsMap()
    .route('id', '_id')
    .route('name', '_name')
    .filter('name', new JsMapFilterChain([
      new JsMapCallbackFilter(value => value.toUpperCase()),
      new JsMapCallbackFilter(value => '<<' + value + '>>'),
    ]))
  )
  .set('Demo', new JsMap()
    .route('film', '_film')
    .filter('film', new JsMapFilterChain([
      new JsMapMappingFilter('FilmPayload'),
      new JsMapCallbackFilter(value => value.name)
    ]))
  )

mapper.map('Demo', { _film: {
  _id: 1,
  _name: 'Star Wars. Episode IV: A New Hope',
} }) // { film: '<<STAR WARS. EPISODE IV: A NEW HOPE>>' }

Sugar:

const mapper = new JsMapper()
  .set('FilmPayload', new JsMap()
    .route('id', '_id')
    .route('name', '_name')
    .filter('name', [
      value => value.toUpperCase(),
      value => '<<' + value + '>>',
    ])
  )
  .set('Demo', new JsMap()
    .route('film', '_film')
    .filter('film', ['FilmPayload', film => film.name])
  )

Injectors

Injectors are used for injecting a processed value into destination object. Available injectors:

import {
  JsMapInjector,
} from '@cmath10/js-mapper'

JsMapInjector is the basic injector class, that used by default. It uses destination member name as property key. If property is function, it will be used as setter (i.e. called with destination as new this and value as parameter). All other injectors should extend this class.

Setter example:

const mapper = new JsMapper()
  .set('DatePayload', new JsMap()
    .destination(() => new Date())
    .route('setHours', 'hours')
  )

mapper.map({ hours: 0 }).getHours() // 0
mapper.map({ hours: 1 }).getHours() // 1

Custom injector example:

const mapper = new JsMapper()
  .set('DatePayload', new JsMap()
    .destination(() => new Date())
    .route('hours', 'hours')
    .inject('hours', new class extends JsMapInjector {
      inject(destination, path, value): void {
        destination.setHours(value)
      }
    })
  )

mapper.map({ hours: 0 }).getHours() // 0
mapper.map({ hours: 1 }).getHours() // 1

版本与发布记录

@cmath10/js-mapper 共发布 5 个版本,首次发布于 2021/05/06;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.2.2latest2022/04/064 年前
1.2.12021/06/015 年前
1.2.02021/05/185 年前
1.1.02021/05/075 年前
1.0.02021/05/065 年前

关于 @cmath10/js-mapper 的常见问题

@cmath10/js-mapper 是什么?

Mapper

如何安装 @cmath10/js-mapper?

在项目目录运行 npm install @cmath10/js-mapper,或使用 pnpm add / yarn add / bun add。

@cmath10/js-mapper 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cmath10/js-mapper 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cmath10/js-mapper 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=12。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cmath10/js-mapper 可以商用吗?

@cmath10/js-mapper 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cmath10/js-mapper 的下载量有多少?

根据 npm 官方下载统计,@cmath10/js-mapper 在 2026/10/10 – 2026/11/08 这 30 天内被下载 10,133 次,日均约 338 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cmath10/js-mapper 还在维护吗?

最新版本 1.2.2 发布于 2022/04/06(4 年前);至今共发布 5 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/05/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。