Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 30 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ filters into two:
| `full_content` | `content` |
| `removeduplicate`, `excludefield` | `remove_duplicate`, `exclude_field` |

`coin` and `market_id` keep their names. v2 also accepts `raw_query` on every
`coin` and `market_id` keep their names. v2 also accepts `rawQuery` on every
endpoint, `sources` included.

v2 responses carry `total_results` and `next_page` where v1 carries
Expand Down Expand Up @@ -153,7 +153,8 @@ await client.latestApi({ rawQuery: 'q=bitcoin&country=us&language=en' });
```

`rawQuery` is mutually exclusive with all other parameters and is validated
against the endpoint's allowed keys.
against the endpoint's allowed keys; for the v1 count endpoints it must also
carry `from_date` and `to_date`.

## Real-time news (WebSocket)

Expand Down Expand Up @@ -200,7 +201,8 @@ for await (const response of ws.stream(registrationId)) {
```

Break out of the loop to stop; the connection closes either way. `ws.close()`
ends an in-flight stream from outside the loop.
ends an in-flight stream from outside the loop — at once, even while it is
waiting to reconnect.

Transient drops (network errors, server restarts, abnormal closes) are
reconnected automatically with a capped exponential backoff. Pass
Expand All @@ -209,12 +211,17 @@ rejection — bad API key or unknown
`registration_id`, exhausted API credits, or too many simultaneous devices — throws
`NewsdataWebSocketAuthError` and is **not** retried.

The server always accepts the handshake and then closes with code **1008** when
the connection is refused, carrying one of three reasons: `invalid credentials
or registration not found`, `api limit reached`, or `device limit reached` (more
than 5 devices on one `registration_id`). Every other close code — including
`1013` (`send timeout`, meaning the client read too slowly) — is transient and
reconnects.
When it refuses a connection, the server accepts the handshake, sends one error
response — `{"status":"error","results":{"message":"…","code":"…"}}` — and
closes. The stream never yields that response: it becomes the thrown error,
whose `message` is the server's explanation, `code` its error code and
`responseBody` the whole response. Close code **1008** is permanent; its reason
is the bare code: `Unauthorized` or `InvalidRequest` (bad key or unknown
`registration_id`), `ApiLimitExceeded` or `ApiKeyLimitExceeded` (credits used
up), `DeviceLimitExceeded` (more than 5 devices on one `registration_id`).
Every other close code — `1011` (server error) and `1013` (the client read too
slowly) included — is transient and reconnects; with `reconnect: false` it
throws `NewsdataWebSocketError` carrying the server's message.

**Each delivered article consumes 1 API credit per connected device.**

Expand All @@ -231,7 +238,7 @@ try {
// ...
}
} catch (err) {
if (err instanceof NewsdataWebSocketAuthError) console.error('rejected:', err.message);
if (err instanceof NewsdataWebSocketAuthError) console.error(`rejected (${err.code}):`, err.message);
else if (err instanceof NewsdataWebSocketError) console.error('stream error:', err.message);
else throw err;
}
Expand All @@ -254,16 +261,18 @@ const ws = new NewsDataApiWebSocket(client, {
> v22. On older runtimes pass your own implementation, e.g.
> `new NewsDataApiWebSocket(client, { WebSocket: require('ws') })`.
>
> Node's global `WebSocket` does not expose the handshake HTTP status. When a
> connection fails before it opens, the client probes the same URL over HTTP to
> tell a permanent rejection (401 / 403) from a transient failure.
> Node's global `WebSocket` does not expose the handshake HTTP status, so a
> handshake that fails before the connection opens — a proxy answering 401 or
> 403, say — shows up as close code 1006 and is retried as a transient failure.

Runnable example: [`examples/websocket.js`](examples/websocket.js).

## Client-side validation

Before any request is sent, parameters are validated and normalized. A
`NewsdataValidationError` is thrown (without spending API quota) when:
Before any request is sent, parameters are validated and normalized. The
returned promise rejects with a `NewsdataValidationError` (without spending API
quota; with `paginate: true` the first iteration throws it — a client method
never throws synchronously) when:

- a parameter is not accepted by that endpoint;
- mutually-exclusive parameters are set together — `q`/`qInTitle`/`qInMeta`,
Expand Down Expand Up @@ -339,9 +348,12 @@ const client = new NewsDataApiClient(apiKey, {
0.3.0 it included the version (`https://newsdata.io/api/1/`), so drop the
trailing `/1/` if you override it.

Retries cover network errors, HTTP 429, and 5xx. 429 honors the `Retry-After`
header (integer seconds or HTTP-date); otherwise backoff is exponential. Auth
and other 4xx errors are never retried.
Retries cover network errors, HTTP 429, and 5xx. `timeout` covers the whole
request, reading the response body included. A 429 waits for its `Retry-After`
(integer seconds or HTTP-date) plus one second; without the header, backoff is
exponential. When `Retry-After` is longer than `retryBackoffMax`, the call
rejects at once with `NewsdataRateLimitError` and `retryAfter` set (seconds),
leaving the wait to you. Auth and other 4xx errors are never retried.

A 429 that waiting cannot fix is never retried.
`NewsdataApiLimitExceededError` means the account's whole credit pool is
Expand Down
4 changes: 3 additions & 1 deletion examples/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@ try {
}
}
} catch (err) {
// A refusal is never yielded as news: the server's explanation arrives
// here, with its code (Unauthorized, ApiLimitExceeded, DeviceLimitExceeded, …).
if (err instanceof NewsdataWebSocketAuthError) {
console.error(`rejected: ${err.message}`);
console.error(`rejected (${err.code}): ${err.message}`);
process.exit(1);
}
throw err;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "newsdata-nodejs-client",
"version": "0.3.0",
"version": "0.4.0",
"description": "Official Node.js client (SDK) for the Newsdata.io News API — fetch real-time, historical, crypto, and stock-market news via REST with validation, retries, pagination, and typed errors.",
"type": "module",
"main": "src/index.js",
Expand Down
77 changes: 53 additions & 24 deletions src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,12 @@ export class NewsDataApiClient {
* @param {string} apiKey
* @param {object} [options]
* @param {string} [options.baseUrl]
* @param {number} [options.timeout] Per-request timeout (ms).
* @param {number} [options.timeout] Per-request timeout (ms), body read included.
* @param {number} [options.maxRetries] Total attempts (1 = no retry).
* @param {number} [options.retryBackoff] Base backoff (ms).
* @param {number} [options.retryBackoffMax] Cap on a single backoff (ms).
* @param {number} [options.retryBackoffMax] Cap on a single backoff (ms). A 429 whose
* Retry-After is longer rejects at once with NewsdataRateLimitError (retryAfter set);
* a shorter one is waited out, plus one second.
* @param {number} [options.paginationDelay] Delay between pages (ms).
* @param {number} [options.maxResult] Default cap for scroll mode.
* @param {number} [options.maxPages] Default cap for paginate mode.
Expand Down Expand Up @@ -153,7 +155,7 @@ export class NewsDataApiClient {
* Single-page endpoint; scroll / paginate are not supported.
* @returns {Promise<object>}
*/
sourcesApi(params = {}) {
async sourcesApi(params = {}) {
const { rawQuery = null, ...rest } = params;
const validated = validateParams('sources', rest, rawQuery);
return this.#request('sources', validated);
Expand Down Expand Up @@ -190,7 +192,7 @@ export class NewsDataApiClient {
* Single-page endpoint; scroll / paginate are not supported.
* @returns {Promise<object>}
*/
sources(params = {}) {
async sources(params = {}) {
const { rawQuery = null, ...rest } = params;
const validated = validateParams('sources_v2', rest, rawQuery);
return this.#request('sources_v2', validated);
Expand All @@ -213,7 +215,7 @@ export class NewsDataApiClient {
* `err.responseBody.results.registration_id`.
* @returns {Promise<object>}
*/
websocketRegister(params = {}) {
async websocketRegister(params = {}) {
const { rawQuery = null, ...rest } = params;
const validated = validateParams('websocket_register', rest, rawQuery);
validated.news_type = WS_NEWS_TYPE;
Expand All @@ -237,7 +239,7 @@ export class NewsDataApiClient {
* @param {string} registrationId
* @returns {Promise<object>}
*/
websocketDelete(registrationId) {
async websocketDelete(registrationId) {
if (typeof registrationId !== 'string' || registrationId === '') {
throw new NewsdataValidationError(
'registrationId must be a non-empty string',
Expand All @@ -252,11 +254,6 @@ export class NewsDataApiClient {
return this.#apiKey;
}

/** The configured fetch, reused by the WebSocket handshake probe. @internal */
get fetchForWebSocket() {
return this.#fetch;
}

/** Forward a log line from the WebSocket layer. @internal */
logForWebSocket(level, message) {
this.#log(level, message);
Expand All @@ -269,6 +266,10 @@ export class NewsDataApiClient {
* Returns a Promise for single & scroll modes, or an async generator when
* `paginate: true`. `v2` selects the v2 response keys (`total_results` /
* `next_page`) for the multi-page modes.
*
* Validation errors are reported the way the call's result is consumed: a
* rejected promise, or (paginate) the generator's first `next()` — never a
* synchronous throw before the caller holds anything to attach a handler to.
*/
#dispatch(endpoint, params, isCount = false, v2 = false) {
const {
Expand All @@ -280,10 +281,15 @@ export class NewsDataApiClient {
...rest
} = params;

if (scroll && paginate) {
throw new NewsdataValidationError('scroll and paginate are mutually exclusive');
let validated;
try {
if (scroll && paginate) {
throw new NewsdataValidationError('scroll and paginate are mutually exclusive');
}
validated = validateParams(endpoint, rest, rawQuery);
} catch (err) {
return paginate ? failOnFirstNext(err) : Promise.reject(err);
}
const validated = validateParams(endpoint, rest, rawQuery);

if (paginate) {
return this.#paginate(endpoint, validated, maxPages ?? this.#maxPages, isCount, v2);
Expand Down Expand Up @@ -324,14 +330,28 @@ export class NewsDataApiClient {
this.#log('info', `${method} ${logUrl} (attempt ${attempt}/${this.#maxRetries})`);

let res;
let text;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.#timeout);
// The timeout covers the whole exchange, body included. Racing it (on
// top of aborting) bounds the body read even when a fetch
// implementation ignores the abort signal while the body streams in.
let timer;
const timedOut = new Promise((_, reject) => {
timer = setTimeout(() => {
reject(new Error(`request timed out after ${this.#timeout}ms`));
controller.abort();
}, this.#timeout);
});
try {
res = await this.#fetch(fullUrl, {
method,
headers: { Accept: 'application/json' },
signal: controller.signal,
});
res = await Promise.race([
this.#fetch(fullUrl, {
method,
headers: { Accept: 'application/json' },
signal: controller.signal,
}),
timedOut,
]);
text = await Promise.race([res.text(), timedOut]);
} catch (err) {
if (attempt >= this.#maxRetries) {
throw new NewsdataNetworkError(
Expand All @@ -347,7 +367,6 @@ export class NewsDataApiClient {
}

const status = res.status;
const text = await res.text();
let body;
try {
body = text === '' ? null : JSON.parse(text);
Expand Down Expand Up @@ -376,15 +395,19 @@ export class NewsDataApiClient {
// A 429 covers a burst limit, a rate limit, and exhausted API
// credits. Only the first two are worth retrying.
const QuotaError = quotaExhaustedError(body);
if (QuotaError !== null || attempt >= this.#maxRetries) {
// A wait longer than retryBackoffMax is left to the caller.
const waitTooLong = retryAfter !== null && retryAfter > this.#retryBackoffMax;
if (QuotaError !== null || attempt >= this.#maxRetries || waitTooLong) {
const ErrorClass = QuotaError ?? NewsdataRateLimitError;
throw new ErrorClass(
this.#errorMessage(body, status), 429, asObject(body),
retryAfter === null ? null : Math.round(retryAfter / 1000),
);
}
const wait = retryAfter ?? this.#backoff(attempt);
this.#log('warn', `429 rate limit; sleeping ${wait}ms`);
// Retry-After is in whole seconds: one second more keeps the retry
// from arriving just before the limit resets.
const wait = retryAfter !== null ? retryAfter + 1000 : this.#backoff(attempt);
this.#log('warn', `429 rate limit (attempt ${attempt}/${this.#maxRetries}); sleeping ${wait}ms`);
await sleep(wait);
continue;
}
Expand Down Expand Up @@ -499,3 +522,9 @@ export class NewsDataApiClient {
function asObject(body) {
return body && typeof body === 'object' && !Array.isArray(body) ? body : null;
}

/** An async generator whose first `next()` rejects with `err` (paginate mode). */
// eslint-disable-next-line require-yield
async function* failOnFirstNext(err) {
throw err;
}
8 changes: 3 additions & 5 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
//
// Parameter names are lowercase here; user-supplied keys are lowercased before
// validation (the API is case-insensitive, so `qInTitle` and `qintitle` are
// equivalent). The sets mirror the server-side filter mapping and the official
// Python/PHP clients.
// equivalent). The sets mirror the server-side filter mapping.

export const BASE_URL = 'https://newsdata.io/api';

Expand Down Expand Up @@ -222,15 +221,14 @@ export const FILTERS = Object.freeze({
],
// Real-time query registration. The real-time service is v2 only, so these
// are the v2 filter names. No date or paging filters apply -- a registered
// query matches news as it is published. `news_type` is set by
// websocketRegister, not by the caller.
// query matches news as it is published. `news_type` is not accepted from
// the caller: websocketRegister sets it after validation.
websocket_register: [
'q', 'q_in_title', 'q_in_meta', 'country', 'exclude_country', 'category',
'exclude_category', 'language', 'exclude_language', 'source_url',
'exclude_source_url', 'source_priority', 'timezone', 'content', 'image',
'video', 'remove_duplicate', 'tag', 'sentiment', 'sentiment_score',
'region', 'organization', 'creator', 'datatype', 'exclude_field',
'news_type',
],
websocket_fetch: [],
websocket_delete: ['registration_id'],
Expand Down
13 changes: 10 additions & 3 deletions src/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,18 @@ export class NewsdataWebSocketError extends NewsdataError {
/**
* @param {string} message
* @param {Error|null} [cause] The underlying error.
* @param {object} [details]
* @param {object|null} [details.responseBody] The error response the server
* sent before closing ({status:"error", results:{message, code}}), if any.
* @param {string|null} [details.code] The server's error code, e.g.
* "Unauthorized" or "ServerError".
*/
constructor(message, cause = null) {
constructor(message, cause = null, { responseBody = null, code = null } = {}) {
super(message);
this.name = 'NewsdataWebSocketError';
if (cause) this.cause = cause;
this.responseBody = responseBody;
this.code = code;
}
}

Expand All @@ -114,8 +121,8 @@ export class NewsdataWebSocketError extends NewsdataError {
* exhausted quota. Never retried, regardless of the `reconnect` setting.
*/
export class NewsdataWebSocketAuthError extends NewsdataWebSocketError {
constructor(message, cause = null) {
super(message, cause);
constructor(message, cause = null, details = {}) {
super(message, cause, details);
this.name = 'NewsdataWebSocketAuthError';
}
}
Expand Down
Loading
Loading