UNPKG

knack-nest

Version:
65 lines (58 loc) 1.56 kB
import FormData from 'form-data'; import got, { Method } from 'got'; import { GenericObject, KnackConstructorArgs } from "knack-sdk/dist/types"; const knackUrl = 'https://api.knack.com' export class KnackConnection { private apiKey:string; private appId: string; private host: string; private token: string constructor(options: KnackConstructorArgs){ this.apiKey = options.apiKey; this.appId = options.appId; this.host = (options.host || knackUrl) + '/v1/'; } public get appid(){ return this.appId; } public get apiToken(){ return this.apiToken; } set apiToken(val: string){ this.token = val } async request<response>( path: string, { method = 'GET', json, searchParams, body: submittedBody, timeoutSeconds = 1000 }: { body?: FormData json?: GenericObject method: Method searchParams?: GenericObject timeoutSeconds?: number } = { method: 'GET' } ) { const { body } = await got(path, { prefixUrl: this.host, headers: { 'X-Knack-Application-Id': this.appId, 'X-Knack-REST-API-Key': this.apiKey, token: this.token, }, method, timeout: { request: (1000 * timeoutSeconds) }, retry: { limit: 5, methods: ['GET', 'POST', 'PUT', 'DELETE'], statusCodes: [429, 503] }, ...(submittedBody && { body: submittedBody }), ...(json && { json }), ...(searchParams && { searchParams }) }) return JSON.parse(body) as response } }