UNPKG

@rr0/cms

Version:

RR0 Content Management System (CMS)

61 lines (60 loc) 2.27 kB
import { HttpSource } from "../HttpSource.js"; import { JSDOM } from "jsdom"; import { SceauDatasource } from "./SceauDatasource.js"; import path from "path"; export class SceauHttpDatasource extends SceauDatasource { constructor(baseUrl, searchPath = "fonds") { super(); this.baseUrl = baseUrl; this.searchPath = searchPath; this.http = new HttpSource(); } getFromRows(context, rows, fields) { const cases = []; for (const row of rows) { if (row.hasChildNodes()) { cases.push(this.getFromRow(context, row, fields)); } } return cases; } queryUrl(context, fondPath) { const day = context.time.getDayOfMonth(); const month = context.time.getMonth(); const year = context.time.getYear(); return new URL(path.join(this.searchPath, fondPath), this.baseUrl); } async readCases(context) { let allCases = []; for (const fetchedPage of this.pages) { const searchUrl = this.queryUrl(context, fetchedPage.path); const page = await this.http.fetch(searchUrl); const doc = new JSDOM(page).window.document.documentElement; const rowEls = doc.querySelectorAll("tr"); const rows = Array.from(rowEls); const header = rows.shift(); const headings = Array.from(header.querySelectorAll("td")).map(header => header.textContent); const fields = []; for (const heading of headings) { const entries = Object.entries(fetchedPage.mapping); for (const [field, label] of entries) { if (label === heading) { fields.push(field); break; } } } const fondCases = this.getFromRows(context, rows, fields); allCases = allCases.concat(fondCases); } return allCases; } getFromRow(context, row, fields) { const values = row.querySelectorAll("td"); const obj = {}; for (let i = 0; i < values.length; i++) { obj[fields[i]] = values[i].textContent; } return obj; } }