cast-wth-schema

1.0.0 • Public • Published

cast-with-schema

NPM version

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

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.

Package Sidebar

Install

npm i cast-wth-schema

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

6.94 kB

Total Files

5

Last publish

Collaborators

  • ajaxy