Skip to content

Commit

Permalink
Merge branch 'staging' into telemetry3
Browse files Browse the repository at this point in the history
  • Loading branch information
RickCarlino committed Oct 29, 2019
2 parents e7af24d + 9a09b75 commit f9aa0c8
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
6 changes: 5 additions & 1 deletion frontend/open_farm/__tests__/cached_crop_test.ts
Expand Up @@ -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 () => {
Expand Down
5 changes: 4 additions & 1 deletion frontend/open_farm/cached_crop.ts
Expand Up @@ -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) =>
Expand All @@ -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));
Expand Down

0 comments on commit f9aa0c8

Please sign in to comment.