-
Notifications
You must be signed in to change notification settings - Fork 0
/
action.js
80 lines (70 loc) · 2.13 KB
/
action.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var mu = require('mu2');
var util = require('util');
var pathHelper = require('path');
var BaseAction = function (req, rep, root, path, context) {
this._req = req;
this._rep = rep;
this._path = path;
this._root = root;
this._context = context;
};
BaseAction.prototype.render = function (template, options) {
var path;
if (template.charAt(0) == '/') {
path = pathHelper.normalize(this._root + template);
}
else {
path = pathHelper.normalize(pathHelper.dirname(this._path) + '/' + template);
}
return mu.compileAndRender(path, options);
}
BaseAction.prototype.renderText = function (template, options) {
var path;
if (template.charAt(0) == '/') {
path = pathHelper.normalize(this._root + template);
}
else {
path = pathHelper.normalize(pathHelper.dirname(this._path) + '/' + template);
}
return mu.renderText(path, options);
}
BaseAction.prototype.renderJSON = function (options, replacer) {
return JSON.stringify(options, replacer);
}
BaseAction.prototype.__do__ = function (method, queryString) {
var rep = this._rep,
html = this[method](queryString, this._context);
if (typeof html == 'string') {
rep.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': html.length
});
rep.end(html);
}
else {
util.pump(html, rep);
}
}
function extend(source, target) {
for (key in target) {
source[key] = target[key];
}
}
exports.create = function (url, methods, modules) {
var Action = function (req, rep, path, context) {
this.super.constructor.call(this, req, rep, path, context);
};
Action.prototype = new BaseAction();
methods = methods || {};
methods.super = Action.prototype;
extend(Action.prototype, methods);
modules = modules || {};
modules.url = url;
modules.create = function (req, rep, root, path, context) {
return new Action(req, rep, root, path, context);
}
modules.hasMethod = function (method) {
return !!methods[method];
}
return modules;
}