omeku-api
Version:
JS wrapper for https://omeku.glitch.me
46 lines (42 loc) • 1.33 kB
JavaScript
const {get} = require('https');
const {URL, URLSearchParams} = require('url');
const endpoints = require('./endpoints.json');
function getContent(url) {
return new Promise((resolve, reject) => {
get(url, (res) => {
const {statusCode} = res;
if(statusCode !== 200) {
res.resume();
reject(`Request failed. Status code: ${statusCode}`);
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => {rawData += chunk});
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
resolve(parsedData);
} catch(e) {
reject(`Error: ${e.message}`);
}
});
}).on('error', (err) => {
reject(`Error: ${err.message}`);
})
});
}
class OmekuClient {
constructor() {
let self = this;
self.api = {};
let baseURL = 'https://omeku.glitch.me/api/v1';
Object.keys(endpoints.api).forEach(async (endpoint) => {
self.api[endpoint] = async function (queryParams = '') {
let url = new URL(`${baseURL}${endpoints.api[endpoint]}`);
queryParams !== '' ? url.search = new URLSearchParams(queryParams) : '';
return await getContent(url.toString());
};
});
}
}
module.exports = OmekuClient;