wiki_thsf_2015/db.js

84 lines
2.0 KiB
JavaScript
Raw Normal View History

2012-01-19 03:01:17 +11:00
var FS = require('fs');
var Path = require('path');
var Markdown = require('markdown').markdown;
2015-03-31 08:04:08 +11:00
var knex = require("knex");
var Bookshelf = require('bookshelf');
2012-01-19 03:01:17 +11:00
// This function is used to map wiki page names to files
// on the real filesystem.
function pathFromName(name) {
return Path.join(__dirname, "pages", name + ".markdown");
}
2012-01-19 04:42:29 +11:00
// Load a file, parse the title and generate the HTML
2012-01-19 03:01:17 +11:00
exports.loadPage = function (name, callback) {
var path = pathFromName(name);
2012-01-19 04:42:29 +11:00
2012-01-19 03:01:17 +11:00
FS.readFile(path, 'utf8', function (err, markdown) {
2012-01-19 04:42:29 +11:00
2012-01-19 03:01:17 +11:00
var exists = true;
if (err) {
if (err.code === "ENOENT") {
2012-01-19 04:42:29 +11:00
// Generate a placeholder body.
markdown = "# " + name.replace(/_/g, " ") +
"\n\n" + "This page does not exist yet.";
2012-01-19 03:01:17 +11:00
exists = false;
} else {
2012-01-19 04:42:29 +11:00
// Forward on all other errors.
2012-01-19 03:01:17 +11:00
return callback(err);
}
}
2012-01-19 04:42:29 +11:00
// Parse and render the markdown.
2012-01-19 03:01:17 +11:00
var tree = Markdown.parse(markdown);
var title = name;
for (var i = 1, l = tree.length; i < l; i++) {
if (tree[i] && tree[i][0] === "header") {
title = tree[i][2];
tree.splice(i, 1);
break;
}
}
var html = Markdown.toHTML(tree);
callback(null, {
name: name,
title: title,
exists: exists,
markdown: markdown,
html: html,
});
2012-01-19 04:42:29 +11:00
2012-01-19 03:01:17 +11:00
});
};
// Saving is simple. Just put the markdown in the file
exports.savePage = function (name, value, callback) {
var path = pathFromName(name);
FS.writeFile(path, value, callback);
};
2015-03-31 08:04:08 +11:00
var dbFile = Path.join(__dirname, 'app.db');
var DB = Bookshelf(knex({
client: 'sqlite3',
connection: { filename: dbFile }
}));
FS.exists(dbFile, function(exists) {
if (!exists) {
console.log("create a new DB")
DB.knex.schema.createTable('Users', function(table) {
table.increments("id")
table.string('username')
table.string('password')
}).then( function(){ console.log("DB created") })
}
})
exports.DB = DB;