
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
data-exchange
Advanced tools
The main purpose of the library is to process data from transport format (e.g. simple object parsed from JSON) to typed JavaScript or TypeScript object and back.
Schemas are container for fields. There are two schema definition approach you can use.
AbstractSchema class (legacy)Base building block is schema with fields. There are two ways to define fields:
fields property of the AbstractSchema classcreateFields() methodThe first way is suitable for most cases of use. The second one can be used to define more complex schema with custom cross field validators and/or some custom special logic in schema definition.
From version 2.3 you can use the declarative approach to define your schemas.
Create object extending the DeclarativeSchema class and defined fields as its properties:
class MyDeclarativeSchema extends DeclarativeSchema {
id = new Int({required: true});
name = new Str({required: true});
description = new Str({required: true, nullable: false});
}
class MyOtherSchema extends MyDeclarativeSchema {
ownerName = new Str({required: true, remoteName: "owner_name"})
}
The declarative schema is recommended because it is more intuitive and it can be easily extended by inheritance.
A field names are resolved by following algorithm:
name attribute is null, set it to property name (the name attribute can be set by explicit assign in constructor attr = new Str("some_explicit_name", {...}))remoteName attribute is null, set it to property namelocalName attribute is null, set it to property nameThere are few types of fields delivered with the library.
Str - stringsNumeric - all numeric valuesInt - integer subset of numeric values (if value is float, it is rouned)Bool - logic valueDate_ - only date (field class has underscore suffix to avoid name conflict with JS built-on Date type)Time - only timeDateTime - both date and timeNested - nested schemaList - list of items with same type.Dict - key value pairs stored in simple object.Map_ - key value pairs stored in the Map object.Common fields constructor interface is
2.3)Nested)Settings values common for all built-in fields are:
required: boolean - true if value cannot be undefinednullable: boolean - true if value can be nulldefaultValue: unknown - default value if value is undefinedlocalName: string - name of attribute in local object (default is name)remoteName: string - name of attribute in remote object (default is name)dumpOnly: boolean - if true, field will not be loadedloadOnly: boolean - if true, field will not be dumpedfilters: FilterSettings|FilterInterface[] - list of filtersvalidators: ValidatorSettings|ValidatorInterface[] - list of validatorsskipIfUndefined: boolean|SkipIfUndefinedSettings - if true (default) a property will not be included in a result
object if the value should be undefinedFor Date like fields:
formatter - instance of the date formatter (default is IsoFormatter with UTC as default timezone)At this time, only ISO format is supported (the IsoFormatter class).
Configuration object of the IsoFormatter has the following structure:
defaultTimeZone?: string|null - time zone used for parsing when an input data has no timezone set. Default is Z
(e.g. 2021-02-03T12:31:01 -> 2021-02-03T12:31:01Z).Fields support validation and filtration of values. There is no validators or filters delivered with the library but
custom validators and filters can be written by implementing ValidatorInterface and FilterInterface.
Order of the operations is:
parseDate(inp: string): Date - parse date from stringparseTime(inp: string): Date - parse time from stringparseDateTime(inp: string): Date - parse date and time from stringformatDate(date: Date): string - format date as stringformatTime(date: Date): string - format time as stringformatDateTime(date: Date): string - format date and time as stringvalidate(val: any, context?: any, result?: any, schema?: SchemaInterface) -> boolean - return true if value is
valid, return false otherwisegetLastErrors() -> ErrorReportInterface[] - get errors of the last validationfilter(val: any) -> any - apply filtration to the val and return resultwhenLoad: boolean - apply skipIfUndefined settings to load() methodwhenDump: boolean - apply skipIfUndefined settings to dump() methodinFilters: FilterInterface[] - filters applied in load() methodoutFilters: FilterInterface[] - filters applied in dump() methodinValidators: FilterInterface[] - validators applied in load() methodoutValidators: FilterInterface[] - validators applied in dump() methodSample schema definition
import { DeclarativeSchema, Int, Str, Date_, Nested, List } from "data-exchange"
class Ban
{
reason: string;
banned_at: Date;
}
class BanSchema extends DeclarativeSchema<Ban>
{
reason = new Str({required: true});
banne_at = new Date_({required: true});
createObject(): Ban
{
return new Ban();
}
}
class UserSchema extends DeclarativeSchema
{
id = new Int({loadOnly: true, remoteName: "id_user", required: true});
name = new Str({required: true}) // field cannot be undefined or NULL
created_at = new DateTime({required: true, nullable: false}) // field cannot be undefined, but NULL is OK
favorite_numbers = new List(new Int(null, {required: true})) // list of integers
allowed_actions = new Dict(new Str(null, {required: true}), new Bool(null, {required: true})) // the key is string and value is boolean
some_mappoing = new Map_(new Date_(null, {required: true}), new Str(null, {required: true, nullable: true})) // the key is Date object and value is string
last_ban = new Nested(new BanSchema(), {required: true, nullable: false})
}
let data = {
id_user: 1,
name: "Karel Novak",
created_at: "2019-09-03T07:01:30.073Z",
favorite_numbers: [1, 13, 69],
allowed_actions: {"action_1": true, "action_2": false},
some_mapping: {"2021-09-09": "foo", "2021-09-10": "bar"},
last_ban: {
reason: "multiple accounts",
bannted_at: "2019-09-03T07:01:30.073Z"
}
}
let schema = new UserSchema();
let item = schema.load(data);
let dumpedData = schema.dump(item);
For more information see docstrings in code or examples in "sample" directory.
The load method has the second optional argument. It is target object where data is load into. If no
object is given, new empty object (by createObject() call) is created.
FAQs
Data loading and dumping library
We found that data-exchange demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.