Skip to content
This repository has been archived by the owner on Jul 15, 2018. It is now read-only.

Commit

Permalink
refactoring, added 404 support
Browse files Browse the repository at this point in the history
  • Loading branch information
olegp committed Oct 20, 2011
1 parent b23ea60 commit 9c2fe3a
Showing 1 changed file with 45 additions and 33 deletions.
78 changes: 45 additions & 33 deletions lib/mcms.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')]
};
};

Expand Down

0 comments on commit 9c2fe3a

Please sign in to comment.