Documentation - v0.0.1
    Preparing search index...

    Class ApiService<Endpoints, Fetcher, OptionType>Abstract

    Generic API service, supporting type safety for endpoints, path params, query params and request/response bodies.

    Although it uses fetch in a very simple way beneath the hood, you can BYO fetch implementation by passing it in the constructor.

    import { ApiService, Endpoint } from "indulgent";

    // A GET endpoint with path param `id` and optional query param `q`, returning an object with `id` and `name`
    type GetItem = Endpoint<{ method: "GET"; path: "/items/:id"; pathParams: { id: string }; query: { q?: string }; response: { id: string; name: string } }>;

    // A POST endpoint with no path params, accepting a JSON body with `name`, returning an object with `id` and `name`
    type CreateItem = Endpoint<{ method: "POST"; path: "/items"; request: { name: string }; response: { id: string; name: string } }>;

    class MyApiService extends ApiService<GetItem | CreateItem> {}
    const api = new MyApiService({ baseUrl: "https://api.example.com" });

    // Making a GET request to /items/123?q=searchterm
    const item = await api.get("/items/:id", { pathParams: { id: "123" }, query: { q: "searchterm" } });

    // Making a POST request to /items with JSON body { name: "NewItem" }
    const newItem = await api.post("/items", { json: { name: "NewItem" } });

    Type Parameters

    Implements

    Index

    Constructors

    • Type Parameters

      • Endpoints extends BaseEndpoint<any, any, any, any, any>
      • Fetcher extends GenericFetcher<Record<string, any>> = GenericFetcher<RequestInit>
      • OptionType extends Record<string, any> = GetFetchOptionsFromFetcher<Fetcher>

      Parameters

      • Optionalopt: {
            baseUrl?: string;
            debug?: boolean;
            defaultOptions?: OptionType;
            fetcher?: GenericFetcher<OptionType>;
        }
        • OptionalbaseUrl?: string

          Optional base URL to be prepended to all request paths.

        • Optionaldebug?: boolean

          Only for debugging purposes, if true, will log additional information to the console.

        • OptionaldefaultOptions?: OptionType

          Default options to be merged with options passed to each fetch call. Useful for setting default headers, credentials, etc.

        • Optionalfetcher?: GenericFetcher<OptionType>

          If you need capabilities beyond the options passed to the fetch method, you can provide your own fetcher implementation.

          defaultFetcher for the default implementation.

      Returns ApiService<Endpoints, Fetcher, OptionType>

    Methods

    • Makes a DELETE request to the specified endpoint.

      Type Parameters

      • Path extends any

      Parameters

      • url: Path
      • Optionaloptions: Partial<
            Omit<
                FetchOptionType<Extract<Endpoints, { method: "DELETE"; path: Path }>>,
                "method",
            >,
        >
      • OptionalfetchOptions: Partial<OptionType>

      Returns Promise<Extract<Endpoints, { method: "DELETE"; path: Path }>["response"]>

      fetch for the base method.

      const data = await api.delete('/some-endpoint', { pathParams: { id: '123' } });
      
    • Base fetch method, allowing to specify any HTTP method.

      Type Parameters

      • E extends Endpoint<BaseEndpointWithOptionals>

      Parameters

      Returns Promise<E["response"]>

      const data = await api.fetch('/some-endpoint', { method: 'GET', pathParams: { id: '123' }, query: { q: 'search' } });
    • Makes a GET request to the specified endpoint.

      Type Parameters

      • Path extends any

      Parameters

      Returns Promise<Extract<Endpoints, { method: "GET"; path: Path }>["response"]>

      fetch for the base method.

      const data = await api.get('/some-endpoint', { pathParams: { id: '123' }, query: { q: 'search' } });
      
    • Makes a HEAD request to the specified endpoint.

      Type Parameters

      • Path extends any

      Parameters

      Returns Promise<Extract<Endpoints, { method: "HEAD"; path: Path }>["response"]>

      fetch for the base method.

      const data = await api.head('/some-endpoint', { pathParams: { id: '123' } });
      
    • Makes a PATCH request to the specified endpoint.

      Type Parameters

      • Path extends any

      Parameters

      Returns Promise<Extract<Endpoints, { method: "PATCH"; path: Path }>["response"]>

      fetch for the base method.

      const data = await api.patch('/some-endpoint', { body: { key: 'value' } });
      

    post

    • post<Path extends any>(
          url: Path,
          options?: Partial<
              Omit<
                  FetchOptionType<Extract<Endpoints, { method: "POST"; path: Path }>>,
                  "method",
              >,
          >,
          fetchOptions?: Partial<OptionType>,
      ): Promise<Extract<Endpoints, { method: "POST"; path: Path }>["response"]>

      Makes a POST request to the specified endpoint.

      Type Parameters

      • Path extends any

      Parameters

      Returns Promise<Extract<Endpoints, { method: "POST"; path: Path }>["response"]>

      fetch for the base method.

      const data = await api.post('/some-endpoint', { body: { key: 'value' } });
      
    • Makes a PUT request to the specified endpoint.

      Type Parameters

      • Path extends any

      Parameters

      Returns Promise<Extract<Endpoints, { method: "PUT"; path: Path }>["response"]>

      fetch for the base method.

      const data = await api.put('/some-endpoint', { body: { key: 'value' } });
      
    • Tries to call a method on the API service and returns a tuple of [error, response].

      Type Parameters

      Parameters

      Returns <Path extends any>(
          url: Path,
          options: MethodFetchOptionType<
              Extract<Endpoints, { method: Method; path: Path }>,
          >,
          fetchOptions?: Partial<OptionType>,
      ) => Promise<
          | [null, Extract<Endpoints, { method: Method; path: Path }>["response"]]
          | [ErrorType, null],
      >

      const [error, data] = await api.try<ErrorType>('GET')('/some-endpoint', { pathParams: { id: '123' }, query: { q: 'search' } });
      if (error) {
      // handle error
      } else {
      // use data
      }