Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,50 @@ const body = {
}
};

const ofx_string = ofx.serialize(header, body);
// By default, the serializer won't close the end node tags. To change that, pass { closeTags: true } as an option.

const options = {closeTags: true};
const ofx_string = ofx.serialize(header, body, options);
console.log(ofx_string);

```

Sample result with default `options`:

```xml
<SIGNONMSGSRSV1>
<SONRS>
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<DTSERVER>20210330
<LANGUAGE>POR
<FI>
<ORG>Some Bank Institution
<FID>012
</FI>
</SONRS>
</SIGNONMSGSRSV1>
```

Sample result with `options = {closeTags: true}`:

```xml
<SIGNONMSGSRSV1>
<SONRS>
<STATUS>
<CODE>0</CODE>
<SEVERITY>INFO</SEVERITY>
</STATUS>
<DTSERVER>20210330</DTSERVER>
<LANGUAGE>POR</LANGUAGE>
<FI>
<ORG>Some Bank Institution</ORG>
<FID>012</FID>
</FI>
</SONRS>
</SIGNONMSGSRSV1>
```

## Data ##
Expand Down
33 changes: 20 additions & 13 deletions ofx.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function parse(data) {

// Parse the XML/SGML portion of the file into an object
// Try as XML first, and if that fails do the SGML->XML mangling
let dataParsed = null;
let dataParsed;
try {
dataParsed = parseXml(content);
} catch (e) {
Expand All @@ -43,7 +43,12 @@ function parse(data) {
return dataParsed;
}

function serialize(header, body) {
const DEFAULT_OPTIONS = {
closeTags: false
}

function serialize(header, body, options = {}) {
const normalizedOptions = {...DEFAULT_OPTIONS, ...options};
let out = '';
// header order could matter
const headers = ['OFXHEADER', 'DATA', 'VERSION', 'SECURITY', 'ENCODING', 'CHARSET',
Expand All @@ -54,28 +59,30 @@ function serialize(header, body) {
});
out += '\n';

out += objToOfx({ OFX: body });
out += objToOfx({ OFX: body }, normalizedOptions);
return out;
}

const objToOfx = (obj) => {
const objToOfx = (obj, options) => {
let out = '';

Object.keys(obj).forEach((name) => {
const item = obj[name];
const start = `<${name}>`;
const end = `</${name}>`;

if (item instanceof Object) {
if (item instanceof Array) {
item.forEach((it) => {
out += `${start}\n${objToOfx(it)}${end}\n`;
});
return;
}
return out += `${start}\n${objToOfx(item)}${end}\n`
if (!(item instanceof Object)) {
out += `${start}${item}${options.closeTags ? end : ''}\n`;
return;
}

if (!(item instanceof Array)) {
return out += `${start}\n${objToOfx(item, options)}${end}\n`
}
out += start + item + '\n';

item.forEach((it) => {
out += `${start}\n${objToOfx(it, options)}${end}\n`;
});
});

return out;
Expand Down