Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

cast-with-schema

Ajaxy2.3kMIT1.5.0

Casting JS objects to correct types using JSON schemas

types, casting, json, schema, api, rest, openapi, swagger, specification, documentation

readme

cast-with-schema

NPM version

The way to cast data to types specified with JSON schema.

Arguments

  • source (object) - Source object to be casted.
  • schema (object) - JSON schema containing types definitions.
  • options (object)
    • allowNaN — Whether or not to return NaN for non-parseable numbers. The default is false which will cast NaN to 0.

Example

May be used for query params casting:

const qs = require('qs');
const castWithSchema = require('cast-with-schema');

const schema = {
  type: "object",
  properties: {
    param1: {
      type: 'string',
    },
    param2: {
      type: 'integer',
    },
    param3: {
      type: 'number',
    },
    param4: {
      type: 'boolean',
    },
  }
};

const query = 'param1=value&param2=777&param3=7.77&param4=false';
const parsed = qs.parse(query);
const casted = castWithSchema(query, schema);

/*
  `casted` is now:
  {
    param1: 'value',
    param2: 777,
    param3: 7.77,
    param4: false,
  }
*/

Supports null if schema is either:

type: ['..', 'null']

or

anyOf: [
  { type: '..' },
  { type: 'null' }
]

See also

Check out tinsypec for more smart JSON schema use cases.

changelog

Change Log

v1.4.0 (2019/08/14 10:36 +00:00)

  • f86c0a4 1.4.0 (@Ajaxy)
  • 11ec409 Fixes for booleans; Cast to strings; Empty string casts to false (@Ajaxy)

v1.3.2 (2019/06/05 20:28 +00:00)

  • 22a0fa5 1.3.2 (@Ajaxy)
  • b89e191 Bump handlebars from 4.0.11 to 4.1.2 (@dependabot[bot])

v1.3.1 (2019/06/05 20:24 +00:00)

  • 4246673 1.3.1 (@Ajaxy)
  • b3080bd Bump js-yaml from 3.12.0 to 3.13.1 (@dependabot[bot])
  • c6efab0 Add CHANGELOG (@Ajaxy)

v1.3.0 (2019/01/17 10:55 +00:00)

  • 53e9740 1.3.0 (@Ajaxy)
  • cfb2540 Add support for options.allowNaN (@Ajaxy)

v1.2.1 (2018/09/11 14:21 +00:00)

  • b0b460a 1.2.1 (@Ajaxy)
  • 700a36f Fix for objects and arrays with null allowed using anyOf (@Ajaxy)

v1.2.0 (2018/08/30 16:00 +00:00)

  • 39e7028 1.2.0 (@Ajaxy)
  • b685d1a Parse flots with parseFloat; Return 0 instead of NaN (@Ajaxy)

v1.1.0 (2018/08/30 15:13 +00:00)