Skip to content
This repository has been archived by the owner on Jan 19, 2024. It is now read-only.

Schema object generation #9

Closed
dmiorandi opened this issue Feb 27, 2016 · 3 comments
Closed

Schema object generation #9

dmiorandi opened this issue Feb 27, 2016 · 3 comments

Comments

@dmiorandi
Copy link

Probably is more related to Typescript than Javascript, but what about schema objects generation?
Actually I'm doing this task in java whit jaxrs generator (based on json schema used in raml).
I would like do to the same on client side.
Have you got any idea, how to achieve this extending this generator?

@blakeembrey
Copy link
Contributor

I'm not 100% which part you're asking about. For the actual implementation, it's generating an index.d.ts file with the client in a template. However, the actual conversion process might take some time. For example, JSON schema conversion has been attempted with https://github.com/lbovet/typson but I can't comment on the implementation as I'm yet to try it out.

I'm going to close this in favour of your implementation issue, #8, but feel free to ask more questions! 👍

@dmiorandi
Copy link
Author

Hello @blakeembrey, what I mean is the opposite. I mean generate d.ts from raml+jsonschema.
Probably I wrote a wrong description.
I've done it by myself, I wrote a node script an it works!!!
I'm using an external project (https://github.com/horiuchi/dtsgenerator.git) and raml parser combined togheter. Steps are:

  • Read RAML file with raml parser and extract all schemas.
  • Foreach schema write a single schema file (this is done cause I've got actually more schema defined in .yaml files that doesn't suite to dtsgenerator. It must be a pure jsonschema.
  • Fix $ref to work on files (i.e. "MyObj" ==> "/MyObj#)
  • Call dtsgenerator on set of schemas

It works on all my projects. The only limitation is that is related only to jsonschemas declared in header of raml.

Do you think it could be integrated as an experimental options?

var path = require("path");
var fs = require('fs');
var raml = require('raml-parser');
var mkdirp = require('mkdirp');
// var dtsgenerator = require('dtsgenerator');
var childProcess= require('child_process');
var rmdir = require('rmdir');
var program = require("commander");

var dtsGen = {
  // 'target': dtsDir,
  'outDir': schemasDir + '**/*'
};

//-----------------------------------------------------------------
var deleteFolderRecursive = function(path) {
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function(file, index) {
      var curPath = path + "/" + file;
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
};

function createEmptyDir(directory){
  if (fs.existsSync(directory)) {
    deleteFolderRecursive(directory);
  }
  mkdirp(directory, function (err) {
    if (err) {
      console.error(err);
      return false;
    }
  });
  return true;
}

function createDirIfnotExists(directory){
  if (!fs.existsSync(directory)) {
    mkdirp(directory, function (err) {
      if (err) {
        console.error(err);
        return false;
      }
    });
  }
  return true;
}

//-----------------------------------------------------------------

// Get raml object from parser, extract jsonschemas and printout in schemas folder
// Also patch $ref to be consistent
// Call dtsgen on generated schemas

program
  .usage('<ramlFile> <json-schema intermediate directory> <dts output directory>')
  .parse(process.argv);
var opts = program;
if (opts.args.length !== 3) {
    program.help();
    return;
}
var ramlFile=opts.args[0];
var schemasDir=opts.args[1];
var dtsDir=opts.args[2];

console.info('Preparing folders...');
if (!createEmptyDir(schemasDir) || !createDirIfnotExists(path.dirname(dtsDir))){
  console.error('preparing folders failed');
  return;
}

console.info('parsing raml ['+ramlFile+'] to extract schemas...');
if (!fs.existsSync(ramlFile)) {
   throw ("raml file not found");
}

raml.loadFile(ramlFile).then(function(data) {
  console.info('raml parsed going to extract to ['+schemasDir+']...');
  var schemaFiles='';
  for (var yamlFile in data.schemas) {
    for (var jsonSchemaName in data.schemas[yamlFile]) {
      var fileContent = data.schemas[yamlFile][jsonSchemaName];
      fileContent = fileContent.replace(/(\s*"\$ref"\s*:\s*")(.*)("\s*)/g, "$1/$2#$3");
      var fileName=schemasDir + "/" +jsonSchemaName + ".schema.json";
      fs.writeFile(fileName, fileContent, function(err) {
        if (err) {
          return console.log(err);
        }
      });
      schemaFiles+=fileName+' ';
    }
  }
  var allFile=schemasDir+'/_allFiles';
  fs.writeFile(allFile, schemaFiles, function(err) {
    if (err) {
      return console.log(err);
    }
  });
  console.info('schema extraction completed, now patching package.json...');
  var packageJsonFile=path.dirname(dtsDir)+'/package.json';
  if (fs.existsSync(packageJsonFile)) {
    fs.readFile(packageJsonFile, 'utf8', function(err, data) {
      if (err) {
        return console.log(err);
      }
      data=data.replace(/("files"\s*:\s*\[\s*)("index.js")(\s*])/, '$1$2,\"api-data.d.ts\"$3');
      fs.writeFile(packageJsonFile, data, function(err) {
        if (err) {
          return console.log(err);
        }
      });
    });
  }

  console.info('going to run dtsgen');
  childProcess.exec('dtsgen --out '+dtsDir+' '+ schemaFiles, function(error, stdout, stderr) {
    if (!error)
      console.info('dtsgen completed successfully onto ['+dtsDir+'] generated');
    else
      console.error(error);
  });

});

@blakeembrey
Copy link
Contributor

No, you're right. I did understand correctly, but missed that typeson was the opposite direction! It can definitely be integrated, but it needs to be properly integrated with the generated output.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants