UNPKG

lunify.js

Version:

A basic api wrapper for the spotify api covering the oauth routes.

165 lines 7.1 kB
"use strict"; 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RestManager = void 0; const __1 = require("../.."); const rest_1 = require("../../../interfaces/rest"); class RestManager { constructor(client) { this.client = client; } resolveUrl(domain, route, query) { return `${domain || __1.RequestDomain.Api}${route}${query ? `?${query}` : ''}`; } resolveRequest(request) { var _a, _b; return __awaiter(this, void 0, void 0, function* () { let query = ''; if (request.query) { const resolvedQuery = new URLSearchParams(Object.fromEntries(Object.entries(request.query).map(([key, value]) => [key, value.toString()]))).toString(); if (resolvedQuery !== '') query = resolvedQuery; } const headers = { 'User-Agent': __1.userAgent.trim() }; if (request.authRequired) { headers.Authorization = 'Basic ' + Buffer.from(this.client.options.clientId + ':' + this.client.options.clientSecret).toString('base64'); } if (request.advancedAuthRequired) { headers.Authorization = yield this.client.credentials.getAuthorization(); } const url = this.resolveUrl(request.domain, request.route, query); const method = request.method.toUpperCase(); const contentType = (_b = (_a = request.headers) === null || _a === void 0 ? void 0 : _a['Content-Type']) === null || _b === void 0 ? void 0 : _b.toLowerCase(); let finalBody; if (request.body && typeof request.body !== 'string' && (!contentType || contentType === 'application/json')) { finalBody = JSON.stringify(request.body); } if (!finalBody) finalBody = request.body; return { url, fetchOptions: { body: ['GET', 'HEAD'].includes(method) ? undefined : finalBody, headers: Object.assign(Object.assign({}, request.headers), headers), method } }; }); } makeRequest(url, options) { return __awaiter(this, void 0, void 0, function* () { let res; try { res = yield fetch(url, options); } catch (error) { if (!(error instanceof Error)) throw error; if ((('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET'))) { return null; } throw error; } if (res.status < 200 || res.status >= 300) { const errorText = yield res.text(); const error = new Error(res.status + ' ' + url + ': ' + errorText); // @ts-expect-error error.info = { status: res.status, url: url, errorText: errorText }; throw error; } return { body: res.body, arrayBuffer() { return res.arrayBuffer(); }, json() { return res.json(); }, text() { return res.text(); }, bodyUsed: res.bodyUsed, headers: res.headers, status: res.status, ok: res.ok }; }); } parseResponse(res) { return __awaiter(this, void 0, void 0, function* () { const contentType = res.headers.get('content-type'); if (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('application/json')) return yield res.json(); if (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('text/html')) return res.text(); if (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('image')) return yield res.arrayBuffer(); return yield res.text(); }); } request(options) { return __awaiter(this, void 0, void 0, function* () { const { url, fetchOptions } = yield this.resolveRequest(options); const res = yield this.makeRequest(url, fetchOptions); return yield this.parseResponse(res); }); } /** * Send a GET request to the spotify api * @param {string} route - The full route to query * @param {RequestData?} options - Optional request options */ get(route, options = {}) { return this.request(Object.assign(Object.assign({}, options), { route, method: rest_1.RequestMethod.Get })); } /** * Send a DELETE request to the spotify api * @param {string} route - The full route to query * @param {RequestData?} options - Optional request options */ delete(route, options = {}) { return this.request(Object.assign(Object.assign({}, options), { route, method: rest_1.RequestMethod.Delete })); } /** * Send a POST request to the spotify api * @param {string} route - The full route to query * @param {RequestData?} options - Optional request options */ post(route, options = {}) { return this.request(Object.assign(Object.assign({}, options), { route, method: rest_1.RequestMethod.Post })); } /** * Send a PUT request to the spotify api * @param {string} route - The full route to query * @param {RequestData?} options - Optional request options */ put(route, options = {}) { return this.request(Object.assign(Object.assign({}, options), { route, method: rest_1.RequestMethod.Put })); } /** * Send a PATCH request to the spotify api * @param {string} route - The full route to query * @param {RequestData?} options - Optional request options */ patch(route, options = {}) { return this.request(Object.assign(Object.assign({}, options), { route, method: rest_1.RequestMethod.Patch })); } } exports.RestManager = RestManager; //# sourceMappingURL=index.js.map