Skip to content

Instantly share code, notes, and snippets.

@jayfresh
Last active June 19, 2019 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jayfresh/07edb4b270ee50d84e6b to your computer and use it in GitHub Desktop.
Save jayfresh/07edb4b270ee50d84e6b to your computer and use it in GitHub Desktop.
/*\
title: $:/plugins/jayfresh/tiddler-server/tiddler-server.js
type: application/javascript
module-type: command
A server command to serve tiddlers as HTML as well as the main server API
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// declare a new command
exports.info = {
name: "tiddler-server",
synchronous: true
};
var Command = function(params,commander,callback) {
// inherit from the tw5 server command
var ServerCommand = require('$:/core/modules/commands/server.js').Command;
this.prototype = new ServerCommand(params,commander);
// add the route to server tiddlers as HTML
// mainly copied from the tw5 server command's GET /recipes/default/tiddlers/* route
this.prototype.server.addRoute({
method: "GET",
path: /^\/(.+)$/,
handler: function(request,response,state) {
var title = decodeURIComponent(state.params[0]),
tiddler = state.wiki.getTiddler(title),
tiddlerFields = {},
knownFields = [
"bag", "created", "creator", "modified", "modifier", "permissions", "recipe", "revision", "tags", "text", "title", "type", "uri"
],
html = "<html><head></head><body><h1>"+title+"</h1><p>";
if(tiddler) {
$tw.utils.each(tiddler.fields,function(field,name) {
var value = tiddler.getFieldString(name);
if(knownFields.indexOf(name) !== -1) {
tiddlerFields[name] = value;
} else {
tiddlerFields.fields = tiddlerFields.fields || {};
tiddlerFields.fields[name] = value;
}
});
tiddlerFields.revision = state.wiki.getChangeCount(title);
tiddlerFields.type = tiddlerFields.type || "text/vnd.tiddlywiki";
response.writeHead(200, {"Content-Type": "text/html"});
html += tiddlerFields.text+"</p></body></html>";
response.end(html,"utf8");
} else {
response.writeHead(404);
response.end();
}
}
});
};
Command.prototype.execute = function() {
// call the execute method of the tw5 server command
this.prototype.execute.apply(this.prototype,arguments);
};
exports.Command = Command;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment