Socket
Book a DemoInstallSign in
Socket

cast-with-schema

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cast-with-schema

Casting JS objects to correct types using JSON schemas

latest
Source
npmnpm
Version
1.5.0
Version published
Weekly downloads
3.5K
-0.9%
Maintainers
1
Weekly downloads
 
Created
Source

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.

Keywords

types

FAQs

Package last updated on 08 Jul 2021

Did you know?

Socket

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.

Install

Related posts