@launchdarkly/js-server-sdk-common-edge
Version:
LaunchDarkly Server SDK for JavaScript - common Edge SDK code
95 lines • 3.36 kB
JavaScript
import { deserializePoll, noop } from '@launchdarkly/js-server-sdk-common';
export class EdgeFeatureStore {
constructor(_edgeProvider, sdkKey, _description, _logger, _cache) {
this._edgeProvider = _edgeProvider;
this._description = _description;
this._logger = _logger;
this._cache = _cache;
// unused
this.delete = noop;
this.upsert = noop;
this._rootKey = `LD-Env-${sdkKey}`;
}
async get(kind, dataKey, callback) {
const { namespace } = kind;
const kindKey = namespace === 'features' ? 'flags' : namespace;
this._logger.debug(`Requesting ${dataKey} from ${this._rootKey}.${kindKey}`);
try {
const storePayload = await this._getStorePayload();
switch (namespace) {
case 'features':
callback(storePayload.flags[dataKey]);
break;
case 'segments':
callback(storePayload.segments[dataKey]);
break;
default:
callback(null);
}
}
catch (err) {
this._logger.error(err);
callback(null);
}
}
async all(kind, callback = noop) {
const { namespace } = kind;
const kindKey = namespace === 'features' ? 'flags' : namespace;
this._logger.debug(`Requesting all from ${this._rootKey}.${kindKey}`);
try {
const storePayload = await this._getStorePayload();
switch (namespace) {
case 'features':
callback(storePayload.flags);
break;
case 'segments':
callback(storePayload.segments);
break;
default:
callback({});
}
}
catch (err) {
this._logger.error(err);
callback({});
}
}
/**
* This method is used to retrieve the environment payload from the edge
* provider. If a cache is provided, it will serve from that.
*/
async _getStorePayload() {
var _a, _b;
let payload = (_a = this._cache) === null || _a === void 0 ? void 0 : _a.get(this._rootKey);
if (payload !== undefined) {
return payload;
}
const providerData = await this._edgeProvider.get(this._rootKey);
if (!providerData) {
throw new Error(`${this._rootKey} is not found in KV.`);
}
payload = deserializePoll(providerData);
if (!payload) {
throw new Error(`Error deserializing ${this._rootKey}`);
}
(_b = this._cache) === null || _b === void 0 ? void 0 : _b.set(this._rootKey, payload);
return payload;
}
async initialized(callback = noop) {
const config = await this._edgeProvider.get(this._rootKey);
const result = config !== null;
this._logger.debug(`Is ${this._rootKey} initialized? ${result}`);
callback(result);
}
init(allData, callback) {
callback();
}
getDescription() {
return this._description;
}
close() {
var _a;
return (_a = this._cache) === null || _a === void 0 ? void 0 : _a.close();
}
}
//# sourceMappingURL=EdgeFeatureStore.js.map