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 cache in API call #918

Merged
merged 7 commits into from
Nov 27, 2024
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/early-dryers-drum.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 cache in API call
28 changes: 28 additions & 0 deletions apps/kitchen-sink/src/ensemble/screens/home.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,28 @@ View:
Text:
text: ${'world' + p + ensemble.storage.get('iconName')}

- Text:
text: ${ensemble.storage.get('email')}
- Button:
label: Call Action
onTap:
invokeAPI:
name: getDummyProducts
onResponse:
executeCode: |
ensemble.storage.set('email', response.body.results[0].email)
ensemble.storage.set('emails', [...ensemble.storage.get("emails"),response.body.results[0].email])
console.log('getData', response.body.results[0].email, ensemble.storage.get('emails'));
- Column:
item-template:
data: '${ensemble.storage.get("emails")}'
name: email
template:
Column:
children:
- Text:
text: ${email}

Global:
scriptName: test.js

Expand Down Expand Up @@ -417,6 +439,12 @@ API:
method: GET
uri: https://httpstat.us/500

getDummyProducts:
method: GET
cache: true
cacheTime: 10
sagardspeed2 marked this conversation as resolved.
Show resolved Hide resolved
uri: https://randomuser.me/api/?results=1

getDummyNumbers:
method: GET
uri: https://661e111b98427bbbef034208.mockapi.io/number?limit=10
Expand Down
1 change: 1 addition & 0 deletions packages/framework/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"react-dom": "^18.2.0"
},
"devDependencies": {
"@tanstack/react-query": "^5.61.0",
"@testing-library/react": "^13.4.0",
"@types/lodash-es": "^4.17.8",
"@types/react": "^18.2.21",
Expand Down
38 changes: 25 additions & 13 deletions packages/framework/src/api/data.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { has, set } from "lodash-es";
import type { Setter } from "jotai";
import { DataFetcher, type WebSocketConnection, type Response } from "../data";
import { error } from "../shared";
import { error, generateAPIHash, queryClient } from "../shared";
import type {
EnsembleActionHookResult,
EnsembleMockResponse,
Expand All @@ -23,6 +23,12 @@ export const invokeAPI = async (
(model) => model.name === apiName,
);

const hash = generateAPIHash({
api: api?.name,
inputs: apiInputs,
screen: screenContext.model?.id,
});

if (!api) {
error(`Unable to find API with name ${apiName}`);
return;
Expand All @@ -42,23 +48,29 @@ export const invokeAPI = async (
// If mock resposne does not exist, fetch the data directly from the API
const useMockResponse =
has(api, "mockResponse") && isUsingMockResponse(screenContext.app?.id);
const res = await DataFetcher.fetch(
api,
{ ...apiInputs, ...context },
{
mockResponse: mockResponse(
evaluatedMockResponse ?? api.mockResponse,
useMockResponse,

const response = await queryClient.fetchQuery({
queryKey: [hash],
queryFn: () =>
DataFetcher.fetch(
api,
{ ...apiInputs, ...context },
{
mockResponse: mockResponse(
evaluatedMockResponse ?? api.mockResponse,
useMockResponse,
),
useMockResponse,
},
),
useMockResponse,
},
);
staleTime: api.cacheExpirySeconds ? api.cacheExpirySeconds * 1000 : 0,
});

if (setter) {
set(update, api.name, res);
set(update, api.name, response);
setter(screenDataAtom, { ...update });
}
return res;
return response;
};

export const handleConnectSocket = (
Expand Down
11 changes: 11 additions & 0 deletions packages/framework/src/shared/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { QueryClient } from "@tanstack/react-query";

export const queryClient = new QueryClient();

export const generateAPIHash = (props: {
api: string | undefined;
inputs: { [key: string]: unknown } | undefined;
screen: string | undefined;
}): string => {
return JSON.stringify({ ...props });
};
1 change: 1 addition & 0 deletions packages/framework/src/shared/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from "./actions";
export * from "./models";
export * from "./dto";
export * from "./common";
export * from "./api";
1 change: 1 addition & 0 deletions packages/framework/src/shared/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export interface EnsembleAPIModel {
url?: string;
method: "GET" | "POST" | "PUT" | "PATCH";
headers?: { [key: string]: string | number | boolean };
cacheExpirySeconds?: number;
body?: string | object;
onResponse?: EnsembleAction;
onError?: EnsembleAction;
Expand Down
1 change: 1 addition & 0 deletions packages/runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@mui/material": "^5.14.9",
"@mui/x-date-pickers": "^6.18.3",
"@react-oauth/google": "^0.12.1",
"@tanstack/react-query": "^5.61.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@turbo/gen": "^1.10.12",
Expand Down
12 changes: 8 additions & 4 deletions packages/runtime/src/EnsembleApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ import type {
import {
ApplicationContextProvider,
EnsembleParser,
queryClient,
} from "@ensembleui/react-framework";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { ToastContainer } from "react-toastify";
import { injectStyle } from "react-toastify/dist/inject-style";
import { QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "./ThemeProvider";
import { EnsembleEntry } from "./runtime/entry";
import { EnsembleScreen } from "./runtime/screen";
Expand Down Expand Up @@ -119,10 +121,12 @@ export const EnsembleApp: React.FC<EnsembleAppProps> = ({
app={app}
environmentOverrides={environmentOverrides}
>
<ThemeProvider>
<RouterProvider router={router} />
<ToastContainer />
</ThemeProvider>
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<RouterProvider router={router} />
<ToastContainer />
</ThemeProvider>
</QueryClientProvider>
</ApplicationContextProvider>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
} from "@testing-library/react";
import "@testing-library/jest-dom";
import { BrowserRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { type ReactNode } from "react";
import { useActionGroup } from "../useEnsembleAction";
import { createCustomWidget } from "../../customWidget";
import { Button } from "../../../widgets";
Expand All @@ -26,8 +28,27 @@ jest.mock("@ensembleui/react-framework", () => ({
},
}));

const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});

interface BrowserRouterProps {
children: ReactNode;
}

const BrowserRouterWrapper = ({ children }: BrowserRouterProps) => (
<QueryClientProvider client={queryClient}>
<BrowserRouter>{children}</BrowserRouter>
</QueryClientProvider>
);

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

test("execute multiple actions", () => {
Expand All @@ -45,7 +66,7 @@ test("execute multiple actions", () => {
],
}),
{
wrapper: BrowserRouter,
wrapper: BrowserRouterWrapper,
},
);

Expand Down Expand Up @@ -142,7 +163,7 @@ test("fetch multiple APIs", async () => {
}}
/>,
{
wrapper: BrowserRouter,
wrapper: BrowserRouterWrapper,
},
);

Expand Down Expand Up @@ -203,7 +224,7 @@ test("mutate multiple storage variables", () => {
/>
</>,
{
wrapper: BrowserRouter,
wrapper: BrowserRouterWrapper,
},
);

Expand Down
Loading