elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

how to replay different requests ? #139

Closed Enigma10 closed 2 years ago

Enigma10 commented 2 years ago

Wretch v2 doesn't have a replay function anymore. So how to know if the request is a POST or GET Request before calling it again

wretch("/resource")
  .get()
  .unauthorized(async (error, req) => {
    // Renew credentials
    const token = await wretch("/renewtoken").get().text();
    storeToken(token);
    // Replay the original request with new credentials
    return req.auth(token).get().unauthorized((err) => {
      throw err;
    }).json();
  })
  .json()
  // The promise chain is preserved as expected
  // ".then" will be performed on the result of the original request
  // or the replayed one (if a 401 error was thrown)
  .then(callback);
elbywan commented 2 years ago

Hey @Enigma10,

Sorry I forgot to add the change in the migration guide, .replay has been renamed to .fetch which should do the trick.

Enigma10 commented 2 years ago

@elbywan Hi, I am also not able to find error and fetchError in the library. I am getting typescript errors when I want to use them.

error(418, (err) => console.log(err.status))
  .fetchError((err) => console.log(err))
  .res();
elbywan commented 2 years ago

@Enigma10 Weird, the following typescript code works perfectly well for me when transpiled using tsc:

import wretch from "wretch"

await wretch("http://httpstat.us/418")
  .get()
  .error(418, (err) => console.log(err.status))
  .res()
await wretch("http://bad")
  .get()
  .fetchError((err) => console.log(err))
  .res()
418
TypeError: fetch failed
    at Object.processResponse (node:internal/deps/undici/undici:5555:34)
    at node:internal/deps/undici/undici:5877:42
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: getaddrinfo ENOTFOUND bad
      at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:84:26) {
    errno: -3008,
    code: 'ENOTFOUND',
    syscall: 'getaddrinfo',
    hostname: 'bad'
  }
}
elbywan commented 2 years ago

Closing as invalid