From a4ec0bd767ffd495aa82990bbfc46ea607f071bc Mon Sep 17 00:00:00 2001 From: Cristiano Amici Date: Tue, 11 May 2021 10:17:28 -0500 Subject: [PATCH] Add support for passing file content as string --- trool/README.md | 25 +++++++++++++++++++++++ trool/lib/Trool.ts | 51 ++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/trool/README.md b/trool/README.md index 0ce1589..ce143c6 100644 --- a/trool/README.md +++ b/trool/README.md @@ -210,3 +210,28 @@ with multiple values. - Import property name rules are the same as for JavaScript keys. That means alphanumeric, underscores, and dashes. Anything other than characters will throw an error. + +- In case you don't have local access to your rules file, or can't otherwise pass a file path, you can use +`initFromString()` and pass the content of the CSV file as a string instead: + ```typescript + const factsHolder = { + Visitors: [new Visitor(), new Visitor()], + Tickets: new Ticket(), + }; + + const importsHolder = { + VisitorTypes: { + ADULT: 'Adult', + CHILD: 'Child', + }, + }; + + try { + const s3 = new AWS.S3(); + const data = await s3.getObject({ Bucket: bucketName, Key: bucketKey }); + + const facts = this.setupFactsHolder(visitors, ticketOpt); + const trool = new Trool(); + await trool.initFromString(data.Body, factsHolder, true, importsHolder); + + ``` diff --git a/trool/lib/Trool.ts b/trool/lib/Trool.ts index b0ab445..1a60411 100644 --- a/trool/lib/Trool.ts +++ b/trool/lib/Trool.ts @@ -24,7 +24,7 @@ class Trool { /** - * Create the decision tables. + * Initialize the engine. * * @param filePath * @param facts @@ -37,14 +37,47 @@ class Trool { showLogs?: boolean, imports?: IImportsHolder, ) { - try { - this.logger = new Logger(showLogs); - const jsonArr = await csvToJson().fromFile(filePath); - const allImports = this.setupImports(jsonArr, imports || {}); - this._decisionTables = this.getTables(jsonArr, facts, allImports); - } catch (err) { - throw err; - } + const jsonArr = await csvToJson().fromFile(filePath); + this.createDecisionTables(jsonArr, facts, showLogs, imports); + } + + + /** + * Initialize the engine with the CSV file content passed as string. + * + * @param fileContent + * @param facts + * @param imports + * @param showLogs + */ + public async initFromString( + fileContent: string, + facts: IFactsHolder, + showLogs?: boolean, + imports?: IImportsHolder, + ) { + const jsonArr = await csvToJson().fromString(fileContent); + this.createDecisionTables(jsonArr, facts, showLogs, imports); + } + + + /** + * Create the decision tables. + * + * @param filePath + * @param facts + * @param imports + * @param showLogs + */ + private createDecisionTables( + jsonArr: IRow[], + facts: IFactsHolder, + showLogs?: boolean, + imports?: IImportsHolder, + ) { + this.logger = new Logger(showLogs); + const allImports = this.setupImports(jsonArr, imports || {}); + this._decisionTables = this.getTables(jsonArr, facts, allImports); }