etymo-js
Version:
NodeJS and browser util for fetching etymology results from https://www.etymonline.com
67 lines (66 loc) • 2.99 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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Etymo = void 0;
const cheerioOps_1 = require("./lib/cheerioOps");
const getHtml_1 = require("./lib/getHtml");
const util_1 = require("./lib/util");
const constants_1 = require("./constants");
class Etymo {
search(term) {
return __awaiter(this, void 0, void 0, function* () {
const url = this._buildSearchUrl(term);
const html = yield (0, getHtml_1.getHtml)(url);
const entries = (0, cheerioOps_1.getEntriesFromSearch)(html);
return entries;
});
}
get(path, opts = {}) {
return __awaiter(this, void 0, void 0, function* () {
const { lang } = opts;
if (!!lang && !(0, util_1.isLanguage)(lang)) {
throw new Error(`Language '${lang}' unknown`);
}
const trimmedPath = path.replace(/^\/[a-z]{2}\/word\//, "/word/");
const url = this._buildGetUrl(trimmedPath, { lang });
const html = yield (0, getHtml_1.getHtml)(url);
const isNotEnglish = lang && lang !== "en" ? true : false;
const entryWithoutPathId = (0, cheerioOps_1.getEntryWithoutPathId)(html, isNotEnglish);
const resolvedPath = isNotEnglish ? `/${lang}` + trimmedPath : path;
const id = (0, util_1.getIdFromPath)(path);
const entry = Object.assign(Object.assign({}, entryWithoutPathId), { path: resolvedPath, id });
return entry;
});
}
trending() {
return __awaiter(this, void 0, void 0, function* () {
const url = "https://www.etymonline.com/api/etymology/trending";
const json = (yield (0, getHtml_1.getJson)(url));
return json.data.items;
});
}
_buildSearchUrl(term) {
const baseUrl = `${constants_1.BASE_URL}/search`;
const urlEncodedTerm = encodeURIComponent(term);
const url = `${baseUrl}?q=${urlEncodedTerm}`;
return url;
}
_buildGetUrl(path, opts = {}) {
const { lang } = opts;
let baseUrl = constants_1.BASE_URL;
if (!!lang && lang !== "en") {
baseUrl += `/${lang}`;
}
const url = baseUrl + path;
return url;
}
}
exports.Etymo = Etymo;