Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Add Cache Wrapper helper to avoid dataset request duplication #64

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions superset-frontend/spec/javascripts/utils/cacheWrapper_spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { cacheWrapper } from 'src/utils/cacheWrapper';

describe('cacheWrapper', () => {
const fnResult = 'fnResult';
const fn = jest.fn<string, [number, number]>().mockReturnValue(fnResult);

let wrappedFn: (a: number, b: number) => string;

beforeEach(() => {
const cache = new Map<string, any>();
wrappedFn = cacheWrapper(fn, cache);
});

afterEach(() => {
jest.clearAllMocks();
});

it('calls fn with its arguments once when the key is not found', () => {
const returnedValue = wrappedFn(1, 2);

expect(returnedValue).toEqual(fnResult);
expect(fn).toBeCalledTimes(1);
expect(fn).toBeCalledWith(1, 2);
});

describe('subsequent calls', () => {
it('returns the correct value without fn being called multiple times', () => {
const returnedValue1 = wrappedFn(1, 2);
const returnedValue2 = wrappedFn(1, 2);

expect(returnedValue1).toEqual(fnResult);
expect(returnedValue2).toEqual(fnResult);
expect(fn).toBeCalledTimes(1);
});

it('fn is called multiple times for different arguments', () => {
wrappedFn(1, 2);
wrappedFn(1, 3);

expect(fn).toBeCalledTimes(2);
});
});

describe('with custom keyFn', () => {
let cache: Map<string, any>;

beforeEach(() => {
cache = new Map<string, any>();
wrappedFn = cacheWrapper(fn, cache, (...args) => `key-${args[0]}`);
});

it('saves fn result in cache under generated key', () => {
wrappedFn(1, 2);
expect(cache.get('key-1')).toEqual(fnResult);
});

it('subsequent calls with same generated key calls fn once, even if other arguments have changed', () => {
wrappedFn(1, 1);
wrappedFn(1, 2);
wrappedFn(1, 3);

expect(fn).toBeCalledTimes(1);
});
});
});
14 changes: 12 additions & 2 deletions superset-frontend/src/components/SupersetResourceSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
ClientErrorObject,
getClientErrorObject,
} from 'src/utils/getClientErrorObject';
import { cacheWrapper } from 'src/utils/cacheWrapper';

export type Value<V> = { value: V; label: string };

Expand All @@ -50,6 +51,15 @@ export interface SupersetResourceSelectProps<T = unknown, V = string> {
* If you're doing anything more complex than selecting a standard resource,
* we'll all be better off if you use AsyncSelect directly instead.
*/

const localCache = new Map<string, any>();

const cachedSupersetGet = cacheWrapper(
SupersetClient.get,
localCache,
({ endpoint }) => endpoint || '',
);

export default function SupersetResourceSelect<T, V>({
value,
initialId,
Expand All @@ -62,7 +72,7 @@ export default function SupersetResourceSelect<T, V>({
}: SupersetResourceSelectProps<T, V>) {
useEffect(() => {
if (initialId == null) return;
SupersetClient.get({
cachedSupersetGet({
endpoint: `/api/v1/${resource}/${initialId}`,
}).then(response => {
const { result } = response.json;
Expand All @@ -77,7 +87,7 @@ export default function SupersetResourceSelect<T, V>({
filters: [{ col: searchColumn, opr: 'ct', value: input }],
})
: rison.encode({ filter: value });
return SupersetClient.get({
return cachedSupersetGet({
endpoint: `/api/v1/${resource}/?q=${query}`,
}).then(
response => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { useChangeEffect } from 'src/common/hooks/useChangeEffect';
import { AsyncSelect } from 'src/components/Select';
import { useToasts } from 'src/messageToasts/enhancers/withToasts';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { cacheWrapper } from 'src/utils/cacheWrapper';
import { NativeFiltersForm } from './types';

type ColumnSelectValue = {
Expand All @@ -38,6 +39,14 @@ interface ColumnSelectProps {
onChange?: (value: ColumnSelectValue | null) => void;
}

const localCache = new Map<string, any>();

const cachedSupersetGet = cacheWrapper(
SupersetClient.get,
localCache,
({ endpoint }) => endpoint || '',
);

/** Special purpose AsyncSelect that selects a column from a dataset */
// eslint-disable-next-line import/prefer-default-export
export function ColumnSelect({
Expand All @@ -61,7 +70,7 @@ export function ColumnSelect({

function loadOptions() {
if (datasetId == null) return [];
return SupersetClient.get({
return cachedSupersetGet({
endpoint: `/api/v1/dataset/${datasetId}`,
}).then(
({ json: { result } }) => {
Expand Down
34 changes: 34 additions & 0 deletions superset-frontend/src/utils/cacheWrapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

export const cacheWrapper = <T extends Array<any>, U>(
fn: (...args: T) => U,
cache: Map<string, any>,
keyFn: (...args: T) => string = (...args: T) => JSON.stringify([...args]),
) => {
return (...args: T): U => {
const key = keyFn(...args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
};
};