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

Added Custom Headers Logic to Query #9458

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
44 changes: 39 additions & 5 deletions src/Utils/request/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,47 @@ import { getResponseBody } from "@/Utils/request/request";
import { QueryOptions, Route } from "@/Utils/request/types";
import { makeHeaders, makeUrl } from "@/Utils/request/utils";

/**
* Extend the QueryOptions interface to include customHeaders
* @template TBody - The type of the request body
*/
export interface QueryOptionsWithHeaders<TBody> extends QueryOptions<TBody> {
customHeaders?: Record<string, string>;
headers?: HeadersInit;
}
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider extending existing QueryOptions instead of creating a new interface.

The addition of QueryOptionsWithHeaders<TBody> introduces redundancy since headers have already been added to QueryOptions<TBody> in types.ts. You can simplify the code by using QueryOptions<TBody> directly and removing QueryOptionsWithHeaders<TBody>.

Apply this diff to remove the redundant interface:

-/**
- * Extend the QueryOptions interface to include customHeaders
- * @template TBody - The type of the request body
- */
-export interface QueryOptionsWithHeaders<TBody> extends QueryOptions<TBody> {
-  customHeaders?: Record<string, string>;
-  headers?: HeadersInit;
-}

And update the function signatures accordingly:

 async function queryRequest<TData, TBody>(
   { path, method, noAuth }: Route<TData, TBody>,
-  options?: QueryOptionsWithHeaders<TBody>,
+  options?: QueryOptions<TBody>,
 ): Promise<TData> { ... }

 export default function query<TData, TBody>(
   route: Route<TData, TBody>,
-  options?: QueryOptionsWithHeaders<TBody>,
+  options?: QueryOptions<TBody>,
 ): (params: { signal: AbortSignal }) => Promise<TData> { ... }

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixing it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@srijantrpth, thank you for fixing it!


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!


// Function to sanitize custom headers
const sanitizeHeaders = (headers: Record<string, string>) => {
const sanitized: Record<string, string> = {};
for (const [key, value] of Object.entries(headers)) {
// Ensure header names follow RFC 7230 and values are safe
if (
/^[!#$%&'*+-.^_`|~0-9a-zA-Z]+$/.test(key) &&
typeof value === "string" && // Changed 'string' to "string"
!value.includes("\n") && // Changed '\n' to "\n"
!value.includes("\r")
) {
// Changed '\r' to "\r"
sanitized[key] = value;
}
}
return sanitized;
};

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

// Merge default headers with sanitized custom headers
const defaultHeaders = makeHeaders(noAuth ?? false);
const customHeaders = sanitizeHeaders(options?.customHeaders || {});
const headers = { ...defaultHeaders, ...customHeaders }; // Merging headers manually

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

Expand Down Expand Up @@ -45,12 +77,14 @@ async function queryRequest<TData, TBody>(

/**
* Creates a TanStack Query compatible request function
* @template TData - The type of the response data
* @template TBody - The type of the request body
*/
export default function query<TData, TBody>(
route: Route<TData, TBody>,
options?: QueryOptions<TBody>,
) {
return ({ signal }: { signal: AbortSignal }) => {
options?: QueryOptionsWithHeaders<TBody>,
): (params: { signal: AbortSignal }) => Promise<TData> {
return ({ signal }) => {
return queryRequest(route, { ...options, signal });
};
}
1 change: 1 addition & 0 deletions src/Utils/request/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export interface QueryOptions<TBody = unknown> {
body?: TBody;
silent?: boolean;
signal?: AbortSignal;
headers?: HeadersInit;
}

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

export function makeHeaders(noAuth: boolean) {
export function makeHeaders(noAuth: boolean, additionalHeaders?: HeadersInit) {
const headers = new Headers({
"Content-Type": "application/json",
Accept: "application/json",
...additionalHeaders,
srijantrpth marked this conversation as resolved.
Show resolved Hide resolved
});

if (!noAuth) {
const token = getAuthorizationHeader();
const token = localStorage.getItem(LocalStorageKeys.accessToken);

if (token) {
headers.append("Authorization", token);
headers.append("Authorization", `Bearer ${token}`);
srijantrpth marked this conversation as resolved.
Show resolved Hide resolved
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