updated schedule api; updated index routing; + routing based on Accept header;

This commit is contained in:
tmshv committed 2015-03-01 01:59:00 +03:00
1 parent 6af90258c9
commit a694abb3e5
6 files changed
+148 -29

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
/**
* Created by tmshv on 01/03/15.
*/
var path = require("path");
var fs = require("mz/fs");
function accepts(routes, def) {
return function *() {
var req = this.request;
var types = Object.keys(routes)
.filter(function (type) {
return req.accepts(type);
});
if (types.length) {
var type = types[0];
yield routes[type].apply(this, arguments);
} else if(def){
yield def;
}else{
this.status = 406;
return;
}
};
}
function index(filename) {
if (!filename){
filename = path.join(__dirname, "../templates/index.html");
}
return function *() {
this.type = "text/html";
this.body = fs.createReadStream(filename);
}
}
module.exports = {
index: index,
accepts: accepts
};
+47
View File
@@ -0,0 +1,47 @@
/**
* Created by tmshv on 22/11/14.
*/
var route = require("koa-route");
var router = require("./");
var db = require("../core/db");
var schedule = require("../models/schedule");
var populate = require("../utils/populate").populate;
const course = require("../models/course");
const team = require("../models/team");
module.exports = function (app) {
app.use(
route.get("/schedule/:period?/:semester?", router.accepts(
{
"text/html": router.index(),
"text/plain": router.index(),
"application/json": function *(period, semester) {
this.type = "application/json";
var doPopulate = this.query.populate || false;
var data = yield db.c("schedules").findOne({
period: period,
semester: semester
});
if(!data) {
this.status = 404;
return;
}
if(doPopulate) {
data.schedule = schedule.populate(data.schedule, [
populate(team.short, "teacher"),
populate(course.name, "lesson")
]);
}
this.body = data;
}
}
))
);
};