RESTManager.js (1708B)
1 'use strict'; 2 3 const APIRequest = require('./APIRequest'); 4 const routeBuilder = require('./APIRouter'); 5 const RequestHandler = require('./RequestHandler'); 6 const { Error } = require('../errors'); 7 const Collection = require('../util/Collection'); 8 const { Endpoints } = require('../util/Constants'); 9 10 class RESTManager { 11 constructor(client, tokenPrefix = 'Bot') { 12 this.client = client; 13 this.handlers = new Collection(); 14 this.tokenPrefix = tokenPrefix; 15 this.versioned = true; 16 this.globalTimeout = null; 17 if (client.options.restSweepInterval > 0) { 18 client.setInterval(() => { 19 this.handlers.sweep(handler => handler._inactive); 20 }, client.options.restSweepInterval * 1000); 21 } 22 } 23 24 get api() { 25 return routeBuilder(this); 26 } 27 28 getAuth() { 29 const token = this.client.token || this.client.accessToken; 30 if (token) return `${this.tokenPrefix} ${token}`; 31 throw new Error('TOKEN_MISSING'); 32 } 33 34 get cdn() { 35 return Endpoints.CDN(this.client.options.http.cdn); 36 } 37 38 push(handler, apiRequest) { 39 return new Promise((resolve, reject) => { 40 handler 41 .push({ 42 request: apiRequest, 43 resolve, 44 reject, 45 retries: 0, 46 }) 47 .catch(reject); 48 }); 49 } 50 51 request(method, url, options = {}) { 52 const apiRequest = new APIRequest(this, method, url, options); 53 let handler = this.handlers.get(apiRequest.route); 54 55 if (!handler) { 56 handler = new RequestHandler(this); 57 this.handlers.set(apiRequest.route, handler); 58 } 59 60 return this.push(handler, apiRequest); 61 } 62 63 set endpoint(endpoint) { 64 this.client.options.http.api = endpoint; 65 } 66 } 67 68 module.exports = RESTManager;