NuxtN
Nuxt15mo ago
pook1574

Repository Pattern implementation attempt

import type { NitroFetchOptions } from "nitropack";
import type { IPaginationResponse } from "@/types/IPaginationResponse";
import type { DjangoPaginationQueryParams } from "@/types/DjangoPaginationQueryParams";
export abstract class BaseRepository<T> {
  protected abstract baseUrl: string;
  protected defaultFetch = $fetch; // Using Nuxt's global $fetch
  async getAllPaginated(
    queryParams: DjangoPaginationQueryParams,
    fetcher = this.defaultFetch
  ): Promise<IPaginationResponse<T>> {
    const options: NitroFetchOptions<"get"> = {
      method: "get", // Using GET method without body
    };
    const queryString = new URLSearchParams(
      Object.entries(queryParams).reduce((acc, [key, value]) => {
        acc[key] = String(value);
        return acc;
      }, {} as Record<string, string>)
    ).toString();
    const response = await fetcher<IPaginationResponse<T>>(
      `${this.baseUrl}?${queryString}`, // Append query string to base URL
      options
    );
    return response;
  }

  async create(payload: T, fetcher = this.defaultFetch): Promise<T> {
    const data = await fetcher<T>(this.baseUrl, {
      method: "POST",
      body: JSON.stringify(payload),
      headers: {
        "Content-Type": "application/json",
      },
    });
    return data;
  }

  async update(
    id: number,
    payload: T,
    fetcher = this.defaultFetch
  ): Promise<T> {
    const data = await fetcher<T>(`${this.baseUrl}/${id}`, {
      method: "PUT",
      body: JSON.stringify(payload),
      headers: {
        "Content-Type": "application/json",
      },
    });
    return data;
  }
  async save(
    entity: T & { id?: number },
    fetcher = this.defaultFetch
  ): Promise<T> {
    if (entity.id) {
      return this.update(entity.id, entity, fetcher);
    } else {
      return this.create(entity, fetcher);
    }
  }
}
Was this page helpful?