media-grab
Version:
Grab random media from the internet
157 lines (156 loc) • 6.7 kB
JavaScript
;
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());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
const TOKEN_BASE_URL = 'https://www.reddit.com/api/v1/access_token';
const API_BASE_URL = 'https://oauth.reddit.com';
const REQUEST_TIMEOUT = 30 * 1000;
class Reddit {
constructor(opts) {
this.username = opts.username;
this.password = opts.password;
this.appId = opts.appId;
this.appSecret = opts.appSecret;
this.userAgent = opts.userAgent || 'reddit';
this.token = null;
this.tokenExpireDate = 0;
}
get(url, data = {}) {
return __awaiter(this, void 0, void 0, function* () {
return this._sendRequest('GET', API_BASE_URL + url, data);
});
}
post(url, data = {}) {
return __awaiter(this, void 0, void 0, function* () {
return this._sendRequest('POST', API_BASE_URL + url, data);
});
}
patch(url, data = {}) {
return __awaiter(this, void 0, void 0, function* () {
return this._sendRequest('PATCH', API_BASE_URL + url, data);
});
}
put(url, data = {}) {
return __awaiter(this, void 0, void 0, function* () {
return this._sendRequest('PUT', API_BASE_URL + url, data);
});
}
delete(url, data = {}) {
return __awaiter(this, void 0, void 0, function* () {
return this._sendRequest('DELETE', API_BASE_URL + url, data);
});
}
_sendRequest(method, url, data) {
return __awaiter(this, void 0, void 0, function* () {
const token = yield this._getToken();
const body = yield this._makeRequest(method, url, data, token);
const errors = body && body.json && body.json.errors;
if (errors && errors.length > 0) {
const err = new Error(errors.map(error => `${error[0]}: ${error[1]} (${error[2]})`).join('. '));
err.code = errors[0][0];
err.codes = errors.map(error => error[0]);
throw err;
}
return body;
});
}
_getToken() {
return __awaiter(this, void 0, void 0, function* () {
if (Date.now() / 1000 <= this.tokenExpireDate)
return this.token;
// Setup query params
const params = new URLSearchParams();
params.append('grant_type', 'password');
params.append('username', this.username);
params.append('password', this.password);
// Setup request config
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
auth: {
username: this.appId,
password: this.appSecret,
},
};
try {
// Make the token request
const res = yield axios_1.default.post(TOKEN_BASE_URL, params, config);
// Throw an error if the response code is not 2xx
if (res.status < 200 || res.status >= 300)
throw new Error(`${res.status} ${res.statusText}`);
// Unpack token data
const { access_token: accessToken, expires_in: expiresIn, token_type: tokenType } = res.data;
// Check token
if (tokenType == null || accessToken == null)
throw new Error(`Cannot obtain token for username ${this.username}. ${res.data.error}. ${res.data.error_description}.`);
// Create well-formed token
this.token = `${tokenType} ${accessToken}`;
// Shorten and set token expiration time
this.tokenExpireDate = ((Date.now() / 1000) + expiresIn) / 2;
// Return token
return this.token;
}
catch (error) {
throw new Error(`Failed to get token: ${error.message}`);
}
});
}
_makeRequest(method, url, data, token) {
return __awaiter(this, void 0, void 0, function* () {
const opts = {
method,
url,
data,
headers: {
'user-agent': this.userAgent,
authorization: token
},
timeout: REQUEST_TIMEOUT
};
// Request JSON API response type
data.api_type = 'json';
opts.json = true;
// Handle request type
switch (method) {
case 'GET':
opts.params = data;
break;
case 'POST':
opts.form = data;
break;
case 'PATCH':
case 'PUT':
case 'DELETE':
opts.body = data;
break;
default:
throw new Error(`Unsupported request method: ${method}`);
}
try {
// Make request
const res = yield (0, axios_1.default)(opts);
// Throw an error if the response code is not 2xx or if the data are stinky
if (res.status < 200 || res.status >= 300 || !(res === null || res === void 0 ? void 0 : res.data))
throw new Error(`${res.status} ${res.statusText}`);
// Gibbe da data pls
return res.data;
}
catch (error) {
throw new Error(`Error making request: ${error.message}`);
}
});
}
}
exports.default = Reddit;