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

Adds useMutation compatible utility function and other abstractions #9463

Merged
merged 7 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
8 changes: 6 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
MutationCache,
QueryCache,
QueryClient,
QueryClientProvider,
Expand All @@ -16,7 +17,7 @@ import AuthUserProvider from "@/Providers/AuthUserProvider";
import HistoryAPIProvider from "@/Providers/HistoryAPIProvider";
import Routers from "@/Routers";
import { FeatureFlagsProvider } from "@/Utils/featureFlags";
import { handleQueryError } from "@/Utils/request/errorHandler";
import { handleHttpError } from "@/Utils/request/errorHandler";

import { PubSubProvider } from "./Utils/pubsubContext";

Expand All @@ -29,7 +30,10 @@ const queryClient = new QueryClient({
},
},
queryCache: new QueryCache({
onError: handleQueryError,
onError: handleHttpError,
}),
mutationCache: new MutationCache({
onError: handleHttpError,
}),
});

Expand Down
82 changes: 80 additions & 2 deletions src/Utils/request/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,12 @@ function FacilityDetails({ id }: { id: string }) {
- Integrates with our global error handling.

```typescript
interface QueryOptions {
interface APICallOptions {
pathParams?: Record<string, string>; // URL parameters
queryParams?: Record<string, string>; // Query string parameters
queryParams?: QueryParams; // Query string parameters
body?: TBody; // Request body
silent?: boolean; // Suppress error notifications
headers?: HeadersInit; // Additional headers
}

// Basic usage
Expand Down Expand Up @@ -100,6 +102,82 @@ are automatically handled.

Use the `silent: true` option to suppress error notifications for specific queries.

## Using Mutations with TanStack Query

For data mutations, we provide a `mutate` utility that works seamlessly with TanStack Query's `useMutation` hook.

```tsx
import { useMutation } from "@tanstack/react-query";
import mutate from "@/Utils/request/mutate";

function CreatePrescription({ consultationId }: { consultationId: string }) {
const { mutate: createPrescription, isPending } = useMutation({
mutationFn: mutate(MedicineRoutes.createPrescription, {
pathParams: { consultationId },
}),
onSuccess: () => {
toast.success("Prescription created successfully");
},
});

return (
<Button
onClick={() => createPrescription({ medicineId: "123", dosage: "1x daily" })}
disabled={isPending}
>
Create Prescription
</Button>
);
}

// With path parameters and complex payload
function UpdatePatient({ patientId }: { patientId: string }) {
const { mutate: updatePatient } = useMutation({
mutationFn: mutate(PatientRoutes.update, {
pathParams: { id: patientId },
silent: true // Optional: suppress error notifications
})
});

const handleSubmit = (data: PatientData) => {
updatePatient(data);
};

return <PatientForm onSubmit={handleSubmit} />;
}
```

### mutate

`mutate` is our wrapper around the API call functionality that works with TanStack Query's `useMutation`. It:
- Handles request body serialization
- Sets appropriate headers
- Integrates with our global error handling
- Provides TypeScript type safety for your mutation payload

```typescript
interface APICallOptions {
pathParams?: Record<string, string>; // URL parameters
queryParams?: QueryParams; // Query string parameters
body?: TBody; // Request body
silent?: boolean; // Suppress error notifications
headers?: HeadersInit; // Additional headers
}

// Basic usage
useMutation({
mutationFn: mutate(routes.users.create)
});

// With parameters
useMutation({
mutationFn: mutate(routes.users.update, {
pathParams: { id },
silent: true // Optional: suppress error notifications
})
});
```

## Migration Guide & Reference

### Understanding the Transition
Expand Down
10 changes: 5 additions & 5 deletions src/Utils/request/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { navigate } from "raviger";

import * as Notifications from "@/Utils/Notifications";
import { QueryError } from "@/Utils/request/queryError";
import { HTTPError } from "@/Utils/request/types";

export function handleQueryError(error: Error) {
export function handleHttpError(error: Error) {
if (error.name === "AbortError") {
return;
}

if (!(error instanceof QueryError)) {
if (!(error instanceof HTTPError)) {
Notifications.Error({ msg: error.message || "Something went wrong!" });
return;
}
Expand All @@ -34,7 +34,7 @@ export function handleQueryError(error: Error) {
});
}

function isSessionExpired(error: QueryError["cause"]) {
function isSessionExpired(error: HTTPError["cause"]) {
return (
// If Authorization header is not valid
error?.code === "token_not_valid" ||
Expand All @@ -49,6 +49,6 @@ function handleSessionExpired() {
}
}

function isBadRequest(error: QueryError) {
function isBadRequest(error: HTTPError) {
return error.status === 400 || error.status === 406;
}
26 changes: 26 additions & 0 deletions src/Utils/request/mutate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { callApi } from "@/Utils/request/query";
import { APICallOptions, Route } from "@/Utils/request/types";

/**
* Creates a TanStack Query compatible mutation function.
*
* Example:
* ```tsx
* const { mutate: createPrescription, isPending } = useMutation({
* mutationFn: mutate(MedicineRoutes.createPrescription, {
* pathParams: { consultationId },
* }),
* onSuccess: () => {
* toast.success(t("medication_request_prescribed"));
* },
* });
* ```
*/
export default function mutate<TData, TBody>(
route: Route<TData, TBody>,
options?: APICallOptions<TBody>,
) {
return (variables: TBody) => {
return callApi(route, { ...options, body: variables });
};
}
31 changes: 22 additions & 9 deletions src/Utils/request/query.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import careConfig from "@careConfig";

import { QueryError } from "@/Utils/request/queryError";
import { getResponseBody } from "@/Utils/request/request";
import { QueryOptions, Route } from "@/Utils/request/types";
import { APICallOptions, HTTPError, Route } from "@/Utils/request/types";
import { makeHeaders, makeUrl } from "@/Utils/request/utils";

async function queryRequest<TData, TBody>(
export async function callApi<TData, TBody>(
{ path, method, noAuth }: Route<TData, TBody>,
options?: QueryOptions<TBody>,
options?: APICallOptions<TBody>,
): Promise<TData> {
const url = `${careConfig.apiUrl}${makeUrl(path, options?.queryParams, options?.pathParams)}`;

const fetchOptions: RequestInit = {
method,
headers: makeHeaders(noAuth ?? false),
headers: makeHeaders(noAuth ?? false, options?.headers),
signal: options?.signal,
};

Expand All @@ -32,7 +31,7 @@ async function queryRequest<TData, TBody>(
const data = await getResponseBody<TData>(res);

if (!res.ok) {
throw new QueryError({
throw new HTTPError({
message: "Request Failed",
status: res.status,
silent: options?.silent ?? false,
Expand All @@ -44,13 +43,27 @@ async function queryRequest<TData, TBody>(
}

/**
* Creates a TanStack Query compatible request function
* Creates a TanStack Query compatible query function.
*
* Example:
* ```tsx
* const { data, isLoading } = useQuery({
* queryKey: ["prescription", consultationId],
* queryFn: query(MedicineRoutes.prescription, {
* pathParams: { consultationId },
* queryParams: {
* limit: 10,
* offset: 0,
* },
* }),
* });
* ```
*/
export default function query<TData, TBody>(
route: Route<TData, TBody>,
options?: QueryOptions<TBody>,
options?: APICallOptions<TBody>,
) {
return ({ signal }: { signal: AbortSignal }) => {
return queryRequest(route, { ...options, signal });
return callApi(route, { ...options, signal });
};
}
24 changes: 0 additions & 24 deletions src/Utils/request/queryError.ts

This file was deleted.

38 changes: 35 additions & 3 deletions src/Utils/request/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,44 @@ export interface RequestOptions<TData = unknown, TBody = unknown> {
silent?: boolean;
}

export interface QueryOptions<TBody = unknown> {
pathParams?: Record<string, string>;
queryParams?: Record<string, string>;
export interface APICallOptions<TBody = unknown> {
pathParams?: Record<string, string | number>;
queryParams?: QueryParams;
body?: TBody;
silent?: boolean;
signal?: AbortSignal;
headers?: HeadersInit;
}

type HTTPErrorCause = Record<string, unknown> | undefined;

export class HTTPError extends Error {
status: number;
silent: boolean;
cause?: HTTPErrorCause;

constructor({
message,
status,
silent,
cause,
}: {
message: string;
status: number;
silent: boolean;
cause?: Record<string, unknown>;
}) {
super(message, { cause });
this.status = status;
this.silent = silent;
this.cause = cause;
}
}

declare module "@tanstack/react-query" {
interface Register {
defaultError: HTTPError;
}
}

export interface PaginatedResponse<TItem> {
Expand Down
27 changes: 7 additions & 20 deletions src/Utils/request/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,33 +50,20 @@ const ensurePathNotMissingReplacements = (path: string) => {
}
};

export function makeHeaders(noAuth: boolean) {
const headers = new Headers({
"Content-Type": "application/json",
Accept: "application/json",
});
export function makeHeaders(noAuth: boolean, additionalHeaders?: HeadersInit) {
const headers = new Headers(additionalHeaders);

if (!noAuth) {
const token = getAuthorizationHeader();
headers.set("Content-Type", "application/json");
headers.append("Accept", "application/json");

if (token) {
headers.append("Authorization", token);
}
const jwtAccessToken = localStorage.getItem(LocalStorageKeys.accessToken);
if (jwtAccessToken && !noAuth) {
headers.append("Authorization", `Bearer ${jwtAccessToken}`);
}
rithviknishad marked this conversation as resolved.
Show resolved Hide resolved

return headers;
}

export function getAuthorizationHeader() {
const bearerToken = localStorage.getItem(LocalStorageKeys.accessToken);

if (bearerToken) {
return `Bearer ${bearerToken}`;
}

return null;
}

export function mergeRequestOptions<TData>(
options: RequestOptions<TData>,
overrides: RequestOptions<TData>,
Expand Down
Loading