Skip to content

Commit

Permalink
Merge pull request #40 from nsinghal12/async-parse
Browse files Browse the repository at this point in the history
Fix #30: add parseAsync method
  • Loading branch information
nsinghal12 authored Oct 30, 2022
2 parents cb9d081 + 167f488 commit ed61586
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 23 deletions.
58 changes: 43 additions & 15 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/** @module Node Pom Parser */

"use strict";

import fs from 'fs';
Expand All @@ -13,45 +11,75 @@ var XML2JS_OPTS = {
normalize: true,
mergeAttrs: true
};

interface ParsedOutput {
pomXml: string;
pomObject: object;
xmlContent?: string;
}
type ParseOptions=(Options & { filePath?: string; xmlContent?: string }) | null
type ParseCallback=(e: Error | null, r?: ParsedOutput | null) => void;

type ParseOptions = (Options & { filePath?: string; xmlContent?: string }) | null

type ParseCallback = (e: Error | null, r?: ParsedOutput | null) => void;

/**
* This method exposes an `async/await` syntax to the older
* `parse` method and allows you to call the method with just
* one argument.
*
* @param {ParseOptions} opt the options to be used for parsing
*
* @returns {Promise<ParsedOutput>} a `Promise` that holds the parsed output
*/
export async function parseAsync(opt: ParseOptions): Promise<ParsedOutput> {
if (!opt) {
throw new Error("You must provide options: opt.filePath and any other option of " + "https://github.com/Leonidas-from-XIV/node-xml2js#options");
}

if (!opt.xmlContent && !opt.filePath) {
throw new Error("You must provide the opt.filePath or the opt.xmlContent");
}

if (opt.filePath) {
const xmlContent = await readFileAsync(opt.filePath, "utf8")
const result = await _parseWithXml2js(xmlContent);
return result;
}

const result = await _parseWithXml2js(opt.xmlContent || '');
delete result.xmlContent;
return result;
}

/**
* Parses xml into javascript object by using a file path or an xml content.
* @param {object} opt Is the option with the filePath or xmlContent and the optional format.
* @return {object} The pom object along with the timers.
*/
function parse(opt: ParseOptions,callback: ParseCallback): void {
function parse(opt: ParseOptions, callback: ParseCallback): void {
if (!opt) {
throw new Error("You must provide options: opt.filePath and any other option of " +
"https://github.com/Leonidas-from-XIV/node-xml2js#options");
throw new Error("You must provide options: opt.filePath and any other option of " + "https://github.com/Leonidas-from-XIV/node-xml2js#options");
}

if (!opt.xmlContent && !opt.filePath) {
throw new Error("You must provide the opt.filePath or the opt.xmlContent");
}


// If the xml content is was not provided by the api client.
// https://github.com/petkaantonov/bluebird/blob/master/API.md#error-rejectedhandler----promise
if (opt.filePath) {
readFileAsync(opt.filePath, "utf8").then(function(xmlContent) {
readFileAsync(opt.filePath, "utf8").then(function (xmlContent) {
return xmlContent;

}).then(_parseWithXml2js).then(function(result) {
}).then(_parseWithXml2js).then(function (result) {
callback(null, result);

}).catch(function(e) {
}).catch(function (e) {
callback(e, null);
});

} else if (opt.xmlContent) {
// parse the xml provided by the api client.
_parseWithXml2js(opt.xmlContent).then(function(result) {
_parseWithXml2js(opt.xmlContent).then(function (result) {
delete result.xmlContent;
callback(null, result);

Expand All @@ -71,7 +99,7 @@ function parse(opt: ParseOptions,callback: ParseCallback): void {
function _parseWithXml2js(xmlContent: string): Promise<ParsedOutput> {
return new Promise(function (resolve, reject) {
// parse the pom, erasing all
xml2js.parseString(xmlContent, XML2JS_OPTS, function(err, pomObject) {
xml2js.parseString(xmlContent, XML2JS_OPTS, function (err, pomObject) {
if (err) {
// Reject with the error
reject(err);
Expand All @@ -93,7 +121,7 @@ function _parseWithXml2js(xmlContent: string): Promise<ParsedOutput> {
* Removes all the arrays with single elements with a string value.
* @param {object} o is the object to be traversed.
*/
function removeSingleArrays(obj: Object):void {
function removeSingleArrays(obj: Object): void {
// Traverse all the elements of the object
traverse(obj).forEach(function traversing(value) {
// As the XML parser returns single fields as arrays.
Expand Down
14 changes: 8 additions & 6 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import parse from "../lib/index.js";
import { expect } from "chai";
import assert from "assert";
import { dirname } from "path";
import { fileURLToPath } from "url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const POM_PATH = __dirname + "/fixture/pom.xml";
// read the current working directory, where
// package.json file lives
const __dirname = process.cwd();

// form path to test fixtures
const POM_PATH = __dirname + "/test/fixture/pom.xml";

describe('require("pom-parser")', function () {
describe("loading from files", function () {
Expand Down Expand Up @@ -58,15 +60,15 @@ describe('require("pom-parser")', function () {
describe("when opts is null", function () {
it("parser should throw an error", function () {
assert.throws(function () {
parse(null, function (err, response) {});
parse(null, function (err, response) { });
});
});
});

describe("when opts is empty", function () {
it("parser should throw an error", function () {
assert.throws(function () {
parse({}, function (err, response) {});
parse({}, function (err, response) { });
});
});
});
Expand Down
6 changes: 4 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
{
"compilerOptions": {
"target": "es5",
"module": "es2022",
"target": "ES6",
"lib": ["ES6"],
"module": "ES6",
"outDir": "./dist",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"moduleResolution": "node"
},
"include": ["lib/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"],
Expand Down

0 comments on commit ed61586

Please sign in to comment.