Skip to content

Commit

Permalink
#2 convert YAML to JSON and vice-versa
Browse files Browse the repository at this point in the history
  • Loading branch information
Raisel Melian committed Jan 24, 2019
1 parent 88a58f6 commit 5e2685b
Show file tree
Hide file tree
Showing 10 changed files with 210 additions and 27 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@ jspm_packages

# Optional REPL history
.node_repl_history
/.idea/
14 changes: 11 additions & 3 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
const program = require('commander');
const { version } = require('./package.json');
const validate = require('./validate');
const convert = require('./convert');

function collect(val, item) {
item.push(val);
Expand All @@ -15,14 +16,21 @@ function collect(val, item) {

program
.version(version)
.usage('<command>')
.option('-c, --config [configFile]', 'config file (containing JSON/YAML). See README for potential values.');
.usage('<command>');
// .option('-c, --config [configFile]', 'config file (containing JSON/YAML). See README for potential values.');

program
.command('validate <file-or-url>')
.description('validate Async-API documents')
.description('validate AsyncAPI file/url')
.action(validate.command);

program
.command('convert <file-or-url>')
.description('convert AsyncAPI file/url from YAML to JSON and vice-versa. No compression is performed')
.option('-f, --format <format>', 'specify desired target format: json|yaml', /^(json|yaml)$/i)
.action((specFile, cmd) => {
convert.command(specFile, cmd.format)
});

program.parse(process.argv);

Expand Down
20 changes: 20 additions & 0 deletions convert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env node

'use strict'

const converter = require('./lib/converter.js');
const formats = converter.formats;

const command = async (specFilePath, targetFormat) => {

if (targetFormat !== formats.YAML || targetFormat !== formats.JSON) {
console.log("throw `Invalid target format: ${targetFormat}`;");
process.exit(1);
}

const document = await converter.convert(specFilePath, targetFormat);
console.log(document);
};


module.exports = { command };
41 changes: 41 additions & 0 deletions lib/converter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';
const parser = require('./parser');
const YAML = require('js-yaml');


const formats = Object.freeze({
JSON: "json",
YAML: "yaml"
});

const convert = async (specFilePath, targetFormat) => {

let content = await parser.getFileContent(specFilePath);

content = content.toString('utf8');

if (targetFormat === formats.YAML) {

let jsonObject = JSON.parse(content);

return YAML.safeDump(jsonObject);

} else if (targetFormat === formats.JSON) {

const parsedContent = YAML.safeLoad(content);

const bundledContent = await parser.bundle(parsedContent);

const dereferencedContent = await parser.dereference(bundledContent);

return JSON.stringify(dereferencedContent);
}

throw `Invalid target format: ${targetFormat}`;
};

module.exports = {
convert: convert,
formats: formats
};

18 changes: 10 additions & 8 deletions lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async function dereference (json) {
});
}

async function bundle (json) {
async function bundle(json) {
return RefParser.bundle(json, {
dereference: {
circular: 'ignore'
Expand All @@ -50,9 +50,8 @@ async function validate (json, schema) {
}

async function parse (filePath) {
let content, parsedContent, dereferencedJSON, bundledJSON, parsed;
let content, parsedContent, dereferencedJSON, bundledJSON, parsed;

try {
if (typeof filePath === 'string') {
content = await getFileContent(filePath);
} else if (typeof filePath === 'object') {
Expand All @@ -61,10 +60,7 @@ async function parse (filePath) {
// console.error(`Could not find a valid asyncapi definition: ${filePath}`);
throw `Could not find a valid asyncapi definition: ${filePath}`;
}
} catch (e) {
// console.error('Can not load the content of the AsyncAPI specification file');
throw e;
}


try {
parsedContent = parseContent(content);
Expand Down Expand Up @@ -102,4 +98,10 @@ async function parse (filePath) {
return JSON.parse(JSON.stringify(parsed));
};

module.exports = parse;
module.exports = {
parse: parse,
getFileContent: getFileContent,
dereference: dereference,
bundle, bundle
};

5 changes: 2 additions & 3 deletions lib/validator.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
'use strict';
const parse = require('./parser');
const parser = require('./parser');

const validate = async (specFile) => {

await parse(specFile);
await parser.parse(specFile);
return true;

};

module.exports = {validate};
5 changes: 4 additions & 1 deletion script.bash
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
#!/usr/bin/env bash
async-api-linter validate /Users/melianr/dev/asyncapi/async-api-linter/test/samples/asyncapi.yml
#async-api-linter validate /Users/melianr/dev/asyncapi/async-api-linter/test/samples/asyncapi.yml
#async-api-linter validate /Users/melianr/dev/asyncapi/async-api-linter/test/samples/asyncapi.json

async-api-linter convert /Users/melianr/dev/asyncapi/async-api-linter/test/samples/asyncapi.yml
117 changes: 117 additions & 0 deletions test/samples/asyncapi.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
{
"asyncapid": "1.2.0",
"info": {
"title": "Streetlights API",
"version": "1.0.0",
"description": "The Smartylighting Streetlights API allows you\nto remotely manage the city lights.\n",
"license": {
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0"
}
},
"baseTopic": "smartylighting.streetlights.1.0",
"servers": [
{
"url": "test.mosquitto.org",
"scheme": "mqtt",
"description": "Test broker",
"variables": {
"port": {
"description": "Secure connection (TLS) is available through port 8883.",
"default": "1883",
"enum": [
"1883",
"8883"
]
}
}
}
],
"topics": {
"event.lighting.measured": {
"x-service-name": "streetlights",
"publish": {
"x-operation-id": "lightMeasuredPublish",
"summary": "Inform about environmental lighting conditions for a particular streetlight.",
"payload": {
"type": "object",
"properties": {
"lumens": {
"type": "integer",
"minimum": 0,
"description": "Light intensity measured in lumens."
},
"sentAt": {
"type": "string",
"format": "date-time",
"description": "Date and time when the message was sent."
}
}
}
},
"subscribe": {
"x-operation-id": "lightMeasuredSubscribe",
"summary": "Inform about environmental lighting conditions for a particular streetlight.",
"payload": {
"type": "object",
"properties": {
"lumens": {
"type": "integer",
"minimum": 0,
"description": "Light intensity measured in lumens."
},
"sentAt": {
"type": "string",
"format": "date-time",
"description": "Date and time when the message was sent."
}
}
}
}
}
},
"components": {
"messages": {
"lightMeasured": {
"summary": "Inform about environmental lighting conditions for a particular streetlight.",
"payload": {
"type": "object",
"properties": {
"lumens": {
"type": "integer",
"minimum": 0,
"description": "Light intensity measured in lumens."
},
"sentAt": {
"type": "string",
"format": "date-time",
"description": "Date and time when the message was sent."
}
}
}
}
},
"schemas": {
"lightMeasuredPayload": {
"type": "object",
"properties": {
"lumens": {
"type": "integer",
"minimum": 0,
"description": "Light intensity measured in lumens."
},
"sentAt": {
"type": "string",
"format": "date-time",
"description": "Date and time when the message was sent."
}
}
},
"sentAt": {
"type": "string",
"format": "date-time",
"description": "Date and time when the message was sent."
}
}
}
}
10 changes: 1 addition & 9 deletions test/samples/asyncapi.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
asyncapi: '1.2.0'
asyncapid: '1.2.0'
info:
title: Streetlights API
version: '1.0.0'
Expand Down Expand Up @@ -29,14 +29,6 @@ topics:
subscribe:
x-operation-id: lightMeasuredSubscribe
$ref: '#/components/messages/lightMeasured'
event.lighting.traced:
x-service-name: streetlights
publish:
x-operation-id: lightTracedPublish
$ref: '#/components/messages/lightMeasured'
subscribe:
x-operation-id: lightTracedSubscribe
$ref: '#/components/messages/lightMeasured'
components:
messages:
lightMeasured:
Expand Down
6 changes: 3 additions & 3 deletions validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ const validator = require('./lib/validator.js');
const command = async (specFile, cmd) => {
try {
await validator.validate(specFile);
// console.log("valid");
console.log("Valid AsyncAPI document");
process.exit(0);
}catch (e) {
// console.error("NOT valid");
// console.error(e.message);
console.log("Non valid AsyncAPI document");
console.error(e.message);
process.exit(1);
}

Expand Down

0 comments on commit 5e2685b

Please sign in to comment.