1.2.6 • Published 4 months ago

data-to-jsonschema-to-ts v1.2.6

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

data-to-jsonschema-to-ts

Convert plain javascript objects to JSON Schema and TypeScript typings.

Installation

npm install data-to-jsonschema-to-ts

Example

Convert data to JSON Schema

import {
  convertJsonSchemaToTs,
  createJsonSchemaValidator,
  generateJsonSchemaFromData,
} from "data-to-jsonschema-to-ts";

const TEST_DATA = [
  {
    id: 1,
    name: "John Doe",
    age: 30,
    email: "email@email.com",
  },
  {
    id: 1,
    name: "John Doe",
    age: 30,
    email: "email@email.com",
    address: {
      street: "123 Main St",
      city: "Anytown",
      state: "NY",
      zip: "12345",
    },
  },
  {
    id: 1,
    name: "John Doe",
    age: 30,
    email: null,
    preferences: [{ name: "pref1", value: "value1" }],
  },
];

const jsonSchema = generateJsonSchemaFromData(TEST_DATA, "TestData", {
  additionalProperties: false,
  existingSchema: undefined,
});

console.log(JSON.stringify(jsonSchema, null, 2));

Create a validator function from the generated schema

const validator = createJsonSchemaValidator(jsonSchema)

console.log(validator({id: 1, name: "John Doe", age: 30, email: "something@email.com"})); // valid
console.log(validator({id: 1, name: "John Doe", age: 30 })); // invalid, missing email

Convert the generated schema to TypeScript

convertJsonSchemaToTs(generatedSchema, {
  additionalProperties: false,
}).then((generatedTs) => {
  console.log(generatedTs);
});

Utilities

createJsonSchemaValidator(schema)

Generate a function that validates an object against a JSON Schema.

import { createJsonSchemaValidator } from "data-to-jsonschema-to-ts";

const validator = createJsonSchemaValidator({
    type: "object",
    properties: {
        id: { type: "number" },
        name: { type: "string" },
        age: { type: "number" },
        email: { type: "string" }
    },
    required: ["id", "name", "age", "email"]
});

validator({
    id: 1,
    name: "John Doe",
    age: 30,
    email: "myemail.com"
}); // { valid: true, errors: undefined }

validator({
    id: 1,
    age: null
}); // { valid: false, errors: [{...}] }

traverseObject(obj, callback)

Walk a plain javascript object and call a callback function for each primitive value and it's dot notation path.

import { traverseObject } from "data-to-jsonschema-to-ts";

const obj = {
    id: 1,
    profile: {
        name: "John Doe",
    }
}

traverseObject(obj, (value, jsonDotPath) => {
    console.log(value, jsonDotPath);
});

// console output:
// 1 "id"
// 'John Doe', "profile.name"
1.2.6

4 months ago

1.2.5

4 months ago

1.2.4

5 months ago

1.2.3

5 months ago

1.2.2

5 months ago

1.2.1

6 months ago

1.2.0

6 months ago

1.1.0

6 months ago

1.0.6

6 months ago

1.0.5

6 months ago

1.0.4

6 months ago

1.0.3

6 months ago

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

6 months ago