const path = require('path'); const fs = require('fs'); const snarkdown = require('snarkdown'); const fecha = require('fecha'); module.exports = function (app) { app.server.get('/history', (req, res) => { const files = fs.readdirSync(app.historyLocation).filter(fileName => fileName.includes('.json')) .map(fileName => { // Cache the file data so sorting doesn't need to re-check each file return { name: fileName, time: fs.statSync(path.resolve(app.historyLocation, fileName)).mtime.getTime() }; }).sort((a, b) => b.time - a.time).map(v => v.name); // Sort from newest to oldest. let history = files.map(fileName => { const bookData = JSON.parse(fs.readFileSync(path.resolve(app.historyLocation, fileName), 'utf8')); bookData.author = bookData.author ? bookData.author : 'author not provided'; bookData.contributor = bookData.contributor ? bookData.contributor : 'Anonymous'; const id = fileName.replace('.json', ''); const added = fecha.format(new Date(bookData.added), 'hh:mm:ssA on dddd MMMM Do, YYYY'); const removed = fecha.format(new Date(parseInt(id)), 'hh:mm:ssA on dddd MMMM Do, YYYY'); const removedTag = '
Taken' + removed + '
'; const modal = app.templater.fill('./templates/elements/modalCard.html', { id, header: '

' + bookData.title + '

' + bookData.author + '

', content: app.templater.fill('./templates/elements/bookInfo.html', { contributor: bookData.contributor, fileFormat: bookData.fileType, added, removedTag, summary: snarkdown(bookData.summary), }), footer: 'Close', }); return app.templater.fill('./templates/elements/book_readable.html', { id, title: bookData.title, author: bookData.author, fileType: bookData.fileType, modal, }); }).join(''); if (history == '') { history = '
No books have been taken yet. Would you like to take a book?
'; } const body = '

History

' + history + '
'; const html = app.templater.fill('./templates/htmlContainer.html', { title: 'History', resourcePath: (req.url.substr(-1) === '/' ? '../' : './'), body }); if (html) { res.send(html); } else { res.send('Something went wrong!'); } }); }