Skip to content

Commit

Permalink
Improvised query headers handling and extend QueryOptions interface
Browse files Browse the repository at this point in the history
  • Loading branch information
srijantrpth committed Dec 16, 2024
1 parent 9ca80e0 commit 0883fb4
Showing 1 changed file with 35 additions and 9 deletions.
44 changes: 35 additions & 9 deletions src/Utils/request/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,43 @@ import { getResponseBody } from "@/Utils/request/request";
import { QueryOptions, Route } from "@/Utils/request/types";
import { makeHeaders, makeUrl } from "@/Utils/request/utils";

declare module "@tanstack/react-query" {
interface Register {
defaultError: QueryError;
}
/**
* 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;
}

// 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)}`;

const headers = makeHeaders(noAuth ?? false, options?.headers);
// 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,
Expand Down Expand Up @@ -53,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 });
};
}

0 comments on commit 0883fb4

Please sign in to comment.