A JSON Schema Validator for JavaScript and TypeScript

Tiny Schema Validator

JSON schema validator with excellent type inference for JavaScript and TypeScript.

Installation

npm install tiny-schema-validator
# or
yarn add tiny-schema-validator

Usage

Creating a schema

import { createSchema, _ } from 'tiny-schema-validator';

export const User = createSchema({
  metadata: _.record({
    date_created: _.number(),
    id: _.string(),
  }),
  profile: _.record({
    name: _.string({
      maxLength: [100, 'too-long'],
      minLength: [2, 'too-short'],
    }),
    age: _.number({
      max: [150, 'too-old'],
      min: [13, 'too-young'],
    }),
    email: _.string({
      pattern: [/^[^@]+@[^@]+\.[^@]+$/, 'invalid-email'],
    }),
  }),
  payment_status: _.union(
    _.constant('pending'),
    _.constant('failed'),
    _.constant('success'),
    _.constant('canceled')
  ),
});

and in TypeScript, everything is the same, but to get the data type inferred from the schema, you can do this:

/*
  UserType {
    metadata: {
      date_created: number;
      id: string;
    };
    profile: {
      name: string;
      age: number;
      email: string;
    };
    payment_status: 'pending' | 'failed' | 'success' | 'canceled';
  }
*/
export type UserType = ReturnType<typeof User.produce>;

Using the schema

When you create a schema, you will get a nice API to handle multiple use-cases in the client and the server.

  • is(data: any): boolean check if the data is valid (eager evaluation)
  • validate(data: any): Errors errors returned has the same shape as the schema you defined (does not throw)
  • produce(data: any): data throws an error when the data is invalid. otherwise, it returns data
  • embed(config?: { optional: boolean }) embeds the schema in other schemas
  • source the schema itself in a parsable format

example usage:

const Person = createSchema({
  name: _.string(),
  age: _.number(),
  email: _.string(),
});

const john = { name: 'john', age: 42, email: 'john@gmail.com' };
Person.is({}); // false
Person.is(john); // true

Person.validate({}); // { name: 'invalid-type', age: 'invalid-type', email: 'invalid-type' }
Person.validate(john); // null

try {
  Person.produce(undefined);
} catch (e) {
  console.log(e instanceof TypeError); // true
  console.log(e.message); // "invalid-data"
}

// embedding the person schema
const GroupOfPeople = createSchema({
  // ...
  people: _.listof(Person.embed()),
  // ...
});

Validators

All validators are required by default. All validators are accessible with the _ (underscore) namespace; The reason for using _ instead of a good name like validators is developer experience, and you can alias it to whatever you want.

import { _ as validators } from 'tiny-schema-validator';

// NOTE: when you call a validator you just create an object with { type: '<type of validator>', ...options }
// this is just a shorthand for that.

// example of all validators and corresponding Typescript types
validators.string(); // string
validators.number(); // number
validators.boolean(); // boolean
validators.constant(42); // 42
validators.union(validators.constant(1), validators.constant(2), validators.constant(3)); // 1 | 2 | 3
validators.list([validators.number(), validators.number()]); // [number, number]
validators.listof(validators.string()); // string[]
validators.recordof(validators.string()); // Record<string, string>
validators.record({
  timestamp: validators.number(),
  id: validators.string(),
}); // { timestamp: number; id: string; }

Check out the full validators API below:

validatorsignatureprops
   
constantconstant(value)value: string | number | boolean
   
stringstring(options?)options (optional): Object
  - optional : boolean defaults to false
  - maxLength: [length: number, error: string]
  - minLength: [length: number, error: string]
  - pattern : [pattern: RegExp, error: string]
   
numbernumber(options?)options(optional): Object
  - optional: boolean default to false
  - min: [number, error: string]
  - max: [number, error: string]
  - is : ['integer' | 'float', error: string] default is both
   
booleanboolean(options?)options(optional): Object
  - optional: boolean default to false
   
unionunion(...validators)validators: Array of validators as paramaters
   
listlist(validators[], options?)validators: Array of validators
  options(optional): Object
  - optional: boolean default to false
   
listoflistof(validator, options?)validator: Validator
  options(optional): Object
  - optional: boolean default to false
   
recordrecord(shape, options?)shape: Object { [key: string]: Validator }
  options(optional): Object
  - optional: boolean default to false
   
recordofrecordof(validator, options?)validator: Validator
  options(optional): Object
  - optional: boolean default to false

Custom validators

To create custom validators that do not break type inference:

  • use validators from _ as building blocks for your custom validator.
  • your custom validator should define optional and required functions.

Example of creating custom validators:

const alphaNumeric = (() => {
  const config = {
    pattern: [/^[a-zA-Z0-9]*$/, 'only-letters-and-number'],
  };
  return {
    required: additional => _.string({ ...additional, ...config, optional: false }), // inferred as Required
    optional: additional => _.string({ ...additional, ...config, optional: true }), // inferred as Optional
  };
})();

const Person = createSchema({
  // ...
  username: alphaNumeric.required({ maxLength: [20, 'username-too-long'] }),
  // ...
});

Caveats

  • When using the recordof | listof | list validators, the optional property of the validator is ignored, example:
_.recordof(_.string({ optional: true /* THIS IS IGNORED */ }));
_.list([_.number({ optional: true /* THIS IS IGNORED */ }), _.number()]);
  • You might expect errors returned from a list | listof validators to be an array but it is actually an object, example:
const list = createSchema({ list: _.listof(_.string()) });
list.validate({ list: ['string', 42, 'string'] }); // { list: { 1: 'invalid-type' } }

Recursive types

Currently, there's no easy way to create recursive types. if you think you could help, PRs are welcome

Errors while wrapping schemas

if you try to wrap your schema, you will encounter this error (Type instantiation is excessively deep and possibly infinite) to fix it, you should unwrap your schema and re-create it inside your abstraction. let's take the following example:

const User = createSchema({
  name: _.string(),
  age: _.number(),
});

// your abstraction
function schemaWrapper<T>(schema: T) {
  //...
}

const wrappedUser = schemaWrapper(User); // ERROR: Type instantiation is excessively deep and possibly infinite

The fix:

import { Schema, R, RecordOptions } from 'tiny-schema-validator';
/*
optionally, to infer data from the embedded schema, you do DataFrom<T>

import { DataFrom } from 'tiny-schema-validator/dist/type-utils';
*/

// extract schema with Schema.embed()
function schemaWrapper<T extends Schema>(schema: R<RecordOptions<T>>) {
  const newSchema = createSchema(schema.shape); // you can add/remove/modify passed schema here
  // ...
}

const wrappedUser = schemaWrapper(User.embed()); // all good no errors

Download Details:
Author: 5alidz
Download Link: Download The Source Code
Official Website: https://github.com/5alidz/tiny-schema-validator 
License: MIT

#javascript #typescript #json 

What is GEEK

Buddha Community

A JSON Schema Validator for JavaScript and TypeScript
Brain  Crist

Brain Crist

1600347600

SCHEMAS in SQL Server -MS SQL Server – Zero to Hero Query Master

Introduction

This is part 3 of “MS SQL Server- Zero to Hero” and in this article, we will be discussing about the SCHEMAS in SQL SERVER. Before getting into this article, please consider to visit previous articles in this series from below,

A glimpse of previous articles
Part 1

In part one, we learned the basics of data, database, database management system, and types of DBMS and SQL.

Part 2
  • We learned to create a database and maintain it using SQL statements.
  • Best practice methods were also mentioned.

#sql server #benefits of schemas #create schema in sql #database schemas #how to create schema in sql server #schemas #schemas in sql server #sql server schemas #what is schema in sql server

A JSON Schema Validator for JavaScript and TypeScript

Tiny Schema Validator

JSON schema validator with excellent type inference for JavaScript and TypeScript.

Installation

npm install tiny-schema-validator
# or
yarn add tiny-schema-validator

Usage

Creating a schema

import { createSchema, _ } from 'tiny-schema-validator';

export const User = createSchema({
  metadata: _.record({
    date_created: _.number(),
    id: _.string(),
  }),
  profile: _.record({
    name: _.string({
      maxLength: [100, 'too-long'],
      minLength: [2, 'too-short'],
    }),
    age: _.number({
      max: [150, 'too-old'],
      min: [13, 'too-young'],
    }),
    email: _.string({
      pattern: [/^[^@]+@[^@]+\.[^@]+$/, 'invalid-email'],
    }),
  }),
  payment_status: _.union(
    _.constant('pending'),
    _.constant('failed'),
    _.constant('success'),
    _.constant('canceled')
  ),
});

and in TypeScript, everything is the same, but to get the data type inferred from the schema, you can do this:

/*
  UserType {
    metadata: {
      date_created: number;
      id: string;
    };
    profile: {
      name: string;
      age: number;
      email: string;
    };
    payment_status: 'pending' | 'failed' | 'success' | 'canceled';
  }
*/
export type UserType = ReturnType<typeof User.produce>;

Using the schema

When you create a schema, you will get a nice API to handle multiple use-cases in the client and the server.

  • is(data: any): boolean check if the data is valid (eager evaluation)
  • validate(data: any): Errors errors returned has the same shape as the schema you defined (does not throw)
  • produce(data: any): data throws an error when the data is invalid. otherwise, it returns data
  • embed(config?: { optional: boolean }) embeds the schema in other schemas
  • source the schema itself in a parsable format

example usage:

const Person = createSchema({
  name: _.string(),
  age: _.number(),
  email: _.string(),
});

const john = { name: 'john', age: 42, email: 'john@gmail.com' };
Person.is({}); // false
Person.is(john); // true

Person.validate({}); // { name: 'invalid-type', age: 'invalid-type', email: 'invalid-type' }
Person.validate(john); // null

try {
  Person.produce(undefined);
} catch (e) {
  console.log(e instanceof TypeError); // true
  console.log(e.message); // "invalid-data"
}

// embedding the person schema
const GroupOfPeople = createSchema({
  // ...
  people: _.listof(Person.embed()),
  // ...
});

Validators

All validators are required by default. All validators are accessible with the _ (underscore) namespace; The reason for using _ instead of a good name like validators is developer experience, and you can alias it to whatever you want.

import { _ as validators } from 'tiny-schema-validator';

// NOTE: when you call a validator you just create an object with { type: '<type of validator>', ...options }
// this is just a shorthand for that.

// example of all validators and corresponding Typescript types
validators.string(); // string
validators.number(); // number
validators.boolean(); // boolean
validators.constant(42); // 42
validators.union(validators.constant(1), validators.constant(2), validators.constant(3)); // 1 | 2 | 3
validators.list([validators.number(), validators.number()]); // [number, number]
validators.listof(validators.string()); // string[]
validators.recordof(validators.string()); // Record<string, string>
validators.record({
  timestamp: validators.number(),
  id: validators.string(),
}); // { timestamp: number; id: string; }

Check out the full validators API below:

validatorsignatureprops
   
constantconstant(value)value: string | number | boolean
   
stringstring(options?)options (optional): Object
  - optional : boolean defaults to false
  - maxLength: [length: number, error: string]
  - minLength: [length: number, error: string]
  - pattern : [pattern: RegExp, error: string]
   
numbernumber(options?)options(optional): Object
  - optional: boolean default to false
  - min: [number, error: string]
  - max: [number, error: string]
  - is : ['integer' | 'float', error: string] default is both
   
booleanboolean(options?)options(optional): Object
  - optional: boolean default to false
   
unionunion(...validators)validators: Array of validators as paramaters
   
listlist(validators[], options?)validators: Array of validators
  options(optional): Object
  - optional: boolean default to false
   
listoflistof(validator, options?)validator: Validator
  options(optional): Object
  - optional: boolean default to false
   
recordrecord(shape, options?)shape: Object { [key: string]: Validator }
  options(optional): Object
  - optional: boolean default to false
   
recordofrecordof(validator, options?)validator: Validator
  options(optional): Object
  - optional: boolean default to false

Custom validators

To create custom validators that do not break type inference:

  • use validators from _ as building blocks for your custom validator.
  • your custom validator should define optional and required functions.

Example of creating custom validators:

const alphaNumeric = (() => {
  const config = {
    pattern: [/^[a-zA-Z0-9]*$/, 'only-letters-and-number'],
  };
  return {
    required: additional => _.string({ ...additional, ...config, optional: false }), // inferred as Required
    optional: additional => _.string({ ...additional, ...config, optional: true }), // inferred as Optional
  };
})();

const Person = createSchema({
  // ...
  username: alphaNumeric.required({ maxLength: [20, 'username-too-long'] }),
  // ...
});

Caveats

  • When using the recordof | listof | list validators, the optional property of the validator is ignored, example:
_.recordof(_.string({ optional: true /* THIS IS IGNORED */ }));
_.list([_.number({ optional: true /* THIS IS IGNORED */ }), _.number()]);
  • You might expect errors returned from a list | listof validators to be an array but it is actually an object, example:
const list = createSchema({ list: _.listof(_.string()) });
list.validate({ list: ['string', 42, 'string'] }); // { list: { 1: 'invalid-type' } }

Recursive types

Currently, there's no easy way to create recursive types. if you think you could help, PRs are welcome

Errors while wrapping schemas

if you try to wrap your schema, you will encounter this error (Type instantiation is excessively deep and possibly infinite) to fix it, you should unwrap your schema and re-create it inside your abstraction. let's take the following example:

const User = createSchema({
  name: _.string(),
  age: _.number(),
});

// your abstraction
function schemaWrapper<T>(schema: T) {
  //...
}

const wrappedUser = schemaWrapper(User); // ERROR: Type instantiation is excessively deep and possibly infinite

The fix:

import { Schema, R, RecordOptions } from 'tiny-schema-validator';
/*
optionally, to infer data from the embedded schema, you do DataFrom<T>

import { DataFrom } from 'tiny-schema-validator/dist/type-utils';
*/

// extract schema with Schema.embed()
function schemaWrapper<T extends Schema>(schema: R<RecordOptions<T>>) {
  const newSchema = createSchema(schema.shape); // you can add/remove/modify passed schema here
  // ...
}

const wrappedUser = schemaWrapper(User.embed()); // all good no errors

Download Details:
Author: 5alidz
Download Link: Download The Source Code
Official Website: https://github.com/5alidz/tiny-schema-validator 
License: MIT

#javascript #typescript #json 

Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Dicanio Rol

Dicanio Rol

1597067523

JSON Schema, Schema.org, JSON-LD: What’s the Difference?

Recently, I have seen several questions like “what’s the difference between JSON-LD and JSON Schema” or “can I use JSON Schema and Schema.org”. I come from a linked data background (which is close to the world of Schema.org) but have recently started using JSON Schema a lot and I have to admit that there is no trivial answer to these questions. There is the obvious similarity in the standard names like “Schema” and “JSON”. If you compare the Schema.org page for  Person to this  example on the JSON Schema page, you have to admit that they kind of look alike. Combine this with the fact that Schema.org touts JSON-LD, which — by design — very much looks like regular JSON completes the confusion. So there definitely are enough reasons to write this article.

JSON Schema

JSON Schema is to JSON what XML Schema is to XML. It allows you to specify the structure of a JSON document. You can state that the field “email” must follow a certain regular expression or that an address has “street_name”, “number”, and “street_type” fields.  Michael Droettboom’s book  “Understanding JSON Schema” illustrates validation quite nicely with red & green examples.

The main use case for JSON Schema seems to be in JSON APIs where it plays two major roles:

  1. Clients and servers can validate request and response objects in a generic way. This makes development a lot easier, since the implementation can “outsource” these checks to a standard component. Once a message passed the validation, you can safely assume that the document adheres to the rules.
  2. As with any API, documentation is key when developers write code that uses it. JSON Schema is increasingly used to describe the structure of requests and responses by embedding it in an overall API description. Swagger is probably the most prominent example of this paradigm. Consider the pet-store example. Scroll all the way down on the page and you see this JSON Schema definition of “Pet”, which is a basic element in requests and responses of this API (you can find the actual JSON Schema embedded in the raw Swagger file — note that currently there are still some differences between the OpenAPI specification and JSON Schema which will be resolved with OpenAPI 3.1).

Image for post

As with all things related to code, reuse is a good idea. JSON Schema has the ability to import schemas using the $ref keyword. There are also efforts to share schemas.  JSON Schema Store is one example. Its main use case is to support syntax highlighting for editors, for instance when editing a swagger file. At the time of writing, it contains over 250 schemas including — drum-roll please / you certainly guessed it — Schema.org. These describe things like  Action and  Place. So the idea could be to centrally define JSON Schema building blocks that can be re-used in different APIs, making it easier to consume them, maybe even to the point where intelligent software can interact with APIs automatically. But before we get carried away, let’s have a look at Schema.org.

#schema #swagger #json-ld #json-schema

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript