Skip to content

Commit

Permalink
fix: enable tree-shaking on data-format (#411)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjlevesque committed Feb 19, 2021
1 parent a2f30a8 commit c6e34ed
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
15 changes: 15 additions & 0 deletions packages/data-format/src/format/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/* eslint-disable spellcheck/spell-checker */
import * as rnf_invoice_0_0_1 from './rnf_invoice/rnf_invoice-0.0.1.json';
import * as rnf_invoice_0_0_2 from './rnf_invoice/rnf_invoice-0.0.2.json';
import * as rnf_invoice_0_0_3 from './rnf_invoice/rnf_invoice-0.0.3.json';

// Re-export the JSON files structured by format and version.
// NB: A dynamic require (require(`${format}/${format}-${version}.json`)) would prevent tree-shaking
const formats: Record<string, Record<string, any>> = {
rnf_invoice: {
'0.0.1': rnf_invoice_0_0_1,
'0.0.2': rnf_invoice_0_0_2,
'0.0.3': rnf_invoice_0_0_3,
},
};
export default formats;
20 changes: 6 additions & 14 deletions packages/data-format/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
// JSON Schema of an address
import * as schemaAddress from './format/address.json';

/* eslint-disable spellcheck/spell-checker */
// another json validation tool from https://github.com/epoberezkin/ajv
import * as AJV from 'ajv';
/* eslint-disable spellcheck/spell-checker */
import * as jsonSchema from 'ajv/lib/refs/json-schema-draft-06.json';
import * as schemaAddress from './format/address.json';
import formats from './format';

export default {
/**
Expand All @@ -13,9 +11,7 @@ export default {
* @return object.valid == true if the json is valid, object.valid == false and object.errors otherwise.
*/
validate(data: any): any {
const validationTool = new AJV()
.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'))
.addSchema(schemaAddress);
const validationTool = new AJV().addMetaSchema(jsonSchema).addSchema(schemaAddress);

// Check the meta information
if (!data.meta) {
Expand All @@ -29,12 +25,8 @@ export default {
}

// Try to retrieve the schema json
let schema;
try {
schema = require(`./format/${data.meta.format}/${data.meta.format}-${
data.meta.version
}.json`);
} catch (e) {
const schema = formats[data.meta.format]?.[data.meta.version];
if (!schema) {
return { valid: false, errors: [{ message: 'format not found' }] };
}

Expand Down

0 comments on commit c6e34ed

Please sign in to comment.