UNPKG

@wristband/express-auth

Version:

SDK for integrating your ExpressJS application with Wristband. Handles user authentication, session management, and token management.

61 lines (60 loc) 2.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WristbandApiClient = void 0; const fetch_error_1 = require("./error/fetch-error"); const constants_1 = require("./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. */ class WristbandApiClient { constructor(wristbandApplicationVanityDomain) { this.baseURL = `https://${wristbandApplicationVanityDomain}/api/v1`; this.defaultHeaders = { 'Content-Type': constants_1.FORM_URLENCODED_MEDIA_TYPE, Accept: constants_1.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 fetch_error_1.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 }); } } exports.WristbandApiClient = WristbandApiClient;