From f3d593bc1e3e377ed432b99f54a826e7a4838dee Mon Sep 17 00:00:00 2001 From: Andrew Henry Date: Thu, 8 Oct 2020 20:30:23 -0700 Subject: [PATCH] Cache gets (#3437) * Cache gets * Added test --- src/api/objects/ObjectAPI.js | 16 +++++++++++++++- src/api/objects/ObjectAPISpec.js | 12 +++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/api/objects/ObjectAPI.js b/src/api/objects/ObjectAPI.js index df8f5f060a..7fb21d89a5 100644 --- a/src/api/objects/ObjectAPI.js +++ b/src/api/objects/ObjectAPI.js @@ -47,6 +47,7 @@ define([ this.providers = {}; this.rootRegistry = new RootRegistry(); this.rootProvider = new RootObjectProvider.default(this.rootRegistry); + this.cache = {}; } /** @@ -154,6 +155,11 @@ define([ * has been saved, or be rejected if it cannot be saved */ ObjectAPI.prototype.get = function (identifier) { + let keystring = this.makeKeyString(identifier); + if (this.cache[keystring] !== undefined) { + return this.cache[keystring]; + } + identifier = utils.parseKeyString(identifier); const provider = this.getProvider(identifier); @@ -165,7 +171,15 @@ define([ throw new Error('Provider does not support get!'); } - return provider.get(identifier); + let objectPromise = provider.get(identifier); + + this.cache[keystring] = objectPromise; + + return objectPromise.then(result => { + delete this.cache[keystring]; + + return result; + }); }; ObjectAPI.prototype.delete = function () { diff --git a/src/api/objects/ObjectAPISpec.js b/src/api/objects/ObjectAPISpec.js index 973cc6744a..93de3378fb 100644 --- a/src/api/objects/ObjectAPISpec.js +++ b/src/api/objects/ObjectAPISpec.js @@ -30,9 +30,11 @@ describe("The Object API", () => { beforeEach(() => { mockProvider = jasmine.createSpyObj("mock provider", [ "create", - "update" + "update", + "get" ]); mockProvider.create.and.returnValue(Promise.resolve(true)); + mockProvider.get.and.returnValue(Promise.resolve(mockDomainObject)); objectAPI.addProvider(TEST_NAMESPACE, mockProvider); }); it("Calls 'create' on provider if object is new", () => { @@ -57,6 +59,14 @@ describe("The Object API", () => { expect(mockProvider.create).not.toHaveBeenCalled(); expect(mockProvider.update).not.toHaveBeenCalled(); }); + + it("Caches multiple requests for the same object", () => { + expect(mockProvider.get.calls.count()).toBe(0); + objectAPI.get(mockDomainObject.identifier); + expect(mockProvider.get.calls.count()).toBe(1); + objectAPI.get(mockDomainObject.identifier); + expect(mockProvider.get.calls.count()).toBe(1); + }); }); }); });