UNPKG

toggl-webhook

Version:
80 lines (79 loc) 2.71 kB
import got, { HTTPError, } from 'got'; import { BadRequestError, ForbiddenError, NotFoundError } from './errors.js'; export class TogglHttpClient { constructor(options) { Object.defineProperty(this, "baseUrl", { enumerable: true, configurable: true, writable: true, value: 'https://track.toggl.com/webhooks/api/v1/' }); Object.defineProperty(this, "apiToken", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "userAgent", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.apiToken = options.apiToken; this.userAgent = options.userAgent || 'node toggl-webhook'; } async get(endpoint, searchParams) { return this.dispatchRequest(endpoint, 'GET', searchParams); } async post(endpoint, json, searchParams) { return this.dispatchRequest(endpoint, 'POST', searchParams, json); } async put(endpoint, json, searchParams) { return this.dispatchRequest(endpoint, 'PUT', searchParams, json); } async patch(endpoint, json, searchParams) { return this.dispatchRequest(endpoint, 'PATCH', searchParams, json); } async delete(endpoint, searchParams) { return this.dispatchRequest(endpoint, 'DELETE', searchParams); } async dispatchRequest(endpoint, method, searchParams, json) { const options = { method, url: endpoint, searchParams, prefixUrl: this.baseUrl, retry: { limit: 0 }, username: this.apiToken, password: 'api_token', responseType: 'json', headers: { 'user-agent': this.userAgent, } }; if (['POST', 'PATCH', 'PUT'] && json) { options.json = json; } try { const { body } = await got(options); return body; } catch (err) { if (err instanceof HTTPError) { const { body, statusCode } = err.response; const message = typeof body === 'string' ? body : err.message; switch (statusCode) { case 400: throw new BadRequestError(message); case 403: throw new ForbiddenError(message); case 404: throw new NotFoundError(message); } } throw err; } } }