@cacheable/net 2.0.7 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +578 -72
- package/dist/index.cjs +1309 -699
- package/dist/index.d.cts +420 -225
- package/dist/index.d.mts +499 -0
- package/dist/index.mjs +1291 -0
- package/package.json +17 -11
- package/dist/index.d.ts +0 -304
- package/dist/index.js +0 -679
package/README.md
CHANGED
|
@@ -8,21 +8,51 @@
|
|
|
8
8
|
[](https://www.npmjs.com/package/@cacheable/net)
|
|
9
9
|
[](https://github.com/jaredwray/cacheable/blob/main/LICENSE)
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
* `fetch`
|
|
14
|
-
* HTTP method helpers
|
|
15
|
-
* [
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
11
|
+
`@cacheable/net` is a high performance network layer for Node.js. It gives you a drop-in `fetch` with native semantics, ergonomic HTTP method helpers (`get`, `post`, `put`, `patch`, `delete`, `head`), and optional response caching powered by [`cacheable`](https://npmjs.com/package/cacheable) — including full [RFC 7234](http://httpwg.org/specs/rfc7234.html) HTTP cache semantics. It also ships first-class, cached **WHOIS** and **RDAP** lookups for domains, IP addresses, and ASNs.
|
|
12
|
+
|
|
13
|
+
* Drop-in `fetch` with native semantics — built on the runtime's global `fetch`, resolves with a `Response` on any status (check `response.ok`, never throws on `4xx`/`5xx`) and preserves `response.url`, `redirected`, and `type`
|
|
14
|
+
* HTTP method helpers — `get`, `post`, `put`, `patch`, `delete`, and `head` that return a typed `{ data, response }` and automatically (de)serialize JSON bodies
|
|
15
|
+
* Optional response caching via [`cacheable`](https://npmjs.com/package/cacheable) — layered (Layer 1 / Layer 2) caching, LRU, TTL expiration, distributed sync, and more
|
|
16
|
+
* [RFC 7234](http://httpwg.org/specs/rfc7234.html) compliant HTTP caching with `http-cache-semantics` (honors `Cache-Control`, `ETag`, `Last-Modified`, `Expires`, conditional revalidation, and `304 Not Modified`)
|
|
17
|
+
* Simple TTL-based caching mode for when you don't want HTTP semantics (`httpCachePolicy: false`)
|
|
18
|
+
* Smart, method-aware automatic cache key generation, with request coalescing in simple caching mode and for WHOIS/RDAP lookups (concurrent identical misses share one upstream request)
|
|
19
|
+
* Custom serialization / deserialization with `stringify` and `parse` — at the instance level or per request
|
|
20
20
|
* Request-level cache control with the `caching` option
|
|
21
|
-
*
|
|
21
|
+
* `whois` and `rdap` lookups for domains, IPv4/IPv6 addresses, and ASNs with **both raw and JSON output**, dynamic IANA server discovery, referral following, and built-in caching
|
|
22
|
+
* Extends [`hookified`](https://npmjs.com/package/hookified) so the instance is an event emitter / hookable object
|
|
23
|
+
* All the features of [`cacheable`](https://npmjs.com/package/cacheable) — layered caching, LRU, TTL expiration, tags, and more
|
|
24
|
+
* Full TypeScript support with comprehensive type definitions
|
|
25
|
+
* ESM and CommonJS builds
|
|
22
26
|
* Extensively tested with 100% code coverage
|
|
23
27
|
|
|
24
28
|
# Table of Contents
|
|
25
29
|
* [Getting Started](#getting-started)
|
|
30
|
+
* [Basic Usage](#basic-usage)
|
|
31
|
+
* [HTTP Method Helpers](#http-method-helpers)
|
|
32
|
+
* [Working with the Response](#working-with-the-response)
|
|
33
|
+
* [Using fetch Directly](#using-fetch-directly)
|
|
34
|
+
* [Caching Control](#caching-control)
|
|
35
|
+
* [HTTP Cache Semantics (RFC 7234)](#http-cache-semantics-rfc-7234)
|
|
36
|
+
* [Simple Caching Mode](#simple-caching-mode)
|
|
37
|
+
* [Custom Serialization](#custom-serialization)
|
|
38
|
+
* [Error Handling](#error-handling)
|
|
39
|
+
* [Using a Custom or Shared Cache](#using-a-custom-or-shared-cache)
|
|
40
|
+
* [Events](#events)
|
|
41
|
+
* [Standalone Functions](#standalone-functions)
|
|
42
|
+
* [WHOIS and RDAP Lookups](#whois-and-rdap-lookups)
|
|
43
|
+
* [WHOIS](#whois)
|
|
44
|
+
* [Following Referrals](#following-referrals)
|
|
45
|
+
* [Standalone whois and whoisRaw](#standalone-whois-and-whoisraw)
|
|
46
|
+
* [WhoisOptions](#whoisoptions)
|
|
47
|
+
* [WhoisResult](#whoisresult)
|
|
48
|
+
* [WHOIS Parsing Helpers](#whois-parsing-helpers)
|
|
49
|
+
* [RDAP](#rdap)
|
|
50
|
+
* [Standalone rdap](#standalone-rdap)
|
|
51
|
+
* [RdapOptions](#rdapoptions)
|
|
52
|
+
* [RdapResult](#rdapresult)
|
|
53
|
+
* [CacheableNet Options](#cacheablenet-options)
|
|
54
|
+
* [CacheableNet API](#cacheablenet-api)
|
|
55
|
+
* [Exports and Types](#exports-and-types)
|
|
26
56
|
* [How to Contribute](#how-to-contribute)
|
|
27
57
|
* [License and Copyright](#license-and-copyright)
|
|
28
58
|
|
|
@@ -32,35 +62,209 @@ Features:
|
|
|
32
62
|
npm install @cacheable/net
|
|
33
63
|
```
|
|
34
64
|
|
|
35
|
-
|
|
65
|
+
`@cacheable/net` ships both ESM and CommonJS builds and includes its own TypeScript type definitions, so no `@types` package is required.
|
|
66
|
+
|
|
67
|
+
```javascript
|
|
68
|
+
// ESM
|
|
69
|
+
import { CacheableNet } from '@cacheable/net';
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
```javascript
|
|
73
|
+
// CommonJS
|
|
74
|
+
const { CacheableNet } = require('@cacheable/net');
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
# Basic Usage
|
|
78
|
+
|
|
79
|
+
Create a `CacheableNet` instance and use the method helpers. By default a `Cacheable` instance is created for you, GET requests are cached, and HTTP cache semantics are enabled.
|
|
36
80
|
|
|
37
81
|
```javascript
|
|
38
82
|
import { CacheableNet } from '@cacheable/net';
|
|
39
83
|
|
|
40
84
|
const net = new CacheableNet();
|
|
41
85
|
|
|
42
|
-
// Simple GET request with caching
|
|
43
|
-
const response = await net.get('https://api.example.com/data');
|
|
44
|
-
console.log(response.data);
|
|
86
|
+
// Simple GET request with caching (the response body is parsed into `data`)
|
|
87
|
+
const { data, response } = await net.get('https://api.example.com/data');
|
|
88
|
+
console.log(response.status, data);
|
|
45
89
|
|
|
46
|
-
// POST request with
|
|
90
|
+
// POST request with a JSON body (serialized automatically)
|
|
47
91
|
const result = await net.post('https://api.example.com/users', {
|
|
48
92
|
name: 'John Doe',
|
|
49
93
|
email: 'john@example.com'
|
|
50
94
|
});
|
|
95
|
+
console.log(result.data);
|
|
51
96
|
|
|
52
|
-
// Using fetch directly
|
|
97
|
+
// Using fetch directly returns the raw Response
|
|
53
98
|
const fetchResponse = await net.fetch('https://api.example.com/data', {
|
|
54
99
|
method: 'GET',
|
|
55
|
-
headers: {
|
|
56
|
-
|
|
57
|
-
|
|
100
|
+
headers: { Authorization: 'Bearer token' }
|
|
101
|
+
});
|
|
102
|
+
console.log(await fetchResponse.json());
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
> `Net` is exported as an alias of `CacheableNet`, so `new Net()` and `new CacheableNet()` are equivalent.
|
|
106
|
+
|
|
107
|
+
# HTTP Method Helpers
|
|
108
|
+
|
|
109
|
+
All method helpers (except `fetch`) parse the response body and return a typed [`DataResponse<T>`](#working-with-the-response) of the shape `{ data, response }`. The `get`, `post`, `put`, `patch`, and `delete` helpers accept a generic type parameter so you can type the parsed `data`.
|
|
110
|
+
|
|
111
|
+
```javascript
|
|
112
|
+
import { CacheableNet } from '@cacheable/net';
|
|
113
|
+
|
|
114
|
+
const net = new CacheableNet();
|
|
115
|
+
|
|
116
|
+
// GET — cached by default
|
|
117
|
+
const { data } = await net.get('https://api.example.com/users/1');
|
|
118
|
+
|
|
119
|
+
// GET with a typed result (TypeScript)
|
|
120
|
+
type User = { id: number; name: string };
|
|
121
|
+
const { data: user } = await net.get<User>('https://api.example.com/users/1');
|
|
122
|
+
|
|
123
|
+
// POST — body is JSON-serialized and Content-Type set to application/json automatically
|
|
124
|
+
await net.post('https://api.example.com/users', { name: 'Ada' });
|
|
125
|
+
|
|
126
|
+
// PUT / PATCH — same body handling as POST
|
|
127
|
+
await net.put('https://api.example.com/users/1', { name: 'Ada Lovelace' });
|
|
128
|
+
await net.patch('https://api.example.com/users/1', { name: 'Ada' });
|
|
129
|
+
|
|
130
|
+
// DELETE — body is optional
|
|
131
|
+
await net.delete('https://api.example.com/users/1');
|
|
132
|
+
|
|
133
|
+
// HEAD — returns the raw Response (no body)
|
|
134
|
+
const head = await net.head('https://api.example.com/users/1');
|
|
135
|
+
console.log(head.headers.get('content-length'));
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
| Method | Signature | Returns | Caching |
|
|
139
|
+
|--------|-----------|---------|---------|
|
|
140
|
+
| `fetch` | `fetch(url, options?)` | `Promise<Response>` | GET requests only |
|
|
141
|
+
| `get` | `get<T>(url, options?)` | `Promise<DataResponse<T>>` | On by default (`caching: false` to disable) |
|
|
142
|
+
| `post` | `post<T>(url, data?, options?)` | `Promise<DataResponse<T>>` | Never cached |
|
|
143
|
+
| `put` | `put<T>(url, data?, options?)` | `Promise<DataResponse<T>>` | Opt-in with `caching: true` |
|
|
144
|
+
| `patch` | `patch<T>(url, data?, options?)` | `Promise<DataResponse<T>>` | Never cached |
|
|
145
|
+
| `delete` | `delete<T>(url, data?, options?)` | `Promise<DataResponse<T>>` | Never cached |
|
|
146
|
+
| `head` | `head(url, options?)` | `Promise<Response>` | Never cached |
|
|
147
|
+
|
|
148
|
+
**Body handling for `post` / `put` / `patch` / `delete`:** if `data` is a `string`, `FormData`, `URLSearchParams`, or `Blob` it is sent as-is; any other value is serialized with the [`stringify`](#custom-serialization) function (default `JSON.stringify`) and a `Content-Type: application/json` header is added when one is not already present.
|
|
149
|
+
|
|
150
|
+
# Working with the Response
|
|
151
|
+
|
|
152
|
+
Every helper that returns data resolves to a `DataResponse<T>`:
|
|
153
|
+
|
|
154
|
+
```typescript
|
|
155
|
+
type DataResponse<T = unknown> = {
|
|
156
|
+
data: T; // the parsed body (falls back to the raw text if parsing fails)
|
|
157
|
+
response: Response; // a standard Response, reconstructed so the body can be read again
|
|
158
|
+
};
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
The `data` field is produced by running the response text through the [`parse`](#custom-serialization) function (default `JSON.parse`). If parsing throws (for example, the body is plain text), the raw string is returned instead, so a helper never rejects just because a body is not JSON.
|
|
162
|
+
|
|
163
|
+
The `response` is a standard `Response` with the native-`fetch` properties preserved — `response.ok`, `response.status`, `response.statusText`, `response.headers`, `response.url`, `response.redirected`, and `response.type` are all available, and because the body is reattached you can still call `response.text()` / `response.json()` on it.
|
|
164
|
+
|
|
165
|
+
```javascript
|
|
166
|
+
const { data, response } = await net.get('https://api.example.com/data');
|
|
167
|
+
|
|
168
|
+
if (response.ok) {
|
|
169
|
+
console.log('final url after redirects:', response.url);
|
|
170
|
+
console.log('etag:', response.headers.get('etag'));
|
|
171
|
+
console.log('parsed body:', data);
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
# Using fetch Directly
|
|
176
|
+
|
|
177
|
+
`net.fetch` is a thin, caching wrapper over the runtime's global `fetch`. It returns the raw `Response` (it does **not** parse the body) and follows native semantics — it resolves on any status and only rejects on a network-level failure.
|
|
178
|
+
|
|
179
|
+
```javascript
|
|
180
|
+
const net = new CacheableNet();
|
|
181
|
+
|
|
182
|
+
const response = await net.fetch('https://api.example.com/data', {
|
|
183
|
+
headers: { Accept: 'application/json' }
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
if (response.ok) {
|
|
187
|
+
const json = await response.json();
|
|
188
|
+
console.log(json);
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
`net.fetch` always uses the instance cache and the instance `httpCachePolicy` setting. To make a one-off request with different HTTP cache behavior, use the [standalone `fetch` function](#standalone-functions), which accepts a per-call `httpCachePolicy`.
|
|
193
|
+
|
|
194
|
+
# Caching Control
|
|
195
|
+
|
|
196
|
+
You can control caching at the instance level and per request.
|
|
197
|
+
|
|
198
|
+
* **GET** requests are cached by default. Pass `caching: false` to disable caching for a single GET request.
|
|
199
|
+
* **PUT** requests are **not** cached by default. Pass `caching: true` to cache a PUT.
|
|
200
|
+
* **POST**, **PATCH**, **DELETE**, and **HEAD** requests are **never** cached — the `caching` option has no effect on them and they always reach the network.
|
|
201
|
+
|
|
202
|
+
```javascript
|
|
203
|
+
import { CacheableNet } from '@cacheable/net';
|
|
204
|
+
|
|
205
|
+
const net = new CacheableNet();
|
|
206
|
+
|
|
207
|
+
// GET requests are cached by default
|
|
208
|
+
const data1 = await net.get('https://api.example.com/data');
|
|
209
|
+
|
|
210
|
+
// Disable caching for a specific GET request
|
|
211
|
+
const data2 = await net.get('https://api.example.com/data', { caching: false });
|
|
212
|
+
|
|
213
|
+
// POST requests are never cached
|
|
214
|
+
const result1 = await net.post('https://api.example.com/data', { value: 1 });
|
|
215
|
+
|
|
216
|
+
// Enable caching for a PUT request (PUT is the only write method that caches)
|
|
217
|
+
const result2 = await net.put('https://api.example.com/data', { value: 1 }, { caching: true });
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
> **Note:** When caching is enabled on a PUT, an identical request is matched by **method and URL only** — the request body is not part of the cache key, so two PUTs to the same URL with different bodies share one cache entry. Only successful responses are ever cached.
|
|
221
|
+
|
|
222
|
+
# HTTP Cache Semantics (RFC 7234)
|
|
223
|
+
|
|
224
|
+
By default (`httpCachePolicy: true`) responses are cached according to [RFC 7234](http://httpwg.org/specs/rfc7234.html) using [`http-cache-semantics`](https://www.npmjs.com/package/http-cache-semantics). In this mode the library:
|
|
225
|
+
|
|
226
|
+
* Respects standard HTTP cache headers (`Cache-Control`, `ETag`, `Last-Modified`, `Expires`)
|
|
227
|
+
* Stores and validates cache policies per RFC 7234, only caching responses that are "storable"
|
|
228
|
+
* Sets the cache TTL from HTTP headers (for example the `max-age` directive)
|
|
229
|
+
* Issues conditional requests with `If-None-Match` / `If-Modified-Since` when an entry needs revalidation
|
|
230
|
+
* Processes `304 Not Modified` responses to refresh the cached entry and its TTL
|
|
231
|
+
* Automatically revalidates stale entries
|
|
232
|
+
|
|
233
|
+
```javascript
|
|
234
|
+
import { CacheableNet } from '@cacheable/net';
|
|
235
|
+
|
|
236
|
+
// HTTP cache semantics are on by default
|
|
237
|
+
const net = new CacheableNet({ httpCachePolicy: true });
|
|
238
|
+
|
|
239
|
+
// TTL is derived from the response's Cache-Control: max-age, ETag, etc.
|
|
240
|
+
const { data } = await net.get('https://api.example.com/data');
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
# Simple Caching Mode
|
|
244
|
+
|
|
245
|
+
Set `httpCachePolicy: false` to use simple key-based caching that ignores HTTP cache directives. In this mode the library:
|
|
246
|
+
|
|
247
|
+
* Caches every successful GET response regardless of cache directives
|
|
248
|
+
* Uses the default TTL from the `Cacheable` instance
|
|
249
|
+
* Never revalidates cached entries
|
|
250
|
+
* Coalesces concurrent identical misses so the origin is hit only once
|
|
251
|
+
|
|
252
|
+
```javascript
|
|
253
|
+
import { CacheableNet } from '@cacheable/net';
|
|
254
|
+
|
|
255
|
+
const net = new CacheableNet({
|
|
256
|
+
httpCachePolicy: false,
|
|
257
|
+
cache: { ttl: '5m' } // every cached GET lives for 5 minutes
|
|
58
258
|
});
|
|
259
|
+
|
|
260
|
+
const { data } = await net.get('https://api.example.com/data');
|
|
59
261
|
```
|
|
60
262
|
|
|
61
|
-
|
|
263
|
+
In either mode, error responses (`4xx` / `5xx`) are always returned to the caller but are **never** cached, so a transient failure is never replayed from a cache hit.
|
|
264
|
+
|
|
265
|
+
# Custom Serialization
|
|
62
266
|
|
|
63
|
-
You can provide custom `stringify` and `parse` functions for handling data serialization. This is particularly useful when working with complex data types that JSON doesn't natively support
|
|
267
|
+
You can provide custom `stringify` and `parse` functions for handling data serialization. This is particularly useful when working with complex data types that JSON doesn't natively support. They can be set on the instance (constructor option or the `stringify` / `parse` properties) or overridden per request.
|
|
64
268
|
|
|
65
269
|
```javascript
|
|
66
270
|
import { CacheableNet } from '@cacheable/net';
|
|
@@ -84,99 +288,401 @@ const response = await net.post('https://api.example.com/data', {
|
|
|
84
288
|
|
|
85
289
|
// Or provide per-request custom serialization
|
|
86
290
|
const result = await net.get('https://api.example.com/data', {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
return superjson.parse(text);
|
|
90
|
-
}
|
|
291
|
+
// Custom parsing with superjson for this request only
|
|
292
|
+
parse: (text) => superjson.parse(text)
|
|
91
293
|
});
|
|
92
294
|
```
|
|
93
295
|
|
|
94
|
-
|
|
296
|
+
You can also read or replace the functions after construction:
|
|
95
297
|
|
|
96
|
-
|
|
298
|
+
```javascript
|
|
299
|
+
net.stringify = (value) => superjson.stringify(value);
|
|
300
|
+
net.parse = (text) => superjson.parse(text);
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
# Error Handling
|
|
304
|
+
|
|
305
|
+
`@cacheable/net` follows native `fetch` semantics. It **resolves** with a `Response` for every completed HTTP exchange — including `4xx` and `5xx` — and only rejects when the request itself fails (DNS failure, connection refused, abort, etc.). Use `response.ok` (or `response.status`) to detect HTTP errors instead of a `try/catch`:
|
|
306
|
+
|
|
307
|
+
```javascript
|
|
308
|
+
const net = new CacheableNet();
|
|
309
|
+
|
|
310
|
+
const { response, data } = await net.get('https://api.example.com/thing');
|
|
311
|
+
if (!response.ok) {
|
|
312
|
+
// 404, 500, etc. — `data` holds any error body the server returned
|
|
313
|
+
throw new Error(`Request failed with status ${response.status}`);
|
|
314
|
+
}
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
Only successful responses are cached. Under the default HTTP cache mode, `2xx` responses are cached per RFC 7234 (honoring `Cache-Control`, `ETag`, `Expires`, etc.); in simple mode (`httpCachePolicy: false`) every `2xx` response is cached. Error responses (`4xx`/`5xx`) are always returned to the caller but **never** cached, so a transient failure is never replayed from a cache hit.
|
|
318
|
+
|
|
319
|
+
# Using a Custom or Shared Cache
|
|
320
|
+
|
|
321
|
+
The `cache` option accepts either a [`Cacheable`](https://npmjs.com/package/cacheable) instance or `CacheableOptions`. Passing options lets `@cacheable/net` construct the instance; passing an instance lets you share one cache across your application and unlocks the full `cacheable` feature set (Layer 1 / Layer 2 storage, distributed sync, tags, statistics, and more).
|
|
97
322
|
|
|
98
323
|
```javascript
|
|
99
324
|
import { CacheableNet } from '@cacheable/net';
|
|
100
325
|
|
|
326
|
+
// Construct a cache from options
|
|
101
327
|
const net = new CacheableNet({
|
|
102
|
-
|
|
328
|
+
cache: { ttl: '1h' }
|
|
103
329
|
});
|
|
330
|
+
```
|
|
104
331
|
|
|
105
|
-
|
|
106
|
-
|
|
332
|
+
```javascript
|
|
333
|
+
import { CacheableNet } from '@cacheable/net';
|
|
334
|
+
import { Cacheable } from 'cacheable';
|
|
335
|
+
import KeyvRedis from '@keyv/redis';
|
|
107
336
|
|
|
108
|
-
//
|
|
109
|
-
const
|
|
110
|
-
|
|
337
|
+
// Share a Layer 1 (memory) + Layer 2 (Redis) cache
|
|
338
|
+
const cache = new Cacheable({
|
|
339
|
+
secondary: new KeyvRedis('redis://localhost:6379'),
|
|
340
|
+
ttl: '1h'
|
|
111
341
|
});
|
|
112
342
|
|
|
113
|
-
|
|
114
|
-
|
|
343
|
+
const net = new CacheableNet({ cache });
|
|
344
|
+
|
|
345
|
+
// The underlying cache is available on the instance
|
|
346
|
+
await net.cache.set('manual:key', 'value');
|
|
347
|
+
console.log(await net.cache.get('manual:key'));
|
|
348
|
+
|
|
349
|
+
// Swap the cache at runtime
|
|
350
|
+
net.cache = new Cacheable();
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
To learn everything the cache can do — layered storage, TTL shorthand (`'1h'`, `'5m'`), `maxTtl`, tag-based invalidation, `CacheableSync`, and statistics — see the [`cacheable` documentation](https://npmjs.com/package/cacheable).
|
|
354
|
+
|
|
355
|
+
# Events
|
|
356
|
+
|
|
357
|
+
`CacheableNet` extends [`hookified`](https://npmjs.com/package/hookified), so each instance is an event emitter / hookable object (`on`, `once`, `off`, `emit`, `onHook`, `removeHook`, …) and accepts `HookifiedOptions` in its constructor.
|
|
358
|
+
|
|
359
|
+
Caching events such as cache hits and misses are emitted by the underlying `Cacheable` instance, which you can reach through `net.cache`:
|
|
360
|
+
|
|
361
|
+
```javascript
|
|
362
|
+
import { CacheableNet } from '@cacheable/net';
|
|
363
|
+
import { CacheableEvents } from 'cacheable';
|
|
364
|
+
|
|
365
|
+
const net = new CacheableNet();
|
|
366
|
+
|
|
367
|
+
net.cache.on(CacheableEvents.CACHE_HIT, (data) => {
|
|
368
|
+
console.log('cache hit:', data.key);
|
|
369
|
+
});
|
|
370
|
+
net.cache.on(CacheableEvents.CACHE_MISS, (data) => {
|
|
371
|
+
console.log('cache miss:', data.key);
|
|
372
|
+
});
|
|
373
|
+
net.cache.on(CacheableEvents.ERROR, (error) => {
|
|
374
|
+
console.error('cache error:', error.message);
|
|
375
|
+
});
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
# Standalone Functions
|
|
379
|
+
|
|
380
|
+
If you don't need an instance, the underlying functions are exported directly. Pass a `cache` in the options to enable caching; without one the request is still made, just not cached. These functions use `JSON.stringify` / `JSON.parse` for body handling.
|
|
381
|
+
|
|
382
|
+
```javascript
|
|
383
|
+
import { fetch, get, post, patch, del, head } from '@cacheable/net';
|
|
384
|
+
import { Cacheable } from 'cacheable';
|
|
385
|
+
|
|
386
|
+
const cache = new Cacheable();
|
|
115
387
|
|
|
116
|
-
//
|
|
117
|
-
const
|
|
118
|
-
|
|
388
|
+
// fetch — no cache needed; returns the raw Response
|
|
389
|
+
const response = await fetch('https://api.example.com/data');
|
|
390
|
+
|
|
391
|
+
// fetch with caching and a per-call HTTP cache policy
|
|
392
|
+
const cached = await fetch('https://api.example.com/data', {
|
|
393
|
+
cache,
|
|
394
|
+
httpCachePolicy: false // override per call (only available on the standalone fetch)
|
|
119
395
|
});
|
|
396
|
+
|
|
397
|
+
// get / post / patch / del — return { data, response }
|
|
398
|
+
// Pass `cache` to enable caching. As with the class helpers, only GET
|
|
399
|
+
// responses are cached; post/patch/del always bypass the cache.
|
|
400
|
+
const { data } = await get('https://api.example.com/data', { cache });
|
|
401
|
+
await post('https://api.example.com/data', { value: 1 }, { cache });
|
|
402
|
+
await patch('https://api.example.com/data', { value: 1 }, { cache });
|
|
403
|
+
|
|
404
|
+
// del accepts an optional body; you can also call it with options only
|
|
405
|
+
await del('https://api.example.com/data/1', undefined, { cache });
|
|
406
|
+
await del('https://api.example.com/data/1', { cache });
|
|
407
|
+
|
|
408
|
+
// head — returns the raw Response (no body)
|
|
409
|
+
const headResponse = await head('https://api.example.com/data', { cache });
|
|
120
410
|
```
|
|
121
411
|
|
|
122
|
-
|
|
412
|
+
> The standalone helpers cover `fetch`, `get`, `post`, `patch`, `del` (DELETE), and `head`. There is no standalone `put`; use `net.put` (or the `fetch` function with `method: 'PUT'`) for PUT requests. `del` is named `del` because `delete` is a reserved word.
|
|
413
|
+
>
|
|
414
|
+
> Except for `fetch` (whose options argument is optional), each standalone helper needs an options argument — pass at least `{}` to `get`, `post`, `patch`, and `head`, and pass `del` an options object (as its second argument, or third when you also send a body). Calling them with the options omitted throws.
|
|
415
|
+
|
|
416
|
+
# WHOIS and RDAP Lookups
|
|
417
|
+
|
|
418
|
+
`@cacheable/net` ships first-class lookups for domains, IP addresses (v4/v6), and ASNs over both the traditional **WHOIS** protocol (TCP port 43) and the modern **RDAP** protocol (HTTPS/JSON). WHOIS returns the registry's **raw text** which is also parsed into a JSON object, while RDAP returns native JSON. The authoritative server is discovered dynamically through IANA and cached, so you never have to ship or maintain a static list of TLD servers.
|
|
419
|
+
|
|
420
|
+
Because WHOIS and RDAP servers are heavily rate-limited, results are cached (and concurrent identical lookups are coalesced) using the same `cacheable` instance as the rest of the library.
|
|
421
|
+
|
|
422
|
+
## WHOIS
|
|
423
|
+
|
|
424
|
+
```javascript
|
|
425
|
+
import { CacheableNet } from '@cacheable/net';
|
|
426
|
+
|
|
427
|
+
const net = new CacheableNet();
|
|
428
|
+
|
|
429
|
+
const result = await net.whois('example.com');
|
|
430
|
+
|
|
431
|
+
result.query; // the normalized query that was looked up
|
|
432
|
+
result.type; // "domain" | "ipv4" | "ipv6" | "asn"
|
|
433
|
+
result.server; // the authoritative server that produced the data
|
|
434
|
+
result.raw; // the full raw WHOIS text (all hops joined by a blank line)
|
|
435
|
+
result.fields; // parsed JSON, e.g. { "Domain Name": "EXAMPLE.COM", "Name Server": ["A", "B"] }
|
|
436
|
+
result.hops; // every server response in order (registry, registrar, ...)
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
`whois` accepts domains, full URLs, IPv4/IPv6 addresses, and ASNs (the query is normalized first — scheme, `www.`, path, port, and trailing dots are stripped, and internationalized domains are converted to punycode):
|
|
440
|
+
|
|
441
|
+
```javascript
|
|
442
|
+
await net.whois('https://www.example.com/path'); // normalized to example.com
|
|
443
|
+
await net.whois('8.8.8.8'); // IPv4 lookup
|
|
444
|
+
await net.whois('2001:4860:4860::8888'); // IPv6 lookup
|
|
445
|
+
await net.whois('AS15169'); // ASN lookup
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
## Following Referrals
|
|
449
|
+
|
|
450
|
+
By default a registry response's `Registrar WHOIS Server` referral is followed to fetch fuller data. Control this with the `follow` option (`false`/`0` to disable, `true` for the default depth of 2, or a number of hops):
|
|
451
|
+
|
|
452
|
+
```javascript
|
|
453
|
+
const shallow = await net.whois('example.com', { follow: false }); // registry only
|
|
454
|
+
const deep = await net.whois('example.com', { follow: 2 }); // follow up to 2 referrals
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
## Standalone whois and whoisRaw
|
|
458
|
+
|
|
459
|
+
You can also use the standalone functions. `whois` returns the full result; `whoisRaw` returns just the raw text. The standalone functions cache only when you pass a `cache` instance in the options.
|
|
123
460
|
|
|
124
|
-
|
|
461
|
+
```javascript
|
|
462
|
+
import { whois, whoisRaw } from '@cacheable/net';
|
|
463
|
+
|
|
464
|
+
const { fields } = await whois('8.8.8.8'); // IP address lookup
|
|
465
|
+
const { fields: asn } = await whois('AS15169'); // ASN lookup
|
|
466
|
+
const raw = await whoisRaw('example.com'); // raw text only
|
|
467
|
+
|
|
468
|
+
// With caching
|
|
469
|
+
import { Cacheable } from 'cacheable';
|
|
470
|
+
const cache = new Cacheable();
|
|
471
|
+
const result = await whois('example.com', { cache });
|
|
472
|
+
```
|
|
125
473
|
|
|
126
|
-
|
|
474
|
+
## WhoisOptions
|
|
127
475
|
|
|
128
|
-
|
|
476
|
+
| Option | Type | Default | Description |
|
|
477
|
+
|--------|------|---------|-------------|
|
|
478
|
+
| `server` | `string` | – | Query this server directly and skip IANA discovery |
|
|
479
|
+
| `port` | `number` | `43` | TCP port for the initial server |
|
|
480
|
+
| `timeout` | `number` | `10000` | Socket timeout in milliseconds |
|
|
481
|
+
| `follow` | `boolean \| number` | `true` | Follow registry → registrar referrals (`true` = depth 2, `false`/`0` = none) |
|
|
482
|
+
| `queryPrefix` | `string` | `""` | Text written before the query (e.g. `"domain "` for some registries) |
|
|
483
|
+
| `encoding` | `BufferEncoding` | `"utf8"` | Encoding used to decode responses |
|
|
484
|
+
| `bootstrapServer` | `string` | `"whois.iana.org"` | The bootstrap WHOIS server used when no `server` is provided |
|
|
485
|
+
| `bootstrapPort` | `number` | `43` | TCP port of the bootstrap WHOIS server |
|
|
486
|
+
| `caching` | `boolean` | `true` | Disable caching for this lookup when `false` |
|
|
487
|
+
| `cache` | `Cacheable` | instance cache | Cache instance (standalone `whois` caches only when provided) |
|
|
488
|
+
| `ttl` | `number \| string` | instance default | TTL override for the cached result |
|
|
489
|
+
|
|
490
|
+
## WhoisResult
|
|
129
491
|
|
|
130
492
|
```typescript
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
493
|
+
type WhoisResult = {
|
|
494
|
+
query: string; // the normalized query that was looked up
|
|
495
|
+
type: WhoisQueryType; // "domain" | "ipv4" | "ipv6" | "asn"
|
|
496
|
+
server: string; // the final authoritative server that produced the primary data
|
|
497
|
+
raw: string; // the raw text across all hops, separated by a blank line
|
|
498
|
+
fields: WhoisFields; // merged parsed fields across all hops (repeats become arrays)
|
|
499
|
+
hops: WhoisHop[]; // every server response, in the order they were queried
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
type WhoisFields = Record<string, string | string[]>;
|
|
503
|
+
|
|
504
|
+
type WhoisHop = {
|
|
505
|
+
server: string; // the server queried for this hop
|
|
506
|
+
port: number; // the TCP port used for this hop
|
|
507
|
+
raw: string; // the raw text returned by this server
|
|
508
|
+
fields: WhoisFields; // the parsed key/value fields for this hop
|
|
509
|
+
};
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
## WHOIS Parsing Helpers
|
|
513
|
+
|
|
514
|
+
The lower-level building blocks used by `whois` are exported so you can normalize, classify, parse, or query servers yourself:
|
|
515
|
+
|
|
516
|
+
```javascript
|
|
517
|
+
import {
|
|
518
|
+
normalizeWhoisQuery,
|
|
519
|
+
detectQueryType,
|
|
520
|
+
parseWhois,
|
|
521
|
+
queryWhoisServer
|
|
522
|
+
} from '@cacheable/net';
|
|
523
|
+
|
|
524
|
+
normalizeWhoisQuery('https://www.Example.com/'); // "example.com"
|
|
525
|
+
detectQueryType('AS15169'); // "asn"
|
|
526
|
+
|
|
527
|
+
// Parse raw WHOIS text into a key/value object (repeats become arrays)
|
|
528
|
+
const fields = parseWhois('Domain Name: EXAMPLE.COM\nName Server: A\nName Server: B');
|
|
529
|
+
// => { "Domain Name": "EXAMPLE.COM", "Name Server": ["A", "B"] }
|
|
530
|
+
|
|
531
|
+
// Query a single WHOIS server directly over TCP and get the raw text back
|
|
532
|
+
const raw = await queryWhoisServer({
|
|
533
|
+
host: 'whois.verisign-grs.com',
|
|
534
|
+
query: 'example.com',
|
|
535
|
+
timeout: 10000
|
|
536
|
+
});
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
| Function | Signature | Description |
|
|
540
|
+
|----------|-----------|-------------|
|
|
541
|
+
| `normalizeWhoisQuery` | `(input: string) => string` | Strip scheme/`www.`/path/port/trailing dots, lowercase, and punycode-encode IDNs |
|
|
542
|
+
| `detectQueryType` | `(value: string) => WhoisQueryType` | Classify a normalized query as `domain`, `ipv4`, `ipv6`, or `asn` |
|
|
543
|
+
| `parseWhois` | `(raw: string) => WhoisFields` | Parse raw WHOIS text into key/value fields (repeated keys become arrays) |
|
|
544
|
+
| `queryWhoisServer` | `(options: QueryWhoisServerOptions) => Promise<string>` | Open a raw WHOIS TCP connection to one server and return its text response |
|
|
545
|
+
|
|
546
|
+
`QueryWhoisServerOptions` accepts `host`, `query`, and optional `port` (default `43`), `queryPrefix` (default `""`), `timeout` (default `10000`), and `encoding` (default `"utf8"`).
|
|
547
|
+
|
|
548
|
+
## RDAP
|
|
549
|
+
|
|
550
|
+
RDAP is the modern, fully structured replacement for WHOIS. The RDAP server is resolved from the IANA bootstrap registries (fetched and cached through the library's own `fetch`).
|
|
551
|
+
|
|
552
|
+
```javascript
|
|
553
|
+
import { CacheableNet } from '@cacheable/net';
|
|
554
|
+
|
|
555
|
+
const net = new CacheableNet();
|
|
556
|
+
|
|
557
|
+
const result = await net.rdap('example.com');
|
|
558
|
+
result.query; // the normalized query
|
|
559
|
+
result.type; // "domain" | "ipv4" | "ipv6" | "asn"
|
|
560
|
+
result.server; // the RDAP base URL used
|
|
561
|
+
result.raw; // raw JSON text
|
|
562
|
+
result.data; // parsed RDAP object
|
|
137
563
|
```
|
|
138
564
|
|
|
139
|
-
|
|
565
|
+
## Standalone rdap
|
|
140
566
|
|
|
141
|
-
|
|
567
|
+
The standalone `rdap` function supports domains, IPs, and ASNs, and caches only when you pass a `cache` instance.
|
|
142
568
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
569
|
+
```javascript
|
|
570
|
+
import { rdap } from '@cacheable/net';
|
|
571
|
+
|
|
572
|
+
const domain = await rdap('example.com');
|
|
573
|
+
const ip = await rdap('1.1.1.1');
|
|
574
|
+
const asn = await rdap('AS15169');
|
|
575
|
+
|
|
576
|
+
// With caching
|
|
577
|
+
import { Cacheable } from 'cacheable';
|
|
578
|
+
const cache = new Cacheable();
|
|
579
|
+
const cached = await rdap('example.com', { cache });
|
|
580
|
+
```
|
|
150
581
|
|
|
151
|
-
|
|
582
|
+
## RdapOptions
|
|
583
|
+
|
|
584
|
+
| Option | Type | Default | Description |
|
|
585
|
+
|--------|------|---------|-------------|
|
|
586
|
+
| `server` | `string` | – | Query this RDAP base URL directly and skip bootstrap discovery |
|
|
587
|
+
| `bootstrapUrl` | `string` | `https://data.iana.org/rdap` | Override the IANA bootstrap base URL |
|
|
588
|
+
| `headers` | `Record<string, string>` | – | Additional request headers |
|
|
589
|
+
| `caching` | `boolean` | `true` | Disable caching for this lookup when `false` |
|
|
590
|
+
| `cache` | `Cacheable` | instance cache | Cache instance (standalone `rdap` caches only when provided) |
|
|
591
|
+
| `ttl` | `number \| string` | instance default | TTL override for the cached result |
|
|
592
|
+
|
|
593
|
+
## RdapResult
|
|
152
594
|
|
|
153
595
|
```typescript
|
|
154
|
-
type
|
|
155
|
-
|
|
156
|
-
|
|
596
|
+
type RdapResult = {
|
|
597
|
+
query: string; // the normalized query that was looked up
|
|
598
|
+
type: WhoisQueryType; // "domain" | "ipv4" | "ipv6" | "asn"
|
|
599
|
+
server: string; // the RDAP base URL that produced the data
|
|
600
|
+
raw: string; // the raw JSON text returned by the server
|
|
601
|
+
data: Record<string, unknown>; // the parsed RDAP object
|
|
157
602
|
};
|
|
158
603
|
```
|
|
159
604
|
|
|
160
|
-
|
|
605
|
+
# CacheableNet Options
|
|
606
|
+
|
|
607
|
+
The constructor accepts `CacheableNetOptions`, which also extends `HookifiedOptions`:
|
|
608
|
+
|
|
609
|
+
```typescript
|
|
610
|
+
type CacheableNetOptions = {
|
|
611
|
+
cache?: Cacheable | CacheableOptions; // Cacheable instance or options (default: new Cacheable())
|
|
612
|
+
httpCachePolicy?: boolean; // Enable HTTP cache semantics (default: true)
|
|
613
|
+
stringify?: (value: unknown) => string; // Custom serializer (default: JSON.stringify)
|
|
614
|
+
parse?: (value: string) => unknown; // Custom parser (default: JSON.parse)
|
|
615
|
+
} & HookifiedOptions;
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
| Option | Type | Default | Description |
|
|
619
|
+
|--------|------|---------|-------------|
|
|
620
|
+
| `cache` | `Cacheable \| CacheableOptions` | `new Cacheable()` | An existing cache instance, or options to construct one |
|
|
621
|
+
| `httpCachePolicy` | `boolean` | `true` | Use RFC 7234 HTTP cache semantics; set `false` for simple TTL-based caching |
|
|
622
|
+
| `stringify` | `(value: unknown) => string` | `JSON.stringify` | Serializer for request bodies and cached values |
|
|
623
|
+
| `parse` | `(value: string) => unknown` | `JSON.parse` | Parser for response bodies |
|
|
624
|
+
|
|
625
|
+
Request options for the method helpers use `NetFetchOptions`, which extends the standard `fetch` `RequestInit` (minus `method` and `cache`, which are managed internally):
|
|
161
626
|
|
|
162
627
|
```typescript
|
|
163
628
|
type NetFetchOptions = {
|
|
164
|
-
caching?: boolean;
|
|
165
|
-
stringify?: (value: unknown) => string;
|
|
166
|
-
parse?: (value: string) => unknown;
|
|
629
|
+
caching?: boolean; // Enable/disable caching for this request
|
|
630
|
+
stringify?: (value: unknown) => string; // Per-request serializer override
|
|
631
|
+
parse?: (value: string) => unknown; // Per-request parser override
|
|
167
632
|
} & Omit<FetchOptions, 'method' | 'cache'>;
|
|
633
|
+
|
|
634
|
+
type FetchOptions = Omit<RequestInit, 'cache'> & {
|
|
635
|
+
cache?: Cacheable; // Cache instance (used by the standalone functions)
|
|
636
|
+
httpCachePolicy?: boolean; // HTTP cache semantics for this request (standalone fetch only)
|
|
637
|
+
};
|
|
168
638
|
```
|
|
169
639
|
|
|
170
|
-
|
|
640
|
+
# CacheableNet API
|
|
641
|
+
|
|
642
|
+
### Properties
|
|
643
|
+
|
|
644
|
+
* `cache: Cacheable` — get/set the underlying `Cacheable` instance used for caching.
|
|
645
|
+
* `httpCachePolicy: boolean` — get/set whether HTTP cache semantics are enabled.
|
|
646
|
+
* `stringify: (value: unknown) => string` — get/set the serializer used for request bodies.
|
|
647
|
+
* `parse: (value: string) => unknown` — get/set the parser used for response bodies.
|
|
648
|
+
|
|
649
|
+
### Methods
|
|
650
|
+
|
|
651
|
+
* `fetch(url, options?)` — fetch with caching support; returns the raw `Response`.
|
|
652
|
+
* `get<T>(url, options?)` — GET request; returns `DataResponse<T>`. Cached by default (`caching: false` to disable).
|
|
653
|
+
* `post<T>(url, data?, options?)` — POST request; serializes `data` and returns `DataResponse<T>`. Never cached.
|
|
654
|
+
* `put<T>(url, data?, options?)` — PUT request; serializes `data` and returns `DataResponse<T>`. Not cached by default; pass `caching: true` to cache.
|
|
655
|
+
* `patch<T>(url, data?, options?)` — PATCH request; serializes `data` and returns `DataResponse<T>`. Never cached.
|
|
656
|
+
* `delete<T>(url, data?, options?)` — DELETE request; optionally serializes `data` and returns `DataResponse<T>`. Never cached.
|
|
657
|
+
* `head(url, options?)` — HEAD request; returns the raw `Response` (no body). Never cached.
|
|
658
|
+
* `whois(query, options?)` — WHOIS lookup; returns a `WhoisResult` with raw text and parsed fields.
|
|
659
|
+
* `rdap(query, options?)` — RDAP lookup; returns an `RdapResult` with raw JSON and parsed data.
|
|
660
|
+
|
|
661
|
+
Inherited from [`hookified`](https://npmjs.com/package/hookified): `on`, `once`, `off`, `emit`, `onHook`, `removeHook`, and the rest of the event/hook API.
|
|
662
|
+
|
|
663
|
+
# Exports and Types
|
|
664
|
+
|
|
665
|
+
`@cacheable/net` exports the following from its entry point:
|
|
666
|
+
|
|
667
|
+
**Classes**
|
|
668
|
+
|
|
669
|
+
* `CacheableNet` — the main class.
|
|
670
|
+
* `Net` — an alias for `CacheableNet`.
|
|
671
|
+
|
|
672
|
+
**Standalone functions**
|
|
673
|
+
|
|
674
|
+
* `fetch`, `get`, `post`, `patch`, `del`, `head` — HTTP helpers (no standalone `put`).
|
|
675
|
+
* `whois`, `whoisRaw`, `rdap` — registration data lookups.
|
|
676
|
+
* `normalizeWhoisQuery`, `detectQueryType`, `parseWhois`, `queryWhoisServer` — WHOIS building blocks.
|
|
171
677
|
|
|
172
|
-
|
|
678
|
+
**Types**
|
|
173
679
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
- To disable caching for GET/HEAD, set `caching: false` in the options
|
|
680
|
+
* `CacheableNetOptions`, `NetFetchOptions`, `StringifyType`, `ParseType`
|
|
681
|
+
* `FetchOptions`, `FetchRequestInit`, `FetchResponse`, `DataResponse`, `GetResponse`
|
|
682
|
+
* `WhoisOptions`, `WhoisResult`, `WhoisFields`, `WhoisHop`, `WhoisQueryType`, `QueryWhoisServerOptions`
|
|
683
|
+
* `RdapOptions`, `RdapResult`
|
|
179
684
|
|
|
685
|
+
> `FetchResponse` is the runtime `Response` type and `GetResponse` is a backward-compatible alias of `DataResponse`.
|
|
180
686
|
|
|
181
687
|
# How to Contribute
|
|
182
688
|
|