Skip to content

Commit

Permalink
Added ConvoStorage.
Browse files Browse the repository at this point in the history
  • Loading branch information
tmtek committed Oct 20, 2018
1 parent e531b30 commit 937d4f0
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 2 deletions.
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
const { Convo } = require('./src/convo');
const { ConvoApp } = require('./src/convo-app');
const { Say } = require('./src/say');
const { ConvoStorage } = require('./src/convo-storage');

module.exports = { Convo, ConvoApp, Say };
module.exports = { Convo, ConvoApp, Say, ConvoStorage };
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@tmtek/convo",
"version": "0.1.9",
"version": "0.1.10",
"description": "A uility for building conversational responses in DialogFlow fufillments",
"main": "index.js",
"scripts": {
Expand Down
14 changes: 14 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,20 @@ convo.getFromStorage("list"); //returns ["one","two","three"]

`onStorageUpdated()` and `setStorage()` are useful when testing your application outside of DialogFlow, because you can use those methods to simulate persisted data, or actually persist it yourself.

#### ConvoStorage

There is a utility included with Convo that you can use to create a Convo object that has it's storage populated from a json file and will also write any changes made to storage to that file:

```javascript
const {ConvoStorage} = require('@tmtek/convo');

new ConvoStorage("storage.json").load(storageConvo => {
new YourApp().intent(storageConvo, 'welcome', null, null, {log:true});
});
```

The ConvoStorage class allows you to specify a json file to load your data from. Then you call `load(convo=> {})` to get a Convo object generated for that storage data. If your application uses `setToStorage()` thereafter, the data will be automatically saved to that json file.



## API Reference
Expand Down
34 changes: 34 additions & 0 deletions src/convo-storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const fs = require('fs');
const {Convo} = require('./convo');

class ConvoStorage {
constructor(filename) {
this._filename = filename;
}

load(callback) {
new Promise((resolve, reject) => {
if (!this._filename) {
resolve({});
return;
}
fs.readFile(this._filename, 'utf8', (error, data) => {
!error ? resolve(JSON.parse(data)) : resolve({})
})
})
.then(data => callback(
new Convo()
.setStorage(data)
.onStorageUpdated(this.write)
));
}

write(storage) {
if(!this._filename) {
return;
}
fs.writeFile(this._filename, JSON.stringify(storage, null, 2), error => {})
}
}

module.exports = {ConvoStorage}

0 comments on commit 937d4f0

Please sign in to comment.