Skip to content

Reuse and compose mappings

To reuse a mapping, register it and reference it by name. Registered mappings carry an $id and live in the registry you pass to the constructor:

const mappings = {
'mapping:Person': {
$id: 'mapping:Person',
source: '/',
mapping: {
'/name': '/fullName',
'/email': '/email'
}
}
}
const mapper = new Mapper({ mappings }, { initializers: {}, transformers: {}, plugins: {} })

Reference it anywhere a descriptor goes. A common shape is each with a $ref, one registered mapping applied per element:

/team:
source: /members
each:
$ref: 'mapping:Person'
{
"members": [
{ "fullName": "Grace Hopper", "email": "grace@example.com" },
{ "fullName": "Emmy Noether", "email": "emmy@example.com" }
]
}

becomes:

{
"team": [
{ "name": "Grace Hopper", "email": "grace@example.com" },
{ "name": "Emmy Noether", "email": "emmy@example.com" }
]
}

To build one mapping on another, inherit its pairings with $extend. Ancestor pairings run first. A pairing redefined in the child overrides the ancestor’s, in the child’s position:

const mappings = {
'mapping:Person': { /* as above */ },
'mapping:Employee': {
$id: 'mapping:Employee',
$extend: 'mapping:Person',
source: '/',
mapping: {
'/badge': '/badgeId'
}
}
}

Applying { $ref: 'mapping:Employee' } maps name, email, and badge.

$extend also takes a list. Ancestors merge in list order, later entries overriding earlier ones, and the extending mapping merges last:

const mappings = {
'mapping:Person': { /* as above */ },
'mapping:Contact': {
$id: 'mapping:Contact',
source: '/',
mapping: {
'/phone': '/phone'
}
},
'mapping:Employee': {
$id: 'mapping:Employee',
$extend: ['mapping:Person', 'mapping:Contact'],
source: '/',
mapping: {
'/badge': '/badgeId'
}
}
}

Now mapping:Employee maps name, email, phone, and badge. The registry stores each mapping flattened, with $extend already resolved, so a registered mapping can be serialized or re-registered on its own; see Registry keywords for the merge rules.