add db function

This commit is contained in:
Mats van Reenen 2020-07-28 15:31:25 +02:00
parent 02b546a5c4
commit 62f3c08aad
2 changed files with 99 additions and 1 deletions

25
app.js
View File

@ -1,9 +1,11 @@
const express = require('express');
const express = require('express'); //TODO: make use of httpd istad of express
// A genareted db with all the pages
const siteMap = require('./siteMap');
// All compilers for all page source types
const compile = require('./compile');
const settings = require('./settings');
const db = require('./db')
db.init()
console.log("siteMap:", siteMap) //DEBUG
@ -13,6 +15,27 @@ app.set('view engine', 'ejs');
app.set('views', __dirname + '/views')
// routing
app.get('/db/:collection/:file', function(req, res, next){
db.get(req.params.collecion, req.params.file, function(err, data){
if(err){
res.status(404)
res.send('FAIL')
return
}
res.type('json')
res.send(data)
})
})
app.post('/db/:collection/:file', function(req, res, next){
db.write(req.params.collecion, req.params.file, req.body, function(err){
if(err){
res.status(500)
res.send('FAIL')
return
}
res.send('OK')
})
})
app.use(renderPage)
app.use(render404)

75
db.js Normal file
View File

@ -0,0 +1,75 @@
const fs = require('fs').promises
const settings = require('./settings')
//TODO: use a propper file type and search method
//TODO: allow encryption
const Path = __dirname + settings.dbDir + '/'
module.exports = {}
function checkCollection(path, callback, args){
const files = fs.readdir(path)
function fn(files){
callback(files, args)
}
files.catch(function(err){
console.log('catch')
if(err.toString().substr(0, notFount.length) == notFount){
p = fs.mkdir(path)
p.catch((err) => { throw err })
p.then(() => { checkCollection(path, callback, args) })
}else{
throw err
}
})
files.then(fn)
}
module.exports.get = function(coll, file, fn){
const path = Path + '/' + coll
checkCollection(path, get, [path, file, fn])
}
function get(files, args){
const path = args[0], file = args[1], fn = args[2]
delete args
if(files.indexOf(file) == -1){
return fn('file not found', null)
}
data = fs.readFile(path + '/' + file)
data.catch((err) => {
fn('error reading file', null)
})
data.then((content) => {
fn(false, content)
})
}
module.exports.write = function(coll, file, data, fn){
const path = Path + '/' + coll
checkCollection(path, write, [path, file, data, fn])
}
function write(files, args){
const path = args[0], file = args[1], data = args[2], fn = args[3]
delete args
data = fs.writeFile(path + '/' + file, data)
data.catch((err) => {
fn('error write file')
})
data.then(() => {
fn(false)
})
}