Add a `memoryLocalStore` implementation (#524)

Summary:
We can use this in tests. If need be, we can enhance this class to allow
simulating failures, low storage limits, etc., but just having a pure
implementation at all is all we need right now.

Test Plan:
Unit tests added.

wchargin-branch: memory-local-store
This commit is contained in:
William Chargin 2018-07-24 19:10:38 -07:00 committed by GitHub
parent d0906eed16
commit 0489ff8844
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,29 @@
// @flow
import {LocalStore} from "./localStore";
/*
* A completely in-memory `LocalStore` implementation that matches the
* happy path of browsers' `localStorage`: storage is always enabled and
* functioning, and there is no storage limit.
*/
export default class MemoryLocalStore implements LocalStore {
_data: Map<string, string>;
constructor(): void {
this._data = new Map();
}
get<T>(key: string, whenUnavailable: T): T {
const raw = this._data.get(key);
return raw == null ? whenUnavailable : JSON.parse(raw);
}
set(key: string, data: mixed): void {
this._data.set(key, JSON.stringify(data));
}
del(key: string): void {
this._data.delete(key);
}
}

View File

@ -0,0 +1,36 @@
// @flow
import MemoryLocalStore from "./memoryLocalStore";
describe("src/app/memoryLocalStore", () => {
it("stores simple values", () => {
const ls = new MemoryLocalStore();
ls.set("one", 1);
expect(ls.get("one")).toBe(1);
});
it("stores complex values", () => {
const ls = new MemoryLocalStore();
ls.set("stuff", [{a: ["one"]}, {b: ["two"]}]);
expect(ls.get("stuff")).toEqual([{a: ["one"]}, {b: ["two"]}]);
});
it("stores null", () => {
const ls = new MemoryLocalStore();
ls.set("one", null);
expect(ls.get("one")).toBe(null);
});
it("overwrites values", () => {
const ls = new MemoryLocalStore();
ls.set("questions", 5);
ls.set("questions", 3);
expect(ls.get("questions")).toBe(3);
});
it("provides `whenUnavailable` for absent values", () => {
const ls = new MemoryLocalStore();
const expected = Symbol();
expect(ls.get("wat", expected)).toBe(expected);
});
});