Permalink
Browse files

refactoring, added 404 support

  • Loading branch information...
1 parent b23ea60 commit 9c2fe3a31c27001ae31b292c9771d7dcb1042f9b @olegp committed Oct 20, 2011
Showing with 45 additions and 33 deletions.
  1. +45 −33 lib/mcms.js
View
@@ -84,49 +84,61 @@ fs.exists(INCLUDES) && fs.list(INCLUDES).forEach(function(file) {
includes[file.substr(0, file.lastIndexOf(ext))] = contents;
});
+// serve a static file
+function serve(uri) {
+ var file = fs.absolute(fs.join(ABSOLUTE_STATIC, uri
+ .substr('static'.length + 1)));
+ if(!file.indexOf(ABSOLUTE_STATIC) && fs.exists(file)) {
+ return {
+ status: 200,
+ 'Content-Type': MIME_TYPES[fs.extension(file)],
+ // TODO add etag or last-modified header
+ // TODO add support for caching
+ body: fs.openRaw(file)
+ };
+ } else {
+ return {
+ status: 404,
+ headers: {},
+ body: []
+ };
+ }
+}
+
+// load a dynamically generated page
+function load(name) {
+ var page = pages[name];
+ if(page) {
+ if(!page.body) {
+ var md = read(page.file);
+ var template = templates[page.link]
+ || templates[fs.join(fs.directory(page.link), 'index')]
+ || templates['index'];
+ page.body = mustache(template, merge({
+ title: page.title == 'index' ? '' : page.title,
+ body: markdown(md),
+ ascending: ascending,
+ descending: descending
+ }, includes));
+ }
+ return page.body;
+ }
+ return '';
+}
+
exports.app = function(request) {
var uri = request.pathInfo.substr(1);
if(!uri.indexOf('static')) {
- var file = fs.absolute(fs.join(ABSOLUTE_STATIC, uri
- .substr('static'.length + 1)));
- if(!file.indexOf(ABSOLUTE_STATIC) && fs.exists(file)) {
- return {
- status: 200,
- 'Content-Type': MIME_TYPES[fs.extension(file)],
- body: fs.openRaw(file)
- };
- } else {
- return {
- status: 404,
- headers: {},
- body: []
- };
- }
+ return serve(uri);
}
-
var name = friendly(uri) || 'index';
- var page = pages[name];
- if(page && !page.body) {
- var md = read(page.file);
- var template = templates[name]
- || templates[fs.join(fs.directory(name), 'index')]
- || templates['index'];
- // TODO inject templates as well -- or separate them out into "partials"?
- page.body = mustache(template, merge({
- // TODO deal with case when title == 'index'
- title: page.title,
- body: markdown(md),
- ascending: ascending,
- descending: descending
- }, includes));
- }
+ var page = load(name);
return {
status: page ? 200 : 404,
headers: {
'Content-Type': 'text/html'
},
- // TODO custom 404 pages
- body: [page ? page.body : 'Not found']
+ body: [page || load('404')]
};
};

0 comments on commit 9c2fe3a

Please sign in to comment.