Select Git revision
-
Markus Opolka authoredMarkus Opolka authored
api.js 4.87 KiB
const express = require('express')
const path = require('path')
const fs = require('fs')
const crypto = require('crypto')
const cache = require('memory-cache')
const convert = require('xml-js')
const lib = require('./lib.js')
// Settings
const DIR = 'letters'
const app = express()
const PORT = 3000
function loadDocAsJson (filepath) {
/*
* TODO: Maybe check if XML is valid?
* Reads XML file and transforms it to JSON
*/
let data = {}
try {
let xml = fs.readFileSync(filepath, 'utf8')
data = convert.xml2js(xml, {compact: true})
} catch (err) {
console.log('> Error while loading ' + filepath)
console.log(err)
return data
}
return data
}
function inCacheFormat (docname, docobj) {
/*
* Create some metadata for document cache representation
*/
let hash = crypto.createHmac('sha256', JSON.stringify(docobj)).digest('hex')
return {
link: '/letters/' + docname.slice(0, -4),
collection: docobj.TEI.teiHeader.fileDesc.titleStmt.collection._text,
url: '/api/letters/' + docname.slice(0, -4),
name: docname.replace(/_/g, ' '),
hash: hash,
object: docobj
}
}
function loadDocumentsToCache (dir) {
/*
* Load all documents to cache
*/
try {
var documents = fs.readdirSync(dir)
} catch (err) {
console.log('> Error while loading files from ' + dir)
console.log(err)
}
for (let docname of documents) {
// We just want the XML documents
if (!docname.endsWith('.xml')) {
continue
}
let docjs = loadDocAsJson(path.join(dir, docname))
cache.put(docname, inCacheFormat(docname, docjs))