@wristband/express-auth
Version:
SDK for integrating your ExpressJS application with Wristband. Handles user authentication, session management, and token management.
57 lines (56 loc) • 2.3 kB
JavaScript
import { FetchError } from './error/fetch-error';
import { FORM_URLENCODED_MEDIA_TYPE, JSON_MEDIA_TYPE } from './utils/constants';
/**
* Thin fetch-based HTTP client for the Wristband API.
*
* Wraps native `fetch` (Node 20+) with a base URL, default headers, and
* structured error handling. Non-2xx responses are thrown as {@link FetchError}
* instances carrying both the raw `Response` and the parsed body.
*/
export class WristbandApiClient {
constructor(wristbandApplicationVanityDomain) {
this.baseURL = `https://${wristbandApplicationVanityDomain}/api/v1`;
this.defaultHeaders = {
'Content-Type': FORM_URLENCODED_MEDIA_TYPE,
Accept: JSON_MEDIA_TYPE,
};
}
async request(endpoint, options = {}) {
const url = `${this.baseURL}${endpoint}`;
const headers = { ...this.defaultHeaders, ...options.headers };
const config = { ...options, headers };
const response = await fetch(url, config);
if (response.status === 204) {
return undefined;
}
const responseBodyText = await response.text();
const responseBody = responseBodyText ? JSON.parse(responseBodyText) : undefined;
if (response.status >= 400) {
throw new FetchError(response, responseBody);
}
return responseBody;
}
/**
* Performs a GET request to the given API endpoint.
*
* @param endpoint - Path relative to the base URL.
* @param headers - Optional additional or override headers.
* @returns The parsed JSON response body.
* @throws {FetchError} On non-2xx responses.
*/
async get(endpoint, headers = {}) {
return this.request(endpoint, { method: 'GET', headers, keepalive: true });
}
/**
* Performs a POST request to the given API endpoint.
*
* @param endpoint - Path relative to the base URL.
* @param body - Request body (typically a form-encoded string).
* @param headers - Optional additional or override headers.
* @returns The parsed JSON response body.
* @throws {FetchError} On non-2xx responses.
*/
async post(endpoint, body, headers = {}) {
return this.request(endpoint, { method: 'POST', headers, body, keepalive: true });
}
}