Skip to content

Commit

Permalink
Add persist method (#367)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexis-falaise authored Mar 14, 2023
1 parent 25826de commit 5743087
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
25 changes: 25 additions & 0 deletions addon/-sdk/context.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
import { isNone } from '@ember/utils';
import { TrackedMap } from 'tracked-maps-and-sets';

const STORAGE_KEY = 'ember-launch-darkly';

function setPersistedFlags(context) {
let persistedFlags = window.localStorage.getItem(STORAGE_KEY);

if (persistedFlags) {
context.replaceFlags(JSON.parse(persistedFlags));
}
}

function setCurrentContext(context) {
setPersistedFlags(context);
window.__LD__ = context;
}

Expand Down Expand Up @@ -62,6 +73,14 @@ class Context {
return this._flags.get(key);
}

persist() {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(this.allFlags));
}

resetPersistence() {
window.localStorage.removeItem(STORAGE_KEY);
}

get allFlags() {
let allFlags = {};

Expand All @@ -76,6 +95,11 @@ class Context {
return isNone(this.client);
}

get persisted() {
let persisted = window.localStorage.getItem(STORAGE_KEY);
return persisted ? JSON.parse(persisted) : undefined;
}

get client() {
return this._client;
}
Expand All @@ -93,5 +117,6 @@ export {
getCurrentContext,
removeCurrentContext,
setCurrentContext,
setPersistedFlags,
Context as default,
};
34 changes: 33 additions & 1 deletion tests/unit/-sdk/context-test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { module, test } from 'qunit';

import Context from 'ember-launch-darkly/-sdk/context';
import Context, { setPersistedFlags } from 'ember-launch-darkly/-sdk/context';

module('Unit | SDK | Context', function () {
test('constructor', function (assert) {
Expand Down Expand Up @@ -156,4 +156,36 @@ module('Unit | SDK | Context', function () {
});
assert.deepEqual(new Context({}, client).user, { key: 'foo' });
});

module('#persistence', function (innerHooks) {
innerHooks.afterEach(function () {
window.localStorage.removeItem('ember-launch-darkly');
});

test('#persist / persisted', function (assert) {
let context = new Context({ foo: true, bar: false });
context.persist();

assert.deepEqual(
context.persisted,
{ foo: true, bar: false },
'Flags persisted in local storage'
);
});

test('#setPersistedFlags', function (assert) {
window.localStorage.setItem(
'ember-launch-darkly',
JSON.stringify({ foo: true, bar: false })
);
let context = new Context({ foo: false, bar: true });
setPersistedFlags(context);

assert.deepEqual(
context.allFlags,
{ foo: true, bar: false },
'Persisted flags were set to context'
);
});
});
});

0 comments on commit 5743087

Please sign in to comment.