📝(frontend) Update documentation
Improve and add jsdoc. Signed-off-by: Zorin95670 <moittie.vincent@gmail.com>
This commit is contained in:
@@ -1,17 +1,39 @@
|
||||
/**
|
||||
* Generic interface for representing an API error structure.
|
||||
*
|
||||
* @template T - Optional type of additional data returned with the error.
|
||||
*/
|
||||
interface IAPIError<T = unknown> {
|
||||
/** HTTP status code or API-defined error code */
|
||||
status: number;
|
||||
/** Optional list of error causes (e.g., validation issues) */
|
||||
cause?: string[];
|
||||
/** Optional extra data provided with the error */
|
||||
data?: T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom error class for representing API errors.
|
||||
* Extends the native Error object with additional context such as HTTP status,
|
||||
* causes, and extra data returned by the API.
|
||||
*
|
||||
* @template T - Optional type of the `data` field
|
||||
*/
|
||||
export class APIError<T = unknown> extends Error implements IAPIError<T> {
|
||||
public status: IAPIError['status'];
|
||||
public cause?: IAPIError['cause'];
|
||||
public data?: IAPIError<T>['data'];
|
||||
|
||||
/**
|
||||
* Constructs a new APIError instance.
|
||||
*
|
||||
* @param message - The human-readable error message.
|
||||
* @param status - The HTTP status code or equivalent.
|
||||
* @param cause - (Optional) List of strings describing error causes.
|
||||
* @param data - (Optional) Any additional data returned by the API.
|
||||
*/
|
||||
constructor(message: string, { status, cause, data }: IAPIError<T>) {
|
||||
super(message);
|
||||
|
||||
this.name = 'APIError';
|
||||
this.status = status;
|
||||
this.cause = cause;
|
||||
@@ -19,6 +41,12 @@ export class APIError<T = unknown> extends Error implements IAPIError<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for checking if a value is an instance of APIError.
|
||||
*
|
||||
* @param error - The value to check.
|
||||
* @returns True if the value is an instance of APIError.
|
||||
*/
|
||||
export const isAPIError = (error: unknown): error is APIError => {
|
||||
return error instanceof APIError;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
/**
|
||||
* Returns the base URL for the backend API.
|
||||
*
|
||||
* Priority:
|
||||
* 1. Uses NEXT_PUBLIC_API_ORIGIN from environment variables if defined.
|
||||
* 2. Falls back to the browser's window.location.origin if in a browser environment.
|
||||
* 3. Defaults to an empty string if executed in a non-browser environment without the env variable.
|
||||
*
|
||||
* @returns The backend base URL as a string.
|
||||
*/
|
||||
export const backendUrl = () =>
|
||||
process.env.NEXT_PUBLIC_API_ORIGIN ||
|
||||
(typeof window !== 'undefined' ? window.location.origin : '');
|
||||
|
||||
/**
|
||||
* Constructs the full base API URL, including the versioned path (e.g., `/api/v1.0/`).
|
||||
*
|
||||
* @param apiVersion - The version of the API (defaults to '1.0').
|
||||
* @returns The full versioned API base URL as a string.
|
||||
*/
|
||||
export const baseApiUrl = (apiVersion: string = '1.0') =>
|
||||
`${backendUrl()}/api/v${apiVersion}/`;
|
||||
|
||||
@@ -22,9 +22,17 @@ export type DefinedInitialDataInfiniteOptionsAPI<
|
||||
>;
|
||||
|
||||
/**
|
||||
* @param param Used for infinite scroll pagination
|
||||
* @param queryConfig
|
||||
* @returns
|
||||
* Custom React hook that wraps React Query's `useInfiniteQuery` for paginated API requests.
|
||||
*
|
||||
* @template T - Type of the request parameters.
|
||||
* @template Q - Type of the API response, which must include an optional `next` field for pagination.
|
||||
*
|
||||
* @param {string} key - Unique key to identify the query in the cache.
|
||||
* @param {(props: T & { page: number }) => Promise<Q>} api - Function that fetches paginated data from the API. It receives the params merged with a page number.
|
||||
* @param {T} param - Static parameters to send with every API request (excluding the page number).
|
||||
* @param {DefinedInitialDataInfiniteOptionsAPI<Q>} [queryConfig] - Optional configuration passed to `useInfiniteQuery` (e.g., stale time, cache time).
|
||||
*
|
||||
* @returns Return value of `useInfiniteQuery`, including data, loading state, fetchNextPage, etc.
|
||||
*/
|
||||
export const useAPIInfiniteQuery = <T, Q extends { next?: APIList<Q>['next'] }>(
|
||||
key: string,
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
/**
|
||||
* Generic interface representing a paginated API response.
|
||||
*
|
||||
* Commonly used for endpoints that return list results with pagination metadata.
|
||||
*
|
||||
* @template T - The type of items in the `results` array.
|
||||
*/
|
||||
export interface APIList<T> {
|
||||
/** Total number of items across all pages */
|
||||
count: number;
|
||||
|
||||
/** URL to the next page of results, if available (can be null or undefined) */
|
||||
next?: string | null;
|
||||
|
||||
/** URL to the previous page of results, if available (can be null or undefined) */
|
||||
previous?: string | null;
|
||||
|
||||
/** The list of items for the current page */
|
||||
results: T[];
|
||||
}
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
/**
|
||||
* Extracts error information from an HTTP `Response` object.
|
||||
*
|
||||
* This is typically used to parse structured error responses from an API
|
||||
* and normalize them into a consistent format with `status`, `cause`, and optional `data`.
|
||||
*
|
||||
* @param response - The HTTP response object from `fetch()`.
|
||||
* @param data - Optional custom data to include with the error output.
|
||||
* @returns An object containing:
|
||||
* - `status`: HTTP status code from the response
|
||||
* - `cause`: A flattened list of error messages, or undefined if no body
|
||||
* - `data`: The optional data passed in
|
||||
*/
|
||||
export const errorCauses = async (response: Response, data?: unknown) => {
|
||||
const errorsBody = (await response.json()) as Record<
|
||||
string,
|
||||
@@ -18,7 +31,11 @@ export const errorCauses = async (response: Response, data?: unknown) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the CSRF token from the document's cookies.
|
||||
* Retrieves the CSRF token from the browser's cookies.
|
||||
*
|
||||
* Assumes the CSRF token is stored as a cookie named "csrftoken".
|
||||
*
|
||||
* @returns The CSRF token string if found, otherwise `undefined`.
|
||||
*/
|
||||
export function getCSRFToken() {
|
||||
return document.cookie
|
||||
|
||||
@@ -19,9 +19,16 @@ export function downloadFile(blob: Blob, filename: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert SVG to PNG
|
||||
* @param svgText - The SVG text to convert
|
||||
* @returns The PNG data URL
|
||||
* Converts an SVG string into a PNG image and returns it as a data URL.
|
||||
*
|
||||
* This function creates a canvas, parses the SVG, calculates the appropriate height
|
||||
* to preserve the aspect ratio, and renders the SVG onto the canvas using Canvg.
|
||||
*
|
||||
* @param {string} svgText - The raw SVG markup to convert.
|
||||
* @param {number} width - The desired width of the output PNG (height is auto-calculated to preserve aspect ratio).
|
||||
* @returns {Promise<string>} A Promise that resolves to a PNG image encoded as a base64 data URL.
|
||||
*
|
||||
* @throws Will throw an error if the canvas context cannot be initialized.
|
||||
*/
|
||||
export async function convertSvgToPng(svgText: string, width: number) {
|
||||
// Create a canvas and render the SVG onto it
|
||||
|
||||
@@ -38,11 +38,15 @@ setCacheNameDetails({
|
||||
});
|
||||
|
||||
/**
|
||||
* In development, use NetworkFirst strategy, in production use CacheFirst strategy
|
||||
* We will be able to test the application in development without having to clear the cache.
|
||||
* @param url
|
||||
* @param options
|
||||
* @returns strategy
|
||||
* Chooses the appropriate caching strategy based on the environment and request context.
|
||||
*
|
||||
* - In **development**, or for **API requests**, or **HTML pages**, it returns a `NetworkFirst` strategy
|
||||
* to prioritize fresh responses and ease debugging without needing to clear caches.
|
||||
* - In **production** (for non-API, non-HTML content), it returns a `CacheFirst` strategy
|
||||
* to favor performance and offline access.
|
||||
*
|
||||
* @param {NetworkFirstOptions | StrategyOptions} [options] - Configuration options for the caching strategy.
|
||||
* @returns {NetworkFirst | CacheFirst} The selected Workbox strategy instance.
|
||||
*/
|
||||
const getStrategy = (
|
||||
options?: NetworkFirstOptions | StrategyOptions,
|
||||
|
||||
@@ -17,8 +17,6 @@ import { logger } from '../utils';
|
||||
/**
|
||||
* init the collaboration server.
|
||||
*
|
||||
* @param port - The port on which the server listens.
|
||||
* @param serverSecret - The secret key for API authentication.
|
||||
* @returns An object containing the Express app, Hocuspocus server, and HTTP server instance.
|
||||
*/
|
||||
export const initServer = () => {
|
||||
|
||||
Reference in New Issue
Block a user