Skip to content

Client cache

ts
import { 
createHttpClient
} from "@duplojs/http/client";
import {
E
,
unwrap
} from "@duplojs/utils";
import { type
Routes
} from "./types";
const
client
=
createHttpClient
<
Routes
>({
baseUrl
: "http://localhost:1506",
}); const
firstUsersRequest
= await
client
.
get
(
"/users", {
clientCache
: "auto" },
); const
secondUsersRequest
= await
client
.
get
(
"/users", {
clientCache
: "auto" },
); if (
E
.
isRight
(
secondUsersRequest
) &&
unwrap
(
secondUsersRequest
).
fromCache
) {
console
.
log
("Response loaded from cache.");
} const
refreshedUsersRequest
= await
client
.
get
(
"/users", {
clientCache
: "auto",
refreshClientCache
: true,
}, ); const
bypassedUsersRequest
= await
client
.
get
(
"/users", {
clientCache
: "auto",
bypassClientCache
: true,
}, ); const
customKeyRequest
= await
client
.
get
(
"/users/{userId}", {
params
: {
userId
: "42" },
clientCache
(
params
) {
return `user:${
params
.
path
}:${
params
.
params
?.
userId
?.
toString
()}`;
}, }, );

The HTTP client can cache responses on the client side. To enable this behavior for a request, use the clientCache property.

With the value "auto", DuploJS builds a cache key from:

  • the HTTP method
  • the final path with injected params
  • the query sorted by key
  • the body

You can also pass a function to build your own cache key.

Only 2xx responses are stored in cache. When a response comes from cache, the fromCache property is set to true.

Two options let you control this behavior:

  • bypassClientCache: true fully ignores cache for the current request: no read and no write.
  • refreshClientCache: true only bypasses cache lookup, performs the network request again, then replaces the cached value if the response is successful.

INFO

Client cache is local to the createHttpClient instance. Two different clients do not share the same cache store.

Released under the MIT License.