raml-org / ramldt2jsonschema

CLI & Library to convert a RAML 1.0 data type to a JSON Schema, and back
Apache License 2.0
59 stars 22 forks source link
raml raml-tooling

ramldt2jsonschema

Greenkeeper badge NPM version NPM downloads Build status Test coverage

CLI & Library to convert a RAML 1.0 DataType to a JSON Schema, and back. Uses webapi-parser under the hood.

Usage

Global (CLI)

npm install -g ramldt2jsonschema

This will install two command-line tools:

dt2js

dt2js <ramlFile> <ramlTypeName> --draft=[version] [--validate]

Options

js2dt

js2dt <jsonFile> <ramlTypeName> [--validate]

Options

Locally (JavaScript)

npm install ramldt2jsonschema --save

dt2js

const r2j = require('ramldt2jsonschema')
const join = require('path').join
const fs = require('fs')

const filePath = join(__dirname, 'complex_cat.raml')
const ramlData = fs.readFileSync(filePath).toString()

async function main () {
  let schema
  try {
    schema = await r2j.dt2js(ramlData, 'Cat')
  } catch (err) {
    console.log(err)
    return
  }
  console.log(JSON.stringify(schema, null, 2))
}

main()

js2dt

const r2j = require('ramldt2jsonschema')
const join = require('path').join
const fs = require('fs')
const yaml = require('js-yaml')

const filePath = join(__dirname, 'complex_cat.json')
const jsonData = fs.readFileSync(filePath).toString()

async function main () {
  let raml
  try {
    raml = await r2j.js2dt(jsonData, 'Cat')
  } catch (err) {
    console.log(err)
    return
  }
  console.log('#%RAML 1.0 Library\n')
  console.log(yaml.safeDump(raml, { 'noRefs': true }))
}

main()

Resolving references

When the input contains external references (!include, uses:, $ref, etc.) and the referred files are not in the same directory as the script it is being ran from, you may provide a third argument to both dt2js and js2dt. The argument must be an object with a basePath key. All references will then be resolved relative to that base path.

Example of using basePath argument in dt2js:

// Script below ran from /home/john/where/ever/
// Reference is located at /home/john/schemas/simple_person.json
const raml2json = require('ramldt2jsonschema')

const ramlStr = `
  #%RAML 1.0 Library

  types:
    Person: !include simple_person.json
`
const basePath = '/home/john/schemas/' // or '../../schemas/'
const schema = raml2json.dt2js(ramlStr, 'Person', { basePath: basePath })
console.log(JSON.stringify(schema, null, 2))

Limitations

License

Apache 2.0