UNPKG

onesky-api-wrapper

Version:
82 lines (81 loc) 3.27 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { md5 } from './md5.js'; export class HttpHelper { constructor({ baseUrl, apiKey, secret }) { this._baseUrl = 'https://platform.api.onesky.io/1'; this._apiKey = ''; this._secret = ''; if (baseUrl) { this._baseUrl = baseUrl; } this._apiKey = apiKey; this._secret = secret; } get(endpoint, queryParams) { return __awaiter(this, void 0, void 0, function* () { const url = this._buildUrl(endpoint, queryParams); const response = yield fetch(url); const result = this._parseResponse(response); return result; }); } post(endpoint, queryParams) { return __awaiter(this, void 0, void 0, function* () { const url = this._buildUrl(endpoint, queryParams); const response = yield fetch(url, { method: 'POST' }); const result = this._parseResponse(response); return result; }); } put(endpoint, queryParams) { return __awaiter(this, void 0, void 0, function* () { const url = this._buildUrl(endpoint, queryParams); const response = yield fetch(url, { method: 'PUT' }); const result = this._parseResponse(response); return result; }); } delete(endpoint, queryParams) { return __awaiter(this, void 0, void 0, function* () { const url = this._buildUrl(endpoint, queryParams); const response = yield fetch(url, { method: 'DELETE' }); const result = this._parseResponse(response); return result; }); } _buildUrl(endpoint, queryParams) { const { hash, timestamp } = this._devhash(); let url = `${this._baseUrl}/${endpoint}?` + new URLSearchParams({ api_key: this._apiKey, timestamp: timestamp.toString(), dev_hash: hash, }); if (queryParams) { url = url + '&' + queryParams; } return url; } _parseResponse(response) { return __awaiter(this, void 0, void 0, function* () { const data = JSON.stringify(yield response.json()); const result = JSON.parse(data); return result; }); } _devhash() { const timestamp = Math.floor(Date.now() / 1000); return { hash: md5(timestamp + this._secret), timestamp, }; } }