2020-01-21 18:12:14 +00:00
|
|
|
// Copyright IBM Corp. 2016,2019. All Rights Reserved.
|
2019-05-08 15:45:37 +00:00
|
|
|
// Node module: loopback-datasource-juggler
|
|
|
|
// This file is licensed under the MIT License.
|
|
|
|
// License text available at https://opensource.org/licenses/MIT
|
|
|
|
|
2016-08-08 08:15:22 +00:00
|
|
|
'use strict';
|
|
|
|
|
2018-12-07 14:54:29 +00:00
|
|
|
const assert = require('assert');
|
|
|
|
const utils = require('../utils');
|
2016-08-08 08:15:22 +00:00
|
|
|
|
|
|
|
/**
|
2016-09-17 00:03:33 +00:00
|
|
|
* Persist a value and associate it with the given key.
|
2016-08-08 08:15:22 +00:00
|
|
|
*
|
2016-09-17 00:03:33 +00:00
|
|
|
* @param {String} key Key to associate with the given value.
|
|
|
|
* @param {*} value Value to persist.
|
|
|
|
* @options {Number|Object} options Optional settings for the key-value
|
|
|
|
* pair. If a Number is provided, it is set as the TTL (time to live) in ms
|
|
|
|
* (milliseconds) for the key-value pair.
|
|
|
|
* @property {Number} ttl TTL for the key-value pair in ms.
|
|
|
|
* @callback {Function} callback
|
|
|
|
* @param {Error} err Error object.
|
|
|
|
* @promise
|
2016-08-08 08:15:22 +00:00
|
|
|
*
|
|
|
|
* @header KVAO.set(key, value, cb)
|
|
|
|
*/
|
|
|
|
module.exports = function keyValueSet(key, value, options, callback) {
|
|
|
|
if (callback == undefined && typeof options === 'function') {
|
|
|
|
callback = options;
|
|
|
|
options = {};
|
|
|
|
} else if (typeof options === 'number') {
|
2016-08-19 17:46:59 +00:00
|
|
|
options = {ttl: options};
|
2016-08-08 08:15:22 +00:00
|
|
|
} else if (!options) {
|
|
|
|
options = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
assert(typeof key === 'string' && key, 'key must be a non-empty string');
|
|
|
|
assert(value != null, 'value must be defined and not null');
|
|
|
|
assert(typeof options === 'object', 'options must be an object');
|
|
|
|
if (options && 'ttl' in options) {
|
|
|
|
assert(typeof options.ttl === 'number' && options.ttl > 0,
|
|
|
|
'options.ttl must be a positive number');
|
|
|
|
}
|
|
|
|
|
|
|
|
callback = callback || utils.createPromiseCallback();
|
|
|
|
|
|
|
|
// TODO convert possible model instance in "value" to raw data via toObect()
|
|
|
|
this.getConnector().set(this.modelName, key, value, options, callback);
|
|
|
|
return callback.promise;
|
|
|
|
};
|