wretch
    Preparing search index...

    Interface Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>

    The Wretch object used to perform easy fetch requests.

    import wretch from "wretch"

    // Reusable wretch instance
    const w = wretch("https://domain.com", { mode: "cors" })

    Immutability : almost every method of this class return a fresh Wretch object.

    interface Wretch<
        Self = unknown,
        Chain = unknown,
        Resolver = undefined,
        ErrorType = undefined,
        CatcherResult = never,
    > {
        accept(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            headerValue: string,
        ): this;
        addon<W, R>(
            addon: WretchAddon<W, R>,
        ): W & Self & Wretch<
            Self & W,
            Chain & R,
            Resolver,
            ErrorType,
            CatcherResult,
        >;
        addon<W1, R1, W2, R2>(
            addon: [WretchAddon<W1, R1>, WretchAddon<W2, R2>],
        ): W1 & W2 & Self & Wretch<
            Self & W1 & W2,
            Chain & R1 & R2,
            Resolver,
            ErrorType,
            CatcherResult,
        >;
        addon<W1, R1, W2, R2, W3, R3>(
            addon: [WretchAddon<W1, R1>, WretchAddon<W2, R2>, WretchAddon<W3, R3>],
        ): W1 & W2 & W3 & Self & Wretch<
            Self & W1 & W2 & W3,
            Chain & R1 & R2 & R3,
            Resolver,
            ErrorType,
            CatcherResult,
        >;
        addon<W1, R1, W2, R2, W3, R3, W4, R4>(
            addon: [
                WretchAddon<W1, R1>,
                WretchAddon<W2, R2>,
                WretchAddon<W3, R3>,
                WretchAddon<W4, R4>,
            ],
        ): W1 & W2 & W3 & W4 & Self & Wretch<
            Self & W1 & W2 & W3 & W4,
            Chain & R1 & R2 & R3 & R4,
            Resolver,
            ErrorType,
            CatcherResult,
        >;
        addon<W1, R1, W2, R2, W3, R3, W4, R4, W5, R5>(
            addon: [
                WretchAddon<W1, R1>,
                WretchAddon<W2, R2>,
                WretchAddon<W3, R3>,
                WretchAddon<W4, R4>,
                WretchAddon<W5, R5>,
            ],
        ): W1 & W2 & W3 & W4 & W5 & Self & Wretch<
            Self & W1 & W2 & W3 & W4 & W5,
            Chain & R1 & R2 & R3 & R4 & R5,
            Resolver,
            ErrorType,
            CatcherResult,
        >;
        addon<W1, R1, W2, R2, W3, R3, W4, R4, W5, R5, W6, R6>(
            addon: [
                WretchAddon<W1, R1>,
                WretchAddon<W2, R2>,
                WretchAddon<W3, R3>,
                WretchAddon<W4, R4>,
                WretchAddon<W5, R5>,
                WretchAddon<W6, R6>,
            ],
        ): W1 & W2 & W3 & W4 & W5 & W6 & Self & Wretch<
            Self & W1 & W2 & W3 & W4 & W5 & W6,
            Chain & R1 & R2 & R3 & R4 & R5 & R6,
            Resolver,
            ErrorType,
            CatcherResult,
        >;
        addon<W1, R1, W2, R2, W3, R3, W4, R4, W5, R5, W6, R6, W7, R7>(
            addon: [
                WretchAddon<W1, R1>,
                WretchAddon<W2, R2>,
                WretchAddon<W3, R3>,
                WretchAddon<W4, R4>,
                WretchAddon<W5, R5>,
                WretchAddon<W6, R6>,
                WretchAddon<W7, R7>,
            ],
        ): W1 & W2 & W3 & W4 & W5 & W6 & W7 & Self & Wretch<
            Self & W1 & W2 & W3 & W4 & W5 & W6 & W7,
            Chain & R1 & R2 & R3 & R4 & R5 & R6 & R7,
            Resolver,
            ErrorType,
            CatcherResult,
        >;
        addon<W1, R1, W2, R2, W3, R3, W4, R4, W5, R5, W6, R6, W7, R7, W8, R8>(
            addon: [
                WretchAddon<W1, R1>,
                WretchAddon<W2, R2>,
                WretchAddon<W3, R3>,
                WretchAddon<W4, R4>,
                WretchAddon<W5, R5>,
                WretchAddon<W6, R6>,
                WretchAddon<W7, R7>,
                WretchAddon<W8, R8>,
            ],
        ): W1 & W2 & W3 & W4 & W5 & W6 & W7 & W8 & Self & Wretch<
            Self & W1 & W2 & W3 & W4 & W5 & W6 & W7 & W8,
            Chain & R1 & R2 & R3 & R4 & R5 & R6 & R7 & R8,
            Resolver,
            ErrorType,
            CatcherResult,
        >;
        addon<
            W1,
            R1,
            W2,
            R2,
            W3,
            R3,
            W4,
            R4,
            W5,
            R5,
            W6,
            R6,
            W7,
            R7,
            W8,
            R8,
            W9,
            R9,
        >(
            addon: [
                WretchAddon<W1, R1>,
                WretchAddon<W2, R2>,
                WretchAddon<W3, R3>,
                WretchAddon<W4, R4>,
                WretchAddon<W5, R5>,
                WretchAddon<W6, R6>,
            ],
        ): W1 & W2 & W3 & W4 & W5 & W6 & W7 & W8 & W9 & Self & Wretch<
            Self & W1 & W2 & W3 & W4 & W5 & W6 & W7 & W8 & W9,
            Chain & R1 & R2 & R3 & R4 & R5 & R6 & R7 & R8 & R9,
            Resolver,
            ErrorType,
            CatcherResult,
        >;
        auth(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            headerValue: string,
        ): this;
        body(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            contents: any,
        ): this;
        catcher<Result>(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            errorId: ErrorId | ErrorId[],
            catcher: (
                error: ErrorType extends undefined ? WretchError : ErrorType,
                originalRequest: this,
            ) => Result,
        ): Self & Wretch<
            Self,
            Chain,
            Resolver,
            ErrorType extends undefined ? WretchError : ErrorType,
            CatcherResult | WretchCatcherResult<Result>,
        >;
        catcherFallback<Result>(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            catcher: (error: unknown, originalRequest: this) => Result,
        ): Self & Wretch<
            Self,
            Chain,
            Resolver,
            ErrorType extends undefined ? WretchError : ErrorType,
            CatcherResult | WretchCatcherResult<Result>,
        >;
        content(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            headerValue: string,
        ): this;
        customError<T>(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            transformer: (
                error: WretchError,
                response: WretchResponse,
                request: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            ) => T | Promise<T>,
        ): Self & Wretch<Self, Chain, Resolver, T, CatcherResult>;
        defer<
            Deferred extends
                Wretch<any, any, any, any, any> = Wretch<
                Self,
                Chain,
                any,
                ErrorType,
                CatcherResult,
            >,
            Clear extends boolean = false,
        >(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            callback: WretchDeferredCallback<
                Self,
                Chain,
                Resolver,
                ErrorType,
                CatcherResult,
                Deferred,
            >,
            clear?: Clear,
        ): Self & Wretch<
            Self,
            Chain,
            Resolver,
            ErrorType,
            CatcherResult
            | InferWretchCatcherResult<Deferred>,
        >;
        delete(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            url?: string,
        ): Resolver extends undefined
            ? Chain & WretchResponseChain<
                Self,
                Chain,
                Resolver,
                ErrorType,
                CatcherResult,
            >
            : Resolver;
        fetch(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            method?: string,
            url?: string,
            body?: any,
        ): Resolver extends undefined
            ? Chain & WretchResponseChain<
                Self,
                Chain,
                Resolver,
                ErrorType,
                CatcherResult,
            >
            : Resolver;
        fetchPolyfill(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            fetch: (url: string, opts: WretchOptions) => Promise<Response>,
        ): this;
        get(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            url?: string,
        ): Resolver extends undefined
            ? Chain & WretchResponseChain<
                Self,
                Chain,
                Resolver,
                ErrorType,
                CatcherResult,
            >
            : Resolver;
        head(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            url?: string,
        ): Resolver extends undefined
            ? Chain & WretchResponseChain<
                Self,
                Chain,
                Resolver,
                ErrorType,
                CatcherResult,
            >
            : Resolver;
        headers(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            headerValues: HeadersInit,
        ): this;
        json(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            jsObject: object,
            contentType?: string,
        ): this;
        middlewares(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            middlewares: ConfiguredMiddleware[],
            clear?: boolean,
        ): this;
        options(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            options: WretchOptions,
            replace?: boolean,
        ): this;
        opts(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            url?: string,
        ): Resolver extends undefined
            ? Chain & WretchResponseChain<
                Self,
                Chain,
                Resolver,
                ErrorType,
                CatcherResult,
            >
            : Resolver;
        patch(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            body?: any,
            url?: string,
        ): Resolver extends undefined
            ? Chain & WretchResponseChain<
                Self,
                Chain,
                Resolver,
                ErrorType,
                CatcherResult,
            >
            : Resolver;
        post(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            body?: any,
            url?: string,
        ): Resolver extends undefined
            ? Chain & WretchResponseChain<
                Self,
                Chain,
                Resolver,
                ErrorType,
                CatcherResult,
            >
            : Resolver;
        put(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            body?: any,
            url?: string,
        ): Resolver extends undefined
            ? Chain & WretchResponseChain<
                Self,
                Chain,
                Resolver,
                ErrorType,
                CatcherResult,
            >
            : Resolver;
        resolve<ResolverReturn, Clear extends boolean = false>(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            resolver: (
                chain: Resolver extends undefined
                    ? Chain & WretchResponseChain<
                        Self,
                        Chain,
                        undefined,
                        ErrorType,
                        CatcherResult,
                    >
                    : Clear extends true
                        ? Chain & WretchResponseChain<
                            Self,
                            Chain,
                            undefined,
                            ErrorType,
                            CatcherResult,
                        >
                        : Resolver,
                originalRequest: Self & Wretch<
                    Self,
                    Chain,
                    Clear extends true ? undefined : Resolver,
                    ErrorType,
                    CatcherResult,
                >,
            ) => ResolverReturn,
            clear?: Clear,
        ): Self & Wretch<Self, Chain, ResolverReturn, ErrorType, CatcherResult>;
        toFetch(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
        ): (url: string, options?: WretchOptions) => Promise<Response>;
        url(
            this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>,
            url: string,
            replace?: boolean,
        ): this;
    }

    Type Parameters

    • Self = unknown
    • Chain = unknown
    • Resolver = undefined
    • ErrorType = undefined
    • CatcherResult = never
    Index

    Body Types

    • Sets the "Content-Type" header, stringifies an object and sets the request body.

      const jsonObject = { a: 1, b: 2, c: 3 };
      wretch("...").json(jsonObject).post();
      // Note that calling an 'http verb' method with an object argument is equivalent:
      wretch("...").post(jsonObject);

      Parameters

      Returns this

    HTTP

    • Sends the request using the accumulated fetch options.

      Can be used to replay requests.

      const reAuthOn401 = wretch()
      .catcher(401, async (error, request) => {
      // Renew credentials
      const token = await wretch("/renewtoken").get().text();
      storeToken(token);
      // Replay the original request with new credentials
      return request.auth(token).fetch().unauthorized((err) => {
      throw err;
      }).json();
      });

      reAuthOn401
      .get("/resource")
      .json() // <- Will only be called for the original promise
      .then(callback); // <- Will be called for the original OR the replayed promise result

      Parameters

      • this: Self & Wretch<Self, Chain, Resolver, ErrorType, CatcherResult>
      • Optionalmethod: string

        The HTTP method to use

      • Optionalurl: string

        Some url to append

      • Optionalbody: any

        Set the body. Behaviour varies depending on the argument type, an object is considered as json.

      Returns Resolver extends undefined
          ? Chain & WretchResponseChain<
              Self,
              Chain,
              Resolver,
              ErrorType,
              CatcherResult,
          >
          : Resolver

    post

    Helpers

    • Adds a catcher which will be called on every subsequent request error.

      Very useful when you need to perform a repetitive action on a specific error code or multiple error codes.

      const w = wretch()
      .catcher(404, err => redirect("/routes/notfound", err.message))
      .catcher(500, err => flashMessage("internal.server.error"))

      // Catch multiple error codes with the same handler
      const w2 = wretch()
      .catcher([401, 403], err => redirect("/login"))

      // No need to catch the 404, 500, 401, or 403 codes, they are already taken care of.
      w.get("http://myapi.com/get/something").json()

      // Default catchers can be overridden if needed.
      w
      .get("http://myapi.com/get/something")
      .notFound(err =>
      // overrides the default 'redirect' catcher
      )
      .json()

      The original request is passed along the error and can be used in order to perform an additional request.

      const reAuthOn401 = wretch()
      .catcher(401, async (error, request) => {
      // Renew credentials
      const token = await wretch("/renewtoken").get().text();
      storeToken(token);
      // Replay the original request with new credentials
      return request.auth(token).fetch().unauthorized((err) => {
      throw err;
      }).json();
      });

      reAuthOn401
      .get("/resource")
      .json() // <- Will only be called for the original promise
      .then(callback); // <- Will be called for the original OR the replayed promise result

      Type Parameters

      • Result

      Parameters

      Returns Self & Wretch<
          Self,
          Chain,
          Resolver,
          ErrorType extends undefined ? WretchError : ErrorType,
          CatcherResult | WretchCatcherResult<Result>,
      >

    • Sets a custom fetch implementation to use for requests.

      This is useful for:

      • Adding custom middleware to fetch
      • Using alternative fetch implementations
      • Mocking fetch in tests
      • Adding performance monitoring
      // Add performance monitoring to fetch
      const customFetch = (url, opts) => {
      console.time(url)
      return fetch(url, opts).finally(() => console.timeEnd(url))
      }

      wretch("http://domain.com")
      .fetchPolyfill(customFetch)
      .get()

      Parameters

      Returns this

    • Sets the fetch options.

      wretch("...").options({ credentials: "same-origin" });
      

      Wretch being immutable, you can store the object for later use.

      const corsWretch = wretch().options({ credentials: "include", mode: "cors" });

      corsWretch.get("http://endpoint1");
      corsWretch.get("http://endpoint2");

      You can override instead of mixing in the existing options by passing a boolean flag.

      // By default options are mixed in :
      let w = wretch()
      .options({ headers: { "Accept": "application/json" } })
      .options({ encoding: "same-origin", headers: { "X-Custom": "Header" } });
      console.log(JSON.stringify(w._options))
      // => {"encoding":"same-origin", "headers":{"Accept":"application/json","X-Custom":"Header"}}

      // With the flag, options are overridden :
      w = wretch()
      .options({ headers: { "Accept": "application/json" } })
      .options(
      { encoding: "same-origin", headers: { "X-Custom": "Header" } },
      true,
      );
      console.log(JSON.stringify(w._options))
      // => {"encoding":"same-origin","headers":{"X-Custom":"Header"}}

      Parameters

      Returns this

    • Converts the wretch instance into a fetch-like function that preserves all accumulated configuration (middlewares, catchers, options, headers, etc.).

      Useful for integrating with libraries that expect a fetch function signature.

      const myFetch = wretch("https://api.example.com")
      .auth("Bearer token")
      .catcher(401, handleAuth)
      .middlewares([retry()])
      .toFetch()

      // Use like regular fetch but with all the wretch configuration
      const response = await myFetch("/users", { method: "GET" })

      Returns (url: string, options?: WretchOptions) => Promise<Response>

    • Appends or replaces the url.

      wretch("/root").url("/sub").get().json();

      // Can be used to set a base url

      // Subsequent requests made using the 'blogs' object will be prefixed with "http://domain.com/api/blogs"
      const blogs = wretch("http://domain.com/api/blogs");

      // Perfect for CRUD apis
      const id = await blogs.post({ name: "my blog" }).json(blog => blog.id);
      const blog = await blogs.get(`/${id}`).json();
      console.log(blog.name);

      await blogs.url(`/${id}`).delete().res();

      // And to replace the base url if needed :
      const noMoreBlogs = blogs.url("http://domain2.com/", true);

      Parameters

      Returns this