Merge pull request #5 from AChris07/add-file-content-support

Add support for passing file content as string
This commit is contained in:
Sean Maxwell
2021-05-14 11:10:30 -07:00
committed by GitHub
2 changed files with 67 additions and 9 deletions

View File

@@ -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);
```

View File

@@ -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);
}