/* eslint-disable class-methods-use-this */
const { System } = require('./system');
const utils = require('./utils');
/**
* @memberof module:@proceed/system
* @extends module:@proceed/system.System
* @class
* @hideconstructor
*/
class Data extends System {
/**
* Read the value for the given key.
* @async
* @param {string} key The key (of form table/id e.g. "execution/1").
* To read all values in the table simply set key
* to the table name e.g. "table" without a slash or id.
* @param {object|null} options The options for the read operation
*/
async read(key, options) {
const taskID = utils.generateUniqueTaskID();
// Prepare the promise
const listenPromise = new Promise((resolve, reject) => {
// Listen for the response
this.commandResponse(taskID, (err, data) => {
// Resolve or reject the promise
if (err) {
reject(err);
} else {
resolve(data);
}
return true;
});
});
// Emit the task
this.commandRequest(taskID, ['read', [key, options]]);
return listenPromise;
}
/**
* Write the value for the given key.
* @async
* @param {string} key The key (of form table/id e.g. "execution/1")
* @param {object} value The value to store
* @param {object|null} options The options for the write operation
*/
async write(key, value, options) {
if (value !== null && typeof value !== 'string') {
throw new Error('data.write() value is not of type string!');
}
const taskID = utils.generateUniqueTaskID();
// Prepare the promise
const listenPromise = new Promise((resolve, reject) => {
// Listen for the response
this.commandResponse(taskID, (err, data) => {
// Resolve or reject the promise
if (err) {
reject(err);
} else {
resolve(data);
}
return true;
});
});
// Emit the task
this.commandRequest(taskID, ['write', [key, value, options]]);
return listenPromise;
}
/**
* Delete the value for the given key.
* @async
* @param {string} key The key (of form table/id e.g. "execution/1")
* @param {object|null} options The options for the delete operation
*/
async delete(key, options) {
this.write(key, null, options);
}
}
module.exports = Data;