Skip to content

Examples with @briklab/reqor ​

This page shows common usage patterns and realistic scenarios.

Retry with exponential backoff ​

ts
import reqor from "@briklab/reqor";

const response = await reqor("https://unstable.example.com/data")
  .retry(5)
  .retryDelay(100, cur => cur * 2)   // start at 100ms, double each time
  .onRetry(n => console.log("attempt", n))
  .get();

Timeout handlers ​

ts
const res = await reqor("https://slow.example.com")
  .timeout(500)
  .onTimeout(() => console.warn("single try timed out"))
  .totalTimeout(5000)
  .onTotalTimeout(() => console.error("gave up"))
  .get();

Adding query parameters ​

ts
const res = await reqor("https://api.example.com/users")
  .params({ page: 2, per_page: 50 })
  .get();

You can also pass a URLSearchParams or an array of objects.

POST with JSON body ​

ts
const res = await reqor("https://api.example.com/login")
  .data({ username: "alice", password: "secret" })
  .post();

Global middleware ​

ts
import reqor from "@briklab/reqor";

reqor.use({
  before: (context) => {
    console.log("request", context.url, context.init);
  },
  after: (response, context) => {
    console.log("response", response.status);
    return response;
  }
});

// later in code
await reqor("https://httpbin.org/get").get();

Local middleware ​

ts
await reqor("/data")
  .use({
    before: (context) => {
      context.init.headers = { ...context.init.headers, Authorization: "bearer tok" };
    }
  })
  .get();

Clearing middlewares ​

ts
reqor.clearMiddlewares();

Delaying execution ​

ts
await reqor("/delayed")
  .after(1000)   // wait 1 second before starting request
  .get();

Combining options and middleware ​

You can mix both styles using the second argument to get()/post():

ts
await reqor("/mix")
  .retry(3)
  .get({
    retry: { number: 2 },
    middleware: async ctx => {
      console.log("mid");
      return ctx.next();
    }
  });

Inspecting the response object ​

The promise resolves to either Reqor.Response or Reqor.ResponseLater (when using fetchLater). It mirrors the native Response with extras such as elapsed (time taken) and retryCount.

ts
const resp = await reqor("/foo").get();
console.log(resp.status, resp.elapsed, resp.retryCount);

Live Demo ​

Next Steps ​