@wristband/nextjs-auth
Version:
SDK for integrating your NextJS application with Wristband. Handles user authentication and token management.
30 lines (29 loc) • 1.3 kB
JavaScript
import { FetchError } from './error';
import { FORM_URLENCODED_MEDIA_TYPE, JSON_MEDIA_TYPE } from './utils/constants';
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;
}
async get(endpoint, headers = {}) {
return this.request(endpoint, { method: 'GET', headers, keepalive: true });
}
async post(endpoint, body, headers = {}) {
return this.request(endpoint, { method: 'POST', headers, body, keepalive: true });
}
}