Socket
Socket
Sign inDemoInstall

json-schema-to-case-class

Package Overview
Dependencies
35
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    json-schema-to-case-class

A library that converts JSON Schema to Scala Case Classes


Version published
Weekly downloads
17
Maintainers
1
Install size
4.17 MB
Created
Weekly downloads
 

Readme

Source

json-schema-to-case-class

A library to convert complex JSON Schema to Scala Case Classes. Supports both NodeJs and Browser environments.

Build Status npm version License PRs Welcome PRs Welcome

Try Online Editor

Example

JSON Schema Generated Scala Case Classes
{
  "title": "Product",
  "type": "object",
  "required": [ "productId", "productName", "price" ],
  "properties": {
    "productId": { "type": "integer" },
    "productName": { "type": "string" },
    "price": { "type": "number" },
    "tags": {
      "type": "array",
      "items": { "type": "string" }
    },
    "dimensions": {
      "type": "object",
      "properties": {
        "length": { "type": "number" },
        "width": { "type": "number" },
        "height": { "type": "number" }
      }
    }
  }
}
case class Product (
   productId: Integer,
   productName: String,
   price: Double,
   tags: Option[List[String]],
   dimensions: Option[Dimensions]
)
case class Dimensions (
   length: Double,
   width: Double,
   height: Double
)

Features

  1. Resolve local as well as remote schema references.
  2. Handle nested JSON schema objects.
  3. Can wrap optional fields in Option[].
  4. Support constraint validations through assertion.
  5. Generate scaladoc based on the description provided in JSON Schema.
  6. Support various text cases for case class and parameter names.
  7. Can default to provided generic type. (default Any)
  8. Can build Enumeration objects for properties with enum field.

Installing

npm install --save json-schema-to-case-class

NPM

Usage - Node

For NodeJs (TypeScript):

import { convert, IConfig } from 'json-schema-to-case-class'

const mySchema: any = { ... };
const config: IConfig = { ... };  // <-- Optional

// With default configuration:
convert( mySChema )
  .then( result => console.log(result) )
  .catch( err => console.error(err) )

// With custom configuration:
convert( mySchema, config )
  .then( result => console.log(result) )
  .catch( err => console.error(err) )

For NodeJs (JavaScript):

const { convert } = require('json-schema-to-case-class');
// OR
const SchemaConverter = require('json-schema-to-case-class');
SchemaConverter.convert( , );

Polyfills

If you are building this for a use in browser, you will need to include the following pollyfills:

 http: require.resolve('http-browserify'),
 https: require.resolve('https-browserify'),
 stream: require.resolve('stream-browserify')

Check webpack.config.js for example configuration.

Usage - Prebuilt Bundle

For browser: If you are using the prebuild bundle, it has all the APIs under SchemaConverter global object:

SchemaConverter.convert( mySchema, config )

Configuration

It is optional to pass configuration object. Every configuration setting is optional as well. When not passed, default kicks-in. IConfig:

NameTypeDescriptionDefault
maxDepthnumberParses nested schema objects upto the depth = maxDepth. Pass 0 for no limit on depth.0
optionSettingstringSetting to wrap optional parameters in Option[].
1. "useOptions" - Wrap optional parameters in Option[]
2. "useOptionsForAll" - Wrapp all parameters in Option[]
3. "noOptions" - Don't wrap any parameter in Option[]
useOptions
classNameTextCasestringText case for case class title. Could be one of:
camelCase, capitalCase, constantCase, dotCase, headerCase, noCase, paramCase, pascalCase, pathCase, sentenceCase, snakeCase
pascalCase
classParamsTextCasestringText case for case class parameters. Could be one of above.snakeCase
topLevelCaseClassNamestringThis config kicks-in only if top level schema object does not have 'title' property.MyCaseClass
defaultGenericTypestringCase class parameter type when type information not available from the schema or if we are converting partial schema using maxDepth setting.Any
parseRefsbooleanWhether to resolve the local or remote schema references ($ref).true
generateCommentsbooleanWhether to generate scaladoc-like comments for the case class generated.false
generateValidationsbooleanWhether to generate validations in the form of assertions in case class body.false
generateEnumerationsbooleanWhether to generate enumerations for enum fields. It generates an object extending scala's Enumeration class and use it in parameter type.false

CLI

It also comes with the CLI. Install the package globally and run:

js2cc --help

OR use with npx

npx js2cc --help
Usage: js2cc <src> [options]

Convert JSON schemas into scala case class

Arguments:
  src                                       Path to json schema. It must be a local file. Support for reading URLs will be added in future version.

Options:
  -v, --version                             Library version
  -d, --max-depth <number>                  Maximum depth to parse nested JSON schema (default: 0)
  -s, --option-setting <type>               Wrap non-required fields in `Option` (choices: "noOptions", "useOptions", "useOptionsForAll", default: "useOptions")
  -n, --top-level-case-class-name <string>  Name of the top-level case class (Applies only if JSON schema does not have top-level `title` property. (default: "MyCaseClass")
  -d, --default-generic-type <string>       Default generic type for unparsable data types (default: "Any")
  -p, --parse-refs                          Parse local and remote references (default: true)
  -c, --generate-comments                   Generate scaladoc comments (default: false)
  -v, --generate-validations                Generate assertions from validations in JSON schema (default: false)
  -e, --generate-enumerations               Generate enumerations (default: false)
  -o, --output <string>                     File name to write output to. If not provided, output will be written to console. (default: false)
  -D, --debug                               Write more detailed output to console (default: false)
  -h, --help                                display help for command

Example call:
  $ js2cc ./local/sample-schema.json -n Person -s useOptions -o sample-output.scala --debug

Browser Support

This library supports recent versions of every major web browsers. Refer to the browserified build dist/js2cc.min.js that you can directly use in <script /> tag of HTML page. It already bundles all the required polyfills.

Limitations

  • Schema Compositions - It currently only supports allOf. Support for anyOf and oneOf will be added in future releases.

Contributing

All contributions, enhancements, and bug-fixes are welcome. Open an issue or create a pull request.

Building locally

  1. Clone the repo
    https://github.com/cchandurkar/json-schema-to-case-class.git

  2. Install Dependancies
    npm install

  3. Setup development environment
    npm run setup-dev-env

  4. Run the test
    npm test

  5. Run eslint checks
    npm run lint

  6. Run eslint checks and fix the errors
    npm run lint:fix

Keywords

FAQs

Last updated on 09 Apr 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc