remove duplicate crop icon requests

pull/1541/head
gabrielburnworth 2019-10-28 11:24:12 -07:00
parent 3152d46f55
commit e065834e95
2 changed files with 9 additions and 2 deletions

View File

@ -13,20 +13,24 @@ const mockResponse: { promise: Promise<{}> } = {
};
jest.mock("axios", () => ({
get: () => mockResponse.promise
get: jest.fn(() => mockResponse.promise)
}));
jest.unmock("../cached_crop");
import { cachedCrop } from "../cached_crop";
import axios from "axios";
import { times } from "lodash";
describe("cachedIcon()", () => {
it("does an HTTP request if the icon can't be found locally", async () => {
times(10, () => cachedCrop("lettuce"));
const item1 = await cachedCrop("lettuce");
expect(item1.svg_icon).toContain("<svg>Wow</svg>");
const item2 = await cachedCrop("lettuce");
expect(item2.slug).toBe(item1.slug);
expect(item2.svg_icon).toBe(item1.svg_icon);
expect(item2.spread).toBe(undefined);
expect(axios.get).toHaveBeenCalledTimes(1);
});
it("handles unexpected responses from OpenFarm", async () => {

View File

@ -37,7 +37,8 @@ function localStorageIconSet(icon: OFIcon): void {
* and the garlic icon is not cached locally, and you try to render 10 garlic
* icons in the first 100ms, and HTTP requests take more than 100ms, you will
* end up performing 10 HTTP requests at application start time. Not very
* efficient */
* efficient.
* SOLUTION: Keep a record of open requests to avoid duplicate requests. */
const promiseCache: Dictionary<Promise<Readonly<OFCropAttrs>>> = {};
const cacheTheIcon = (slug: string) =>
@ -60,6 +61,8 @@ const cacheTheIcon = (slug: string) =>
function HTTPIconFetch(slug: string) {
const url = OpenFarmAPI.OFBaseURL + slug;
// Avoid duplicate requests.
if (promiseCache[url]) { return promiseCache[url]; }
promiseCache[url] = axios
.get<OFCropResponse>(url)
.then(cacheTheIcon(slug), cacheTheIcon(slug));