media-grab
Version:
Grab random media from the internet
127 lines (126 loc) • 4.76 kB
JavaScript
import axios from '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;
}
async get(url, data = {}) {
return this._sendRequest('GET', API_BASE_URL + url, data);
}
async post(url, data = {}) {
return this._sendRequest('POST', API_BASE_URL + url, data);
}
async patch(url, data = {}) {
return this._sendRequest('PATCH', API_BASE_URL + url, data);
}
async put(url, data = {}) {
return this._sendRequest('PUT', API_BASE_URL + url, data);
}
async delete(url, data = {}) {
return this._sendRequest('DELETE', API_BASE_URL + url, data);
}
async _sendRequest(method, url, data) {
const token = await this._getToken();
const body = await 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;
}
async _getToken() {
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 = await axios.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}`);
}
}
async _makeRequest(method, url, data, token) {
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 = await axios(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?.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}`);
}
}
}
export default Reddit;