1.0.0 • Published 2 years ago

@asanrom/javascript-object-sanitizer v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Javascript Object Sanitizer

npm version

Object sanitizer for javascript and typescript.

Forces the input to follow a pre-defined schema. Useful to check application/json bodies in web requests and responses from untrusted APIs.

Installation

If you are using a npm managed project use:

npm install @asanrom/javascript-object-sanitizer

If you are using it in the browser, download the minified file from the Releases section and import it to your html:

<script type="text/javascript" src="/path/to/javascript-object-sanitizer.js"></script>

Usage

Node:

import { ObjectSchema } from '@asanrom/javascript-object-sanitizer';

// With require: const ObjectSchema = require('@asanrom/javascript-object-sanitizer').ObjectSchema;

// Example schema or complex object
const schema = ObjectSchema.object({
    stringProperty: ObjectSchema.string().withDefaultValue(""),
    integerProperty: ObjectSchema.integer(),
    positiveNumber: ObjectSchema.number().withMin(0),
    array: ObjectSchema.array(ObjectSchema.object({
        arrayItemProp1: ObjectSchema.boolean(),
    })),
    optionalProperty: ObjectSchema.optional(ObjectSchema.number()),
});

// Test user input
schema.test(userInput); // Returns true or false

// Sanitize
const sanitized = schema.sanitize(userInput); // Forces user input to follow the schema

Browser:

window.ObjectSchema = ObjectSanitizer.ObjectSchema;

// Example schema or complex object
const schema = ObjectSchema.object({
    stringProperty: ObjectSchema.string().withDefaultValue(""),
    integerProperty: ObjectSchema.integer(),
    positiveNumber: ObjectSchema.number().withMin(0),
    array: ObjectSchema.array(ObjectSchema.object({
        arrayItemProp1: ObjectSchema.boolean(),
    })),
    optionalProperty: ObjectSchema.optional(ObjectSchema.number()),
});

// Test user input
schema.test(userInput); // Returns true or false

// Sanitize
const sanitized = schema.sanitize(userInput); // Forces user input to follow the schema

Documentation

1.0.0

2 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago