UNPKG

lunify.js

Version:

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

164 lines 6.03 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RestManager = void 0; const rest_1 = require("../../../interfaces/rest"); const __1 = require("../.."); class RestManager { client; basicAuthorization; constructor(client) { this.client = client; this.basicAuthorization = null; if (client) { this.basicAuthorization = this.makeSecretString(client.options.clientId, client.options.clientSecret); } } makeSecretString(clientId, clientSecret) { return "Basic " + Buffer.from(clientId + ":" + clientSecret).toString("base64"); } setBasicAuthorization(clientId, clientSecret) { this.basicAuthorization = this.makeSecretString(clientId, clientSecret); return this; } resolveUrl(domain, route, query) { return `${domain || __1.RequestDomain.Api}${route}${query ? `?${query}` : ""}`; } async resolveRequest(request) { 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) { if (!this.basicAuthorization) throw new Error(__1.LunifyErrors.RequireBasicAuth); headers.Authorization = this.basicAuthorization; } if (request.advancedAuthRequired) { if (!this.client) throw new Error(__1.LunifyErrors.RequireAdvancedAuth); headers.Authorization = await this.client.credentials.getAuthorization(); } const url = this.resolveUrl(request.domain, request.route, query); const method = request.method.toUpperCase(); const contentType = request.headers?.["Content-Type"]?.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: { ...request.headers, ...headers }, method } }; } async makeRequest(url, options) { let res; try { res = await fetch(url, options); } catch (error) { if (!(error instanceof Error)) throw error; if ((("code" in error && error.code === "ECONNRESET") || error.message.includes("ECONNRESET"))) { throw error; } throw error; } if (res.status < 200 || res.status >= 300) { const errorText = await res.text(); const error = new Error(res.status + " " + url + ": " + errorText); // @ts-expect-error - Error does not natively support info property error.info = { status: res.status, url, 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 }; } async parseResponse(res) { const contentType = res.headers.get("content-type"); if (contentType?.startsWith("application/json")) return await res.json(); if (contentType?.startsWith("text/html")) return res.text(); if (contentType?.startsWith("image")) return await res.arrayBuffer(); return await res.text(); } async request(options) { const { url, fetchOptions } = await this.resolveRequest(options); const res = await this.makeRequest(url, fetchOptions); return await 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({ ...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({ ...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({ ...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({ ...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({ ...options, route, method: rest_1.RequestMethod.Patch }); } } exports.RestManager = RestManager; //# sourceMappingURL=index.js.map