forked from geddy/geddy
/
controller.js
365 lines (326 loc) · 10.3 KB
/
controller.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
* Geddy JavaScript Web development framework
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var sys = require('sys');
var fs = require('fs');
var errors = require('geddy-core/lib/errors');
var response = require('geddy-core/lib/response');
var Templater = require('geddy-template/lib/adapters/ejs').Templater
var Controller = function (obj) {
var undefined; // Local copy of undefined value
// The http.ServerRequest passed to the 'request' event
// callback function
this.request = null;
// The http.ServerResponse passed to the 'request' event
// callback function
this.response = null;
// The action gets passed these as an argument, but we keep
// them here too to have access to the format for
// content-negotiation
this.params = null;
// Cookies collection, written out in the finish and redirect methods
this.cookies = null;
// The name of the controller constructor function,
// in CamelCase with uppercase initial letter -- use geddy.inflections
// to get the other casing versions
this.name = null;
// Content-type the controller can respond with -- assume
// minimum of plaintext
this.respondsWith = ['txt'];
// Content to respond with -- can be an Object or String
this.content = '';
// High-level set of options which can represent multiple
// content-types
// 'txt', 'json', 'xml', 'html'
this.format = '';
// Content-type of the response -- driven by the format, and
// by what content-types the client accepts
this.contentType = '';
// The template root to look in for partials when rendering templates
// Gets created programmatically based on controller name -- see renderTemplate
this.templateRoot = undefined;
// This will be used for 'before' actions for plugins
this.beforeFilters = [];
// This will be used for 'after' actions for plugins
this.afterFilters = [];
// Override defaults with passed-in options
geddy.util.meta.mixin(this, obj);
};
Controller.prototype = new function () {
this.before = function (filter, o) {
this.addFilter('before', filter, o || {});
};
this.after = function (filter, o) {
this.addFilter('after', filter, o || {});
};
this.addFilter = function (phase, filter, opts) {
var obj = {name: filter};
obj.except = opts.except;
obj.only = opts.only;
this[phase + 'Filters'].push(obj);
}
/**
* Primary entry point for calling the action on a controller
*/
this.handleAction = function (action, params) {
var _this = this;
// Wrap the actual action-handling in a callback to use as the 'last'
// method in the async chain of before-filters
var callback = function () {
_this[action].call(_this, params);
};
this.execFilters(action, 'before', callback);
};
this.execFilters = function (action, phase, callback) {
var _this = this;
var filters = this[phase + 'Filters'];
var filter;
var name;
var hook;
var list = [];
var applyFilter;
for (var i = 0; i < filters.length; i++) {
filter = filters[i];
applyFilter = true;
if (filter.only && filter.only != action) {
applyFilter = false;
}
if (filter.except && filter.except == action) {
applyFilter = false;
}
if (applyFilter) {
name = filter.name;
hook = geddy.hooks.collection[name];
hook.args = [_this];
list.push(hook);
}
}
var chain = new geddy.util.async.AsyncChain(list);
chain.last = callback;
chain.run();
};
this.formatters = {
// Right now all we have is JSON and plaintext
// Fuck XML until somebody enterprisey wants it
json: function (content) {
var toJson = content.toJson || content.toJSON;
if (typeof toJson == 'function') {
return toJson.call(content);
}
return JSON.stringify(content);
}
, js: function (content, controller) {
var params = controller.params;
if (!params.callback) {
err = new errors.InternalServerError('JSONP callback not defined.');
controller.error(err);
}
return params.callback + '(' + JSON.stringify(content) + ');';
}
, txt: function (content) {
if (typeof content.toString == 'function') {
return content.toString();
}
return JSON.stringify(content);
}
};
this.redirect = function (redir) {
var url;
if (typeof redir == 'string') {
url = redir;
}
else {
var contr = redir.controller || this.name;
var act = redir.action;
var ext = redir.format || this.params.format;
var id = redir.id;
contr = geddy.util.string.decamelize(contr);
url = '/' + contr;
url += act ? '/' + act : '';
url += id ? '/' + id : '';
if (ext) {
url += '.' + ext;
}
}
var r = new response.Response(this.response);
var headers = {'Location': url};
headers['Set-Cookie'] = this.cookies.serialize();
this.session.close(function () {
r.send('', 302, headers);
});
};
this.error = function (err) {
errors.respond(this.response, err);
};
this.transfer = function (act) {
this.params.action = act;
this[act](this.params);
};
this.respond = function (content, format) {
// format and contentType are set at the same time
var negotiated = this.negotiateContent(format);
this.format = negotiated.format;
this.contentType = negotiated.contentType;
if (!this.contentType) {
var err = new errors.NotAcceptableError('Not an acceptable media type.');
this.error(err);
}
this.formatContentAndFinish(content);
};
this.finish = function () {
var r = new response.Response(this.response);
var headers = {'Content-Type': this.contentType};
headers['Set-Cookie'] = this.cookies.serialize();
var content = this.content;
if (this.session) {
this.session.close(function () {
r.send(content, 200, headers);
});
}
else {
r.send(content, 200, headers);
}
};
this.negotiateContent = function (frmt) {
var format
, contentType
, types = []
, match
, params = this.params
, err
, accepts = this.request.headers.accept
, pat
, wildcard = false;
// If the client doesn't provide an Accept header, assume
// it's happy with anything
if (accepts) {
accepts = accepts.split(',');
}
else {
accepts = ['*/*'];
}
if (frmt) {
types = [frmt];
}
else if (params.format) {
var f = params.format;
// See if we can actually respond with this format,
// i.e., that this one is in the list
if (f && ('|' + this.respondsWith.join('|') + '|').indexOf(
'|' + f + '|') > -1) {
types = [f];
}
}
else {
types = this.respondsWith;
}
// Okay, we have some format-types.
if (types.length) {
// Ignore quality factors for now
for (var i = 0, ii = accepts.length; i < ii; i++) {
accepts[i] = accepts[i].split(';')[0];
// We need a string operation here, due to different charset encodings of browser headers
if (accepts[i].indexOf('*/*') < 0) {
continue;
}
wildcard = true;
break;
}
// If agent accepts anything, respond with the controller's first choice
if (wildcard) {
var t = types[0];
format = t;
contentType = response.formatsPreferred[t];
if (!contentType) {
this.throwUndefinedFormatError();
}
}
// Otherwise look through the acceptable formats and see if
// Geddy knows about any of them.
else {
for (var i = 0, ii = types.length; i < ii; i++) {
pat = response.formatPatterns[types[i]];
if (pat) {
for (var j = 0, jj = accepts.length; j < jj; j++) {
match = accepts[j].match(pat);
if (match) {
format = types[i];
contentType = match;
break;
}
}
}
// If respondsWith contains some random format that Geddy doesn't know
// TODO Make it easy for devs to add new formats
else {
this.throwUndefinedFormatError();
}
// Don't look at any more formats if there's a match
if (match) {
break;
}
}
}
}
return {format: format, contentType: contentType};
};
this.throwUndefinedFormatError = function () {
err = new errors.InternalServerError('Format not defined in response.formats.');
this.error(err);
};
this.formatContentAndFinish = function (content) {
if (typeof content == 'string') {
this.content = content;
this.finish();
}
else {
if (this.format) {
this.formatContent(this.format, content);
}
else {
err = new errors.InternalServerError('Unknown format');
this.error(err);
}
}
};
this.formatContent = function (format, data) {
if (format == 'html') {
this.renderTemplate(data);
}
else {
var c = this.formatters[format](data, this);
this.formatContentAndFinish(c);
}
};
this.renderTemplate = function (data) {
var _this = this;
// Calculate the templateRoot if not set
this.templateRoot = this.templateRoot ||
'app/views/' + geddy.inflections[this.name].filename.plural;
var templater = new Templater();
var content = '';
templater.addListener('data', function (d) {
// Buffer for now, but could stream
content += d;
});
templater.addListener('end', function () {
_this.formatContentAndFinish(content);
});
templater.render(data, [this.templateRoot], this.params.action);
};
}();
exports.Controller = Controller;