bandeng-mapper
v1.0.1
Published
Mapper for node.js
Readme
bandeng-mapper
English
Overview
bandeng-mapper is a powerful and flexible data mapping library for Node.js that allows you to transform JSON data structures based on schema configurations. It provides a declarative way to map, transform, and validate data with support for field renaming, type conversion, default values, nested objects, and arrays.
Features
- Simple Configuration: Use
0to exclude fields or1to include fields - Object Configuration: Fine-grained control with
required,type,rename,default, anditemsoptions - Field Name Transformation: Automatic conversion between camelCase and snake_case
- Type Conversion: Convert values to
stringorarraytypes - Field Renaming: Rename fields during mapping
- Default Values: Provide fallback values for empty fields
- Array Handling: Support for array inputs, array fields, and nested arrays
- Deep Nesting: Handle deeply nested objects and arrays
- Input Validation: Comprehensive schema validation with clear error messages
- Edge Case Handling: Graceful handling of null, undefined, empty strings, and non-object inputs
Installation
npm install bandeng-mapperQuick Start
const Mapper = require('bandeng-mapper')
// Create a mapper instance
const mapper = new Mapper()
// Define a schema
const schema = {
name: 1, // Simple: include field
age: 0, // Simple: exclude field
email: {
// Object: detailed configuration
required: true,
type: 'string',
rename: 'emailAddress'
}
}
// Map data
const data = {
name: 'John',
age: 30,
email: '[email protected]'
}
const result = mapper.map(data, schema)
// Result: { name: 'John', emailAddress: '[email protected]' }Configuration Options
Constructor Options
const mapper = new Mapper({
fieldCase: 'camel' // 'camel' | 'snake' | 'none' (default: 'none')
})- fieldCase: Controls automatic field name transformation
'camel': Converts snake_case to camelCase (e.g.,user_name→userName)'snake': Converts camelCase to snake_case (e.g.,userName→user_name)'none': No transformation (default)
Schema Configuration
Simple Configuration
0: Exclude the field from output1: Include the field as-is
Simple configuration can be used at any nesting level:
const schema = {
name: 1, // Include
age: 0, // Exclude
address: {
street: 1,
zip: 0 // Simple config works in nested objects too
}
}Object Configuration
{
required: boolean, // false: exclude, true: include (default: true)
type: string, // 'string' | 'array' | null
rename: string, // New field name (or null to keep original)
default: any, // Default value (null/undefined won't be used)
items: object // Schema for array items or nested objects
}Usage Examples
Basic Field Mapping
const mapper = new Mapper()
const schema = {
name: 1,
age: 0,
email: {required: true}
}
const data = {name: 'John', age: 30, email: '[email protected]'}
const result = mapper.map(data, schema)
// { name: 'John', email: '[email protected]' }Field Renaming
const schema = {
name: {required: true, rename: 'fullName'},
age: {required: true, rename: 'userAge'}
}
const data = {name: 'John', age: 30}
const result = mapper.map(data, schema)
// { fullName: 'John', userAge: 30 }Type Conversion
const schema = {
age: {required: true, type: 'string'},
tags: {required: true, type: 'array', default: []}
}
const data = {age: 30, tags: ['developer', 'nodejs']}
const result = mapper.map(data, schema)
// { age: '30', tags: ['developer', 'nodejs'] }Default Values
const schema = {
name: {required: true, default: 'Unknown'},
age: {required: true, default: 0},
tags: {required: true, type: 'array', default: []}
}
const data = {}
const result = mapper.map(data, schema)
// { name: 'Unknown', age: 0, tags: [] }Note: Default values are only used when the field value is null, undefined, or empty string (''). If default is explicitly set to null, it won't be used.
Field Case Transformation
// Camel case conversion
const mapper = new Mapper({fieldCase: 'camel'})
const schema = {user_name: 1, user_age: 1}
const data = {user_name: 'John', user_age: 30}
const result = mapper.map(data, schema)
// { userName: 'John', userAge: 30 }
// Snake case conversion
const mapper2 = new Mapper({fieldCase: 'snake'})
const schema2 = {userName: 1, userAge: 1}
const data2 = {userName: 'John', userAge: 30}
const result2 = mapper2.map(data2, schema2)
// { user_name: 'John', user_age: 30 }Array Handling
// Array input
const schema = {name: 1, age: 1}
const data = [
{name: 'John', age: 30},
{name: 'Jane', age: 25}
]
const result = mapper.map(data, schema)
// [
// { name: 'John', age: 30 },
// { name: 'Jane', age: 25 }
// ]
// Array field with items configuration
const schema2 = {
users: {
required: true,
type: 'array',
items: {
name: {required: true, rename: 'fullName'},
age: {required: true, type: 'string'}
}
}
}
const data2 = {
users: [
{name: 'John', age: 30},
{name: 'Jane', age: 25}
]
}
const result2 = mapper.map(data2, schema2)
// {
// users: [
// { fullName: 'John', age: '30' },
// { fullName: 'Jane', age: '25' }
// ]
// }Nested Objects
You can use simple configuration (0 and 1) directly in nested objects, or use items for more complex configurations:
// Using simple configuration directly in nested objects
const schema = {
address: {
addressInfo: {
address: 1,
city: 1,
state: 1,
zip: 0 // Exclude zip field
}
}
}
const data = {
address: {
addressInfo: {
address: '123 Main St',
city: 'New York',
state: 'NY',
zip: '10001' // Will be excluded
}
}
}
const result = mapper.map(data, schema)
// {
// address: {
// addressInfo: {
// address: '123 Main St',
// city: 'New York',
// state: 'NY'
// }
// }
// }// Using items configuration for nested objects
const schema = {
user: {
required: true,
items: {
profile: {
required: true,
items: {
name: 1,
email: {required: true, rename: 'emailAddress'}
}
}
}
}
}
const data = {
user: {
profile: {
name: 'John',
email: '[email protected]',
age: 30 // Will be excluded
}
}
}
const result = mapper.map(data, schema)
// {
// user: {
// profile: {
// name: 'John',
// emailAddress: '[email protected]'
// }
// }
// }Complex Example
const mapper = new Mapper({fieldCase: 'camel'})
const schema = {
name: {
required: true,
type: 'string',
default: '',
rename: 'label'
},
age: 0, // Exclude
city: 1, // Include as-is
phone: {
required: true,
type: 'array',
default: [],
rename: 'phoneList',
items: {
type: {
required: true,
type: 'string',
rename: 'phoneType'
},
number: {
required: true,
type: 'string',
rename: 'phoneNumber'
}
}
}
}
const data = {
name: 'John',
age: 30,
city: 'New York',
phone: [
{type: 'home', number: '123-456-7890'},
{type: 'work', number: '098-765-4321'}
]
}
const result = mapper.map(data, schema)
// {
// label: 'John',
// city: 'New York',
// phoneList: [
// { phoneType: 'home', phoneNumber: '123-456-7890' },
// { phoneType: 'work', phoneNumber: '098-765-4321' }
// ]
// }Edge Cases
The mapper handles various edge cases gracefully:
- Null/Undefined Input: Returns the input as-is
- Empty String Input: Returns the input as-is
- Non-Object Input: Returns the input as-is (strings, numbers, booleans)
- Non-Object Array: Returns the array as-is
- Empty Array: Returns empty array
- Null Field Values: Uses default value if provided, otherwise keeps null
- Undefined Field Values: Uses default value if provided
- Empty String Field Values: Uses default value if provided
Type Mismatch Handling
When a field value doesn't match the configured type, the mapper will:
- Return the original value: Ignore the schema configuration and return the original value as-is
- Print a warning: Output a warning message indicating the type mismatch
Warning Format: [bandeng-mapper] 字段 "fieldName": 类型不匹配: 期望 expectedType,实际为 actualType,将返回原始值
Field Name in Warning: The warning uses the renamed field name (if rename is configured), otherwise uses the original field name.
Type Conversion Rules:
stringtype: Can convert numbers, booleans, etc., so no warning is printedarraytype: Must be an array, cannot convert from other types
Example:
const mapper = new Mapper()
const schema = {
phone: {
required: true,
type: 'array',
rename: 'phoneList'
}
}
const data = {
phone: 123 // Number instead of array
}
const result = mapper.map(data, schema)
// Warning: [bandeng-mapper] 字段 "phoneList": 类型不匹配: 期望 array,实际为 number,将返回原始值
// Result: { phoneList: 123 }Unprocessable Values
When encountering values that cannot be processed (functions, Symbols, Date objects, RegExp, Error, Map, Set, etc.), the mapper will return a type description string instead:
- Functions →
[Function] - Symbols →
[Symbol] - Date objects →
[Date] - RegExp →
[RegExp] - Error objects →
[Error] - Map →
[Map] - Set →
[Set] - Other special objects →
[ConstructorName]
Example:
const mapper = new Mapper()
const schema = {
fn: 1,
date: 1,
sym: 1
}
const data = {
fn: function () {},
date: new Date(),
sym: Symbol('test')
}
const result = mapper.map(data, schema)
// {
// fn: '[Function]',
// date: '[Date]',
// sym: '[Symbol]'
// }Schema Validation
The mapper validates schema configurations and throws descriptive errors for:
- Invalid
fieldCasevalues - Invalid schema types (must be object, 0, or 1)
- Invalid
requiredvalues (must be boolean) - Invalid
typevalues (must be string or null) - Invalid
renamevalues (must be string or null) - Invalid
itemsvalues (must be object, not array)
Creating and Validating Schema: Use mapper.schema() to create and validate a schema configuration:
const mapper = new Mapper()
// Create and validate schema in one step
const userSchema = mapper.schema({
name: {required: true, type: 'string', rename: 'label'},
age: 1,
phone: {
required: true,
type: 'array',
rename: 'phoneList',
items: {
type: 1,
number: 1
}
}
})
// If schema is invalid, an error will be thrown immediately
// Important: mapper.schema() returns a plain JavaScript object
// It's just a validated configuration object, not a special schema instance
console.log(typeof userSchema) // 'object'
console.log(userSchema instanceof Object) // true
// Now safe to use
const result = mapper.map(data, userSchema)Important Note: mapper.schema() returns a plain JavaScript object. It's not a special schema class or instance - it's just the same configuration object you passed in, but validated. This design is intentional and allows you to:
- Use the schema object like any regular JavaScript object
- Store it, pass it around, or modify it if needed
- Use it directly with
map()without any special handling
This allows you to catch schema configuration errors at creation time, rather than discovering them only when map() is called.
API Reference
new Mapper(config)
Creates a new Mapper instance.
Parameters:
config(Object, optional): Configuration objectfieldCase(String, optional): Field name transformation mode ('camel','snake', or'none'). Default:'none'
Returns: Mapper instance
Throws: Error if config is invalid
mapper.schema(schemaConfig)
Creates and validates a schema configuration. This method validates the schema immediately and throws an error if the configuration is invalid.
Parameters:
schemaConfig(Object): Schema configuration object
Returns: The validated schema configuration object (a plain JavaScript object)
Throws: Error if schema configuration is invalid
Important: The returned value is a plain JavaScript object, not a special schema instance. You can use it like any regular object - store it, pass it around, or modify it if needed.
Example:
const mapper = new Mapper()
// Create and validate schema
const schema = mapper.schema({
name: {required: true, type: 'string'},
age: {required: true, type: 'string'}
})
// schema is a plain object
console.log(typeof schema) // 'object'
console.log(schema instanceof Object) // true
// Schema is validated, safe to use
const result = mapper.map(data, schema)mapper.map(data, schema, overrideSchema)
Maps data according to the schema configuration.
Parameters:
data(Object|Array|Any): Data to mapschema(Object): Schema configurationoverrideSchema(Object, optional): Optional override configuration that partially overrides fields in the base schema. Only fields that exist in the base schema will be overridden.
Returns: Mapped data (Object|Array|Any)
Throws: Error if schema is invalid
Note: The schema is automatically validated when map() is called. To validate a schema at creation time, use schema().
Schema Override: The third parameter overrideSchema allows you to partially override the base schema at mapping time. Only fields that exist in the base schema will be overridden; fields that don't exist in the base schema will be ignored.
Example:
const mapper = new Mapper()
// Base schema
const baseSchema = {
name: {required: true, type: 'string', rename: 'label'},
age: 1,
phone: {
required: true,
type: 'array',
rename: 'phoneList',
items: {type: 1, number: 1}
}
}
// Override schema - only overrides existing fields
const overrideSchema = {
name: {required: true, type: 'string', rename: 'fullName'}, // Override rename
phone: {
required: true,
type: 'array',
rename: 'contacts', // Override rename
items: {type: 1} // Override items (number field removed)
}
// age field not in override, so it keeps the base configuration (age: 1)
}
const data = {
name: 'John',
age: 30,
phone: [{type: 'home', number: '123'}]
}
// Use override schema
const result = mapper.map(data, baseSchema, overrideSchema)
// {
// fullName: 'John', // rename overridden
// age: 30, // base configuration kept
// contacts: [ // rename overridden
// {type: 'home'} // items overridden (number removed)
// ]
// }Testing
Run tests with:
npm testLicense
ISC
中文
概述
bandeng-mapper 是一个功能强大且灵活的数据映射库,适用于 Node.js 环境。支持基于 schema 配置来转换 JSON 数据结构。该库提供了声明式的方式来映射、转换和验证数据,支持字段重命名、类型转换、默认值、嵌套对象和数组等功能。
特性
- 简单配置:使用
0排除字段或1包含字段 - 对象配置:通过
required、type、rename、default和items选项进行细粒度控制 - 字段名转换:自动在驼峰命名和下划线命名之间转换
- 类型转换:将值转换为
string或array类型 - 字段重命名:在映射过程中重命名字段
- 默认值:为空字段提供后备值
- 数组处理:支持数组输入、数组字段和嵌套数组
- 深层嵌套:处理深层嵌套的对象和数组
- 输入验证:全面的 schema 验证,提供清晰的错误信息
- 边界情况处理:优雅处理 null、undefined、空字符串和非对象输入
安装
npm install bandeng-mapper快速开始
const Mapper = require('bandeng-mapper')
// 创建映射器实例
const mapper = new Mapper()
// 定义 schema
const schema = {
name: 1, // 简单配置:包含字段
age: 0, // 简单配置:排除字段
email: {
// 对象配置:详细配置
required: true,
type: 'string',
rename: 'emailAddress'
}
}
// 映射数据
const data = {
name: 'John',
age: 30,
email: '[email protected]'
}
const result = mapper.map(data, schema)
// 结果: { name: 'John', emailAddress: '[email protected]' }配置选项
构造函数选项
const mapper = new Mapper({
fieldCase: 'camel' // 'camel' | 'snake' | 'none' (默认: 'none')
})- fieldCase:控制自动字段名转换
'camel':将下划线命名转换为驼峰命名(例如:user_name→userName)'snake':将驼峰命名转换为下划线命名(例如:userName→user_name)'none':不进行转换(默认值)
Schema 配置
简单配置
0:从输出中排除该字段1:按原样包含该字段
简单配置可以在任何嵌套层级使用:
const schema = {
name: 1, // 包含
age: 0, // 排除
address: {
street: 1,
zip: 0 // 简单配置在嵌套对象中同样有效
}
}对象配置
{
required: boolean, // false: 排除, true: 包含 (默认: true)
type: string, // 'string' | 'array' | null
rename: string, // 新字段名(或 null 保持原名)
default: any, // 默认值(null/undefined 不会被使用)
items: object // 数组项或嵌套对象的 schema
}使用示例
基本字段映射
const mapper = new Mapper()
const schema = {
name: 1,
age: 0,
email: {required: true}
}
const data = {name: 'John', age: 30, email: '[email protected]'}
const result = mapper.map(data, schema)
// { name: 'John', email: '[email protected]' }字段重命名
const schema = {
name: {required: true, rename: 'fullName'},
age: {required: true, rename: 'userAge'}
}
const data = {name: 'John', age: 30}
const result = mapper.map(data, schema)
// { fullName: 'John', userAge: 30 }类型转换
const schema = {
age: {required: true, type: 'string'},
tags: {required: true, type: 'array', default: []}
}
const data = {age: 30, tags: ['developer', 'nodejs']}
const result = mapper.map(data, schema)
// { age: '30', tags: ['developer', 'nodejs'] }默认值
const schema = {
name: {required: true, default: 'Unknown'},
age: {required: true, default: 0},
tags: {required: true, type: 'array', default: []}
}
const data = {}
const result = mapper.map(data, schema)
// { name: 'Unknown', age: 0, tags: [] }注意:默认值仅在字段值为 null、undefined 或空字符串('')时使用。如果 default 显式设置为 null,则不会被使用。
字段名转换
// 驼峰命名转换
const mapper = new Mapper({fieldCase: 'camel'})
const schema = {user_name: 1, user_age: 1}
const data = {user_name: 'John', user_age: 30}
const result = mapper.map(data, schema)
// { userName: 'John', userAge: 30 }
// 下划线命名转换
const mapper2 = new Mapper({fieldCase: 'snake'})
const schema2 = {userName: 1, userAge: 1}
const data2 = {userName: 'John', userAge: 30}
const result2 = mapper2.map(data2, schema2)
// { user_name: 'John', user_age: 30 }数组处理
// 数组输入
const schema = {name: 1, age: 1}
const data = [
{name: 'John', age: 30},
{name: 'Jane', age: 25}
]
const result = mapper.map(data, schema)
// [
// { name: 'John', age: 30 },
// { name: 'Jane', age: 25 }
// ]
// 带 items 配置的数组字段
const schema2 = {
users: {
required: true,
type: 'array',
items: {
name: {required: true, rename: 'fullName'},
age: {required: true, type: 'string'}
}
}
}
const data2 = {
users: [
{name: 'John', age: 30},
{name: 'Jane', age: 25}
]
}
const result2 = mapper.map(data2, schema2)
// {
// users: [
// { fullName: 'John', age: '30' },
// { fullName: 'Jane', age: '25' }
// ]
// }Schema 覆盖
您可以在映射时使用第三个参数部分覆盖 schema 配置:
const mapper = new Mapper()
// 基础 schema
const baseSchema = {
name: {required: true, type: 'string', rename: 'label'},
age: 1,
city: 1
}
// 覆盖 schema - 只覆盖已存在的字段
const overrideSchema = {
name: {required: true, type: 'string', rename: 'fullName'}
// age 和 city 不在覆盖配置中,所以保持基础配置
}
const data = {name: 'John', age: 30, city: 'NY'}
// 使用覆盖 schema
const result = mapper.map(data, baseSchema, overrideSchema)
// {
// fullName: 'John', // rename 被覆盖
// age: 30, // 保持基础配置
// city: 'NY' // 保持基础配置
// }嵌套对象
在嵌套对象中可以直接使用简单配置(0 和 1),也可以使用 items 进行更复杂的配置:
// 在嵌套对象中直接使用简单配置
const schema = {
address: {
addressInfo: {
address: 1,
city: 1,
state: 1,
zip: 0 // 排除 zip 字段
}
}
}
const data = {
address: {
addressInfo: {
address: '123 Main St',
city: 'New York',
state: 'NY',
zip: '10001' // 将被排除
}
}
}
const result = mapper.map(data, schema)
// {
// address: {
// addressInfo: {
// address: '123 Main St',
// city: 'New York',
// state: 'NY'
// }
// }
// }// 使用 items 配置嵌套对象
const schema = {
user: {
required: true,
items: {
profile: {
required: true,
items: {
name: 1,
email: {required: true, rename: 'emailAddress'}
}
}
}
}
}
const data = {
user: {
profile: {
name: 'John',
email: '[email protected]',
age: 30 // 将被排除
}
}
}
const result = mapper.map(data, schema)
// {
// user: {
// profile: {
// name: 'John',
// emailAddress: '[email protected]'
// }
// }
// }复杂示例
const mapper = new Mapper({fieldCase: 'camel'})
const schema = {
name: {
required: true,
type: 'string',
default: '',
rename: 'label'
},
age: 0, // 排除
city: 1, // 按原样包含
phone: {
required: true,
type: 'array',
default: [],
rename: 'phoneList',
items: {
type: {
required: true,
type: 'string',
rename: 'phoneType'
},
number: {
required: true,
type: 'string',
rename: 'phoneNumber'
}
}
}
}
const data = {
name: 'John',
age: 30,
city: 'New York',
phone: [
{type: 'home', number: '123-456-7890'},
{type: 'work', number: '098-765-4321'}
]
}
const result = mapper.map(data, schema)
// {
// label: 'John',
// city: 'New York',
// phoneList: [
// { phoneType: 'home', phoneNumber: '123-456-7890' },
// { phoneType: 'work', phoneNumber: '098-765-4321' }
// ]
// }边界情况
映射器优雅地处理各种边界情况:
- Null/Undefined 输入:按原样返回输入
- 空字符串输入:按原样返回输入
- 非对象输入:按原样返回输入(字符串、数字、布尔值)
- 非对象数组:按原样返回数组
- 空数组:返回空数组
- Null 字段值:如果提供了默认值则使用,否则保持 null
- Undefined 字段值:如果提供了默认值则使用
- 空字符串字段值:如果提供了默认值则使用
类型不匹配处理
当字段值与配置的 type 不匹配时,映射器会:
- 返回原始值:忽略 schema 配置,直接返回原始值
- 打印警告信息:输出警告信息,提示类型不匹配
警告格式:[bandeng-mapper] 字段 "字段名": 类型不匹配: 期望 expectedType,实际为 actualType,将返回原始值
警告中的字段名:警告信息使用重命名的字段名(如果配置了 rename),否则使用原始字段名。
类型转换规则:
string类型:可以转换数字、布尔值等,因此不会打印警告array类型:必须是数组,无法从其他类型转换
示例:
const mapper = new Mapper()
const schema = {
phone: {
required: true,
type: 'array',
rename: 'phoneList'
}
}
const data = {
phone: 123 // 数字而不是数组
}
const result = mapper.map(data, schema)
// 警告: [bandeng-mapper] 字段 "phoneList": 类型不匹配: 期望 array,实际为 number,将返回原始值
// 结果: { phoneList: 123 }无法处理的值
当遇到无法处理的值(函数、Symbol、Date 对象、RegExp、Error、Map、Set 等)时,映射器会返回类型描述字符串:
- 函数 →
[Function] - Symbol →
[Symbol] - Date 对象 →
[Date] - RegExp →
[RegExp] - Error 对象 →
[Error] - Map →
[Map] - Set →
[Set] - 其他特殊对象 →
[构造函数名]
示例:
const mapper = new Mapper()
const schema = {
fn: 1,
date: 1,
sym: 1
}
const data = {
fn: function () {},
date: new Date(),
sym: Symbol('test')
}
const result = mapper.map(data, schema)
// {
// fn: '[Function]',
// date: '[Date]',
// sym: '[Symbol]'
// }Schema 验证
映射器会验证 schema 配置,并在以下情况抛出描述性错误:
- 无效的
fieldCase值 - 无效的 schema 类型(必须是对象、0 或 1)
- 无效的
required值(必须是布尔值) - 无效的
type值(必须是字符串或 null) - 无效的
rename值(必须是字符串或 null) - 无效的
items值(必须是对象,不能是数组)
创建和验证 Schema:使用 mapper.schema() 方法来创建和验证 schema 配置:
const mapper = new Mapper()
// 一步创建并验证 schema
const userSchema = mapper.schema({
name: {required: true, type: 'string', rename: 'label'},
age: 1,
phone: {
required: true,
type: 'array',
rename: 'phoneList',
items: {
type: 1,
number: 1
}
}
})
// 如果 schema 无效,会立即抛出错误
// 重要说明:mapper.schema() 返回的是一个普通的 JavaScript 对象
// 它只是一个经过验证的配置对象,不是特殊的 schema 实例
console.log(typeof userSchema) // 'object'
console.log(userSchema instanceof Object) // true
// 现在可以安全使用
const result = mapper.map(data, userSchema)重要提示:mapper.schema() 返回的是一个普通的 JavaScript 对象。它不是特殊的 schema 类或实例,只是您传入的同一个配置对象,但经过了验证。这个设计是有意为之的,允许您:
- 像使用任何普通 JavaScript 对象一样使用 schema 对象
- 存储它、传递它,或在需要时修改它
- 直接与
map()一起使用,无需特殊处理
这样可以在创建时捕获 schema 配置错误,而不是等到调用 map() 时才发现。
API 参考
new Mapper(config)
创建一个新的 Mapper 实例。
参数:
config(Object, 可选):配置对象fieldCase(String, 可选):字段名转换模式('camel'、'snake'或'none')。默认值:'none'
返回: Mapper 实例
抛出: 如果配置无效则抛出错误
mapper.schema(schemaConfig)
创建并验证 schema 配置。该方法会立即验证 schema,如果配置无效则抛出错误。
参数:
schemaConfig(Object):Schema 配置对象
返回: 验证后的 schema 配置对象(一个普通的 JavaScript 对象)
抛出: 如果 schema 配置无效则抛出错误
重要提示:返回值是一个普通的 JavaScript 对象,不是特殊的 schema 实例。您可以像使用任何普通对象一样使用它 - 存储它、传递它,或在需要时修改它。
示例:
const mapper = new Mapper()
// 创建并验证 schema
const schema = mapper.schema({
name: {required: true, type: 'string'},
age: {required: true, type: 'string'}
})
// schema 是一个普通对象
console.log(typeof schema) // 'object'
console.log(schema instanceof Object) // true
// Schema 已验证,可以安全使用
const result = mapper.map(data, schema)mapper.map(data, schema, overrideSchema)
根据 schema 配置映射数据。
参数:
data(Object|Array|Any):要映射的数据schema(Object):Schema 配置overrideSchema(Object, 可选):可选的覆盖配置,用于部分覆盖基础 schema 中的字段。只有基础 schema 中存在的字段才会被覆盖。
返回: 映射后的数据(Object|Array|Any)
抛出: 如果 schema 无效则抛出错误
注意:调用 map() 时会自动验证 schema。如果要在创建时验证 schema,请使用 schema()。
Schema 覆盖:第三个参数 overrideSchema 允许您在映射时部分覆盖基础 schema。只有基础 schema 中存在的字段才会被覆盖;基础 schema 中不存在的字段将被忽略。
示例:
const mapper = new Mapper()
// 基础 schema
const baseSchema = {
name: {required: true, type: 'string', rename: 'label'},
age: 1,
phone: {
required: true,
type: 'array',
rename: 'phoneList',
items: {type: 1, number: 1}
}
}
// 覆盖 schema - 只覆盖已存在的字段
const overrideSchema = {
name: {required: true, type: 'string', rename: 'fullName'}, // 覆盖 rename
phone: {
required: true,
type: 'array',
rename: 'contacts', // 覆盖 rename
items: {type: 1} // 覆盖 items(number 字段被移除)
}
// age 字段不在覆盖配置中,所以保持基础配置 (age: 1)
}
const data = {
name: 'John',
age: 30,
phone: [{type: 'home', number: '123'}]
}
// 使用覆盖 schema
const result = mapper.map(data, baseSchema, overrideSchema)
// {
// fullName: 'John', // rename 被覆盖
// age: 30, // 保持基础配置
// contacts: [ // rename 被覆盖
// {type: 'home'} // items 被覆盖(number 被移除)
// ]
// }测试
运行测试:
npm test许可证
ISC
