purai.js
Version:
NPM package for PurAI API
62 lines (61 loc) • 1.85 kB
JavaScript
import { ApiRequestMethod } from '../types/api.js';
import PurAiApiError from './PurAiApiError.js';
export class Http {
key;
baseUrl;
constructor(key, baseUrl) {
this.key = key;
this.baseUrl = baseUrl;
}
;
async check(response) {
const body = await response.json().catch(() => null);
if (!response.ok) {
switch (response.status) {
case 400:
{
throw new PurAiApiError(response, body, 'Invalid request');
}
;
case 500:
{
throw new PurAiApiError(response, body, 'An internal server error occurred while processing the request, try again later');
}
;
default:
{
throw new PurAiApiError(response, body, 'Unknown error');
}
;
}
;
}
;
if (!body || body.error)
throw new PurAiApiError(response, body, 'Unknown error');
return body;
}
;
request(method, path, options) {
return fetch(`${this.baseUrl}/${path}`, {
method,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.key}`
},
body: typeof options?.body === 'object' ? JSON.stringify(options.body) : undefined
});
}
;
async get(path) {
const response = await this.request(ApiRequestMethod.Get, path);
return this.check(response);
}
;
async post(path, body) {
const response = await this.request(ApiRequestMethod.Post, path, { body });
return this.check(response);
}
;
}
;