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
26 changes: 23 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,13 +241,14 @@ await client.deleteApplication('myapp');
```typescript
await client.updateVersion('myapp', '1.0.0', {
releaseNotes: 'Bug fixes',
isActive: true,
isEnabled: true,
minimumClientVersion: '0.9.0',
totpCode: '123456',
totpCode: '123456', // required to enable a version when the tenant has TOTP on
});
```

The API only applies `releaseNotes`, `isEnabled` and `totpCode`. The `isActive` and
`minimumClientVersion` options are deprecated and ignored.

### Manage Customers

```typescript
Expand Down Expand Up @@ -358,6 +359,7 @@ interface ApiError {
message: string;
details?: Record<string, unknown>;
timestamp?: string;
httpStatus?: number; // set for every non-2xx response
}
```

Expand Down Expand Up @@ -403,6 +405,24 @@ if (response.success && response.data) {
}
```

Error codes come from two places:

- **The API's error envelope:** upper case, e.g. `BAD_REQUEST`, `UNAUTHORIZED`, `NOT_FOUND`.
- **The client**, for responses that aren't the envelope (auth middleware, rate limiter,
gateway error pages): lower case and derived from the HTTP status: `bad_request`,
`unauthorized`, `forbidden`, `not_found`, `conflict`, `rate_limited`, `server_error`,
`http_error`. The client also uses `TIMEOUT` when a request exceeds `timeout`, and
`NETWORK_ERROR` when the request fails or a successful response isn't JSON.

So compare codes case-insensitively, or check `response.error?.httpStatus`, which is set for
every non-2xx response:

```typescript
if (response.error?.httpStatus === 429) {
// back off and retry
}
```

For download operations, errors are thrown as exceptions:

```typescript
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bindist/client",
"version": "1.0.1",
"version": "1.0.2",
"description": "TypeScript/JavaScript client for the BinDist API",
"main": "dist/index.js",
"module": "dist/index.mjs",
Expand Down
73 changes: 71 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,14 @@ export class BinDistClient {
signal: controller.signal,
});

const text = await response.text();
clearTimeout(timeoutId);

const data = await response.json();
return data as ApiResponse<T>;
if (!response.ok) {
return errorResponse<T>(response.status, response.statusText, text);
}

return JSON.parse(text) as ApiResponse<T>;
} catch (error) {
clearTimeout(timeoutId);

Expand Down Expand Up @@ -390,6 +394,71 @@ export class BinDistClient {
}
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}

/**
* Build the response for a non-2xx status. Uses the API's error envelope when
* the body has one; otherwise (auth middleware, rate limiter, gateway HTML
* page, empty body) synthesizes an error from the HTTP status. Either way the
* status is kept in `error.httpStatus`.
*/
function errorResponse<T>(
status: number,
statusText: string,
text: string
): ApiResponse<T> {
let body: unknown;
try {
body = JSON.parse(text);
} catch {
body = undefined;
}

if (isRecord(body) && isRecord(body.error) && typeof body.error.code === 'string') {
const envelope = body as unknown as ApiResponse<T>;
return {
success: false,
error: { ...envelope.error!, httpStatus: status },
meta: envelope.meta,
};
}

let message = '';
if (isRecord(body)) {
// Bare {"message": "..."} or {"error": "..."} bodies
if (typeof body.message === 'string') {
message = body.message;
} else if (typeof body.error === 'string') {
message = body.error;
}
}

return {
success: false,
error: {
code: codeForStatus(status),
message: message || statusText || `HTTP ${status}`,
httpStatus: status,
},
};
}

/**
* Stable lower-case error code for an HTTP status, matching the other BinDist clients.
*/
function codeForStatus(status: number): string {
if (status === 400) return 'bad_request';
if (status === 401) return 'unauthorized';
if (status === 403) return 'forbidden';
if (status === 404) return 'not_found';
if (status === 409) return 'conflict';
if (status === 429) return 'rate_limited';
if (status >= 500) return 'server_error';
return 'http_error';
}

/**
* Create a new BinDist client instance
*/
Expand Down
13 changes: 12 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@
*/

/**
* Represents an error returned by the API
* Represents an error returned by the API.
*
* Errors from the API's own error envelope carry upper-case codes such as
* `NOT_FOUND`. Errors from layers in front of the API (auth middleware, rate
* limiters, gateways) don't use the envelope; for those the client derives a
* lower-case code from the HTTP status (`unauthorized`, `rate_limited`,
* `server_error`, ...). Compare codes case-insensitively, or use `httpStatus`.
*/
export interface ApiError {
code: string;
message: string;
details?: Record<string, unknown>;
timestamp?: string;
/** HTTP status of the response; set for every non-2xx response. */
httpStatus?: number;
}

/**
Expand Down Expand Up @@ -94,9 +102,12 @@ export interface GetDownloadInfoOptions {
*/
export interface UpdateVersionOptions {
releaseNotes?: string | null;
/** @deprecated Ignored by the API; only `releaseNotes`, `isEnabled` and `totpCode` are applied. */
isActive?: boolean;
isEnabled?: boolean;
/** @deprecated Ignored by the API; only `releaseNotes`, `isEnabled` and `totpCode` are applied. */
minimumClientVersion?: string;
/** 6-digit TOTP code; required when setting `isEnabled: true` on a tenant with TOTP enabled. */
totpCode?: string;
}

Expand Down
Loading