npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ko-jsonschema

v0.0.4

Published

json schema generator

Downloads

7

Readme

knockout-jsonSchema

knockout-jsonSchema is a Knockout.js plugin designed to generate a JSON schema according to json-schema.org specifications. The generated JSON schema describes the valid JSON data for a given knockout view model including the data restrictions which were defined using the Knockout-Validation library.

This allows you to easely generate a schema that can be used to validate your JSON data on the server side (using the technology of your pick), while keeping your model definitions and restirctions automatically in sync on both client and server.

Basic Usage

knockout-jsonSchema creates a ko.jsonSchema object. To create a JSON schema simply use the generateSchema method. The methods gets the knockout view model as the first parameter and an optional settings object as the second.

generrate - ko.jsonSchema.generate(viewModel, [settings])

var viewModel = {
    person: {
        name: ko.observable("foo"),
        age: ko.observable(30)
    },
    discountEligibility: ko.observable(true)
};

ko.jsonSchema.generate(viewModel);

This opertaion will produce the following JSON schema:

     {
        "title": "",
        "$schema": "http://json-schema.org/draft-04/schema#",
        "type": "object",
        "properties": {
            "person": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string"
                    },
                  "age": {
                      "type": "string"
                  }
                },
              "additionalProperties": false
            },
          "discountEligibility": {
              "type": "string"
          }
        },
        "additionalProperties": false
    }

The basic knockout-validation definitions are supported so the validations on your view model will be reflected in the JSON schema.

   var viewModel = {
	   firstName: ko.observable("foo").extend({
					required: true,
					minLength: 3,
					pattern: {
						message: "Hey this doesnt match my pattern",
						params: "^[a-zA-Z]+$"
					}
			 })
   };

   ko.jsonSchema.generate(viewModel);

Now the firstName property in the schema has the restirctions defined by the knockout validation exetnders:

	{
  "title": "",
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "firstName": {
      "minLength": 3,
      "pattern": "^[a-zA-Z]+$",
      "type": [
        "string",
        "null"
      ]
    }
  },
  "additionalProperties": false,
  "required": [
    "firstName"
  ]
}

The generate method gets as its second parameter a set of key/value pairs that configure the schema generation: ignore - an array with properties names that shouldn't be represented in the schema. additionalProperties - defines weather properties that are not listed in the schema will be allowed when the schema is validated (the defeult is false). additionalProperties can also be defined specifically on each object within the view model. title - the title of the schema (metadata that isn't used for validation).

The following command will generate a schema that excludes the firstName and lastName properties, allows additional properties and has "sample schema" as its title:

   ko.jsonSchema.generate(viewModel,{ignore:['lastName','firstName'], additionalProperties: true, title: "sample schema"});

Extending the Generator

The plugin is extensible. For example, say that for boolean types you want the schema to allow not only boolean values but also their string representation. This can be acheived by adding your own generator:

ko.jsonSchema.registerGenerator("booleanType", {
                condition: function (property) { return typeof property === "boolean"; },
                generate: function (property) {
                    return {
                        "anyOf": [
                          {
                              "type": "boolean"
                          },
                          {
                              "type": "string",
                              "enum": ["true","false"]
                          }
                        ]
                    };
                }
            });

Server Side Validation

In order to validate the JSON data on the server, you first have to export your view model, npm install ko-jsonschema and create the JSON schema. Then, you can validate the json data against the schema with any software that supports version 4 of the json schema specification.

Following is an example using is-my-json-valid assuming you have exported a view model that contains a single required firstName property in src/viewModel.js:

var viewModel = require("./src/viewModel.js")
var jsonSchema = require("ko-jsonSchema")
var schema = jsonSchema.generate(viewModel)

var validator = require('is-my-json-valid')

var validate = validator(jsonSchema.generate(viewModel))

console.log('should be valid', validate({firstName: 'John'}))
console.log('should not be valid', validate({hello: 'world'}))
console.log(validate.errors)

To be sure, the view model in src/viewModel.js is defined as follows:

(function (factory) {
  "use strict";
  //CommonJS
  if (typeof exports === "object" && typeof module === "object") {
          require("knockout.validation");
          module.exports = factory(require("knockout"));
  //AMD
  } else if (typeof define === "function" && define.amd) {
      define(["knockout","knockout.validation"], factory);
  //normal script tag
  } else {
    window.viewModel = factory(ko);
  }
}(function (ko) {
                  return {
                         firstName: ko.observable("foo1").extend({
                                      required: true,
                                      minLength: 3,
                                      pattern: {
                                          message: "Hey this doesnt match my pattern",
                                          params: "^[a-zA-Z]+$"
                                      }
                               })
                  };
}
));

Dependencies

  • knockout 2.0+

Build

This project uses grunt for building/minifying.

Install from NPM

npm install ko-jsonschema --save

License

MIT http://www.opensource.org/licenses/mit-license.php