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: added support for forceRefresh cache in invokeAPI #992

Merged
merged 3 commits into from
Jan 17, 2025
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
7 changes: 7 additions & 0 deletions .changeset/tidy-pants-kiss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@ensembleui/react-framework": patch
"@ensembleui/react-kitchen-sink": patch
"@ensembleui/react-runtime": patch
---

Added support for bypassCache cache in invokeAPI
3 changes: 1 addition & 2 deletions apps/kitchen-sink/src/ensemble/screens/home.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -504,8 +504,7 @@ API:

getDummyProducts:
method: GET
cache: true
cacheTime: 10
cacheExpirySeconds: 10
uri: https://randomuser.me/api/?results=1

getDummyNumbers:
Expand Down
9 changes: 7 additions & 2 deletions packages/framework/src/api/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
EnsembleActionHookResult,
EnsembleMockResponse,
EnsembleSocketModel,
InvokeAPIOptions,
} from "../shared";
import { screenDataAtom, type ScreenContextDefinition } from "../state";
import { isUsingMockResponse } from "../appConfig";
Expand All @@ -18,6 +19,7 @@ export const invokeAPI = async (
context?: { [key: string]: unknown },
evaluatedMockResponse?: string | EnsembleMockResponse,
setter?: Setter,
options?: InvokeAPIOptions,
): Promise<Response | undefined> => {
const api = screenContext.model?.apis?.find(
(model) => model.name === apiName,
Expand All @@ -44,7 +46,7 @@ export const invokeAPI = async (
setter(screenDataAtom, update);
}

// If mock resposne does not exist, fetch the data directly from the API
// If mock response does not exist, fetch the data directly from the API
const useMockResponse =
has(api, "mockResponse") && isUsingMockResponse(screenContext.app?.id);

Expand All @@ -62,7 +64,10 @@ export const invokeAPI = async (
useMockResponse,
},
),
staleTime: api.cacheExpirySeconds ? api.cacheExpirySeconds * 1000 : 0,
staleTime:
api.cacheExpirySeconds && !options?.bypassCache
? api.cacheExpirySeconds * 1000
: 0,
});

if (setter) {
Expand Down
3 changes: 3 additions & 0 deletions packages/framework/src/hooks/useCommandCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
import type {
EnsembleScreenModel,
EnsembleWidget,
InvokeAPIOptions,
NavigateExternalScreen,
NavigateModalScreenAction,
NavigateScreenAction,
Expand Down Expand Up @@ -98,6 +99,7 @@ export const useCommandCallback = <
invokeAPI: async (
apiName: string,
apiInputs?: { [key: string]: unknown },
options?: InvokeAPIOptions,
) =>
invokeAPI(
apiName,
Expand All @@ -113,6 +115,7 @@ export const useCommandCallback = <
},
undefined,
set,
options,
),
navigateExternalScreen: (url: NavigateExternalScreen) =>
navigateExternalScreen(url),
Expand Down
6 changes: 6 additions & 0 deletions packages/framework/src/shared/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export interface InvokeAPIAction {
name: string;
/** Specify the key/value pairs to pass into the API */
inputs?: { [key: string]: Expression<unknown> };
/** Forcefully clears the cache for this API invocation */
bypassCache?: boolean;
/** execute an Action upon successful completion of the API */
onResponse?: EnsembleAction;
/** execute an Action upon error */
Expand Down Expand Up @@ -219,3 +221,7 @@ export type EnsembleAction =
| { messageSocket?: SendSocketMessageAction }
| { disconnectSocket?: DisconnectSocketAction }
| { dispatchEvent?: DispatchEventAction };

export interface InvokeAPIOptions {
bypassCache?: boolean;
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ const wrapper: React.FC<React.PropsWithChildren> = ({ children }) => (
uri: "https://dummyjson.com/products?skip=${skip}&limit=${limit}",
inputs: ["skip", "limit"],
},
{
name: "getDummyUser",
method: "GET",
uri: "https://randomuser.me/api/?results=1",
cacheExpirySeconds: 120,
},
],
}}
>
Expand Down Expand Up @@ -111,6 +117,37 @@ test("call ensemble.invokeAPI", async () => {
expect(execResult).toBe(apiConfig.limit);
});

test("call ensemble.invokeAPI with bypassCache", async () => {
const { result: withoutForce } = renderHook(
() =>
useExecuteCode(
"ensemble.invokeAPI('getDummyUser', null).then((res) => res.body.results[0].email)",
),
{ wrapper },
);

const { result: withForce } = renderHook(
() =>
useExecuteCode(
"ensemble.invokeAPI('getDummyUser', null, { bypassCache: true }).then((res) => res.body.results[0].email)",
),
{ wrapper },
);

let withoutForceInitialResult;
let withoutForceResult;
let withForceResult;

await act(async () => {
withoutForceInitialResult = await withoutForce.current?.callback();
withoutForceResult = await withoutForce.current?.callback();
withForceResult = await withForce.current?.callback();
});

expect(withoutForceInitialResult).toBe(withoutForceResult);
expect(withForceResult).not.toBe(withoutForceResult);
});

test.todo("populates application invokables");

test.todo("resolves values in order of scoping");
67 changes: 67 additions & 0 deletions packages/runtime/src/runtime/hooks/__tests__/useInvokeApi.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -270,3 +270,70 @@ test("after API response modal should close", async () => {
expect(triggerAPIButton).not.toBeInTheDocument();
});
});

test("fetch API with force cache clear", async () => {
fetchMock.mockResolvedValue({ body: { data: "foobar" } });

render(
<EnsembleScreen
screen={{
name: "test_force_cache_clear",
id: "test_force_cache_clear",
body: {
name: "Column",
properties: {
children: [
{
name: "Button",
properties: {
label: "Without Force",
onTap: { invokeAPI: { name: "testForceCache" } },
},
},
{
name: "Button",
properties: {
label: "With Force",
onTap: {
invokeAPI: {
name: "testForceCache",
bypassCache: true,
},
},
},
},
],
},
},
apis: [
{
name: "testForceCache",
method: "GET",
cacheExpirySeconds: 60,
},
],
}}
/>,
{ wrapper: BrowserRouterWrapper },
);

const withoutForce = screen.getByText("Without Force");
fireEvent.click(withoutForce);

await waitFor(() => {
expect(fetchMock).toHaveBeenCalledTimes(1);
});

fireEvent.click(withoutForce);

await waitFor(() => {
expect(fetchMock).toHaveBeenCalledTimes(1);
});

const withForce = screen.getByText("With Force");
fireEvent.click(withForce);

await waitFor(() => {
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});
7 changes: 4 additions & 3 deletions packages/runtime/src/runtime/hooks/useEnsembleAction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,10 @@ export const useInvokeAPI: EnsembleActionHook<InvokeAPIAction> = (action) => {
useMockResponse,
},
),
staleTime: currentApi.cacheExpirySeconds
? currentApi.cacheExpirySeconds * 1000
: 0,
staleTime:
currentApi.cacheExpirySeconds && !action.bypassCache
? currentApi.cacheExpirySeconds * 1000
: 0,
});

setData(currentApi.name, response);
Expand Down
Loading