moving to koa 2.0; + api

This commit is contained in:
tmshv committed 2016-03-23 14:56:59 +03:00
1 parent 44724132c0
commit 0ffa403b60
17 files changed
+398 -339

No files matched your search

+48 -34
View File
@@ -1,4 +1,5 @@
import co from 'co';
import compose from 'koa-compose';
import route from 'koa-route';
import {index, json} from './';
import {sortByPattern} from '../utils/sort';
@@ -7,42 +8,55 @@ import {c} from '../core/db';
let split = d => s => s.split(d);
let toArray = split(',');
export default function (app) {
app.use(route.get('/collective', index()));
app.use(route.get('/teacher/list', json(
function *() {
this.type = 'application/json';
let pattern = toArray(this.query.sort || '');
let data = yield c('collective').find();
if (!data) {
this.status = 404;
return;
}
let collective = yield data
.map(processProfile);
this.body = sortByPattern(collective, pattern, i => i.id);
}
)));
app.use(route.get('/teacher/:id', json(
function *(id) {
this.type = 'application/json';
let data = yield c('collective').findOne({id: id});
if (!data) {
this.status = 404;
return;
}
this.body = yield processProfile(data);
}
)))
export default function () {
return compose([
collective(),
list(),
teacher()
]);
};
function collective() {
return route.get('/collective', index());
}
function list() {
return route.get('/teacher/list', json(
async(ctx) => {
ctx.type = 'application/json';
let pattern = toArray(ctx.query.sort || '');
let data = await c('collective').find();
if (!data) {
ctx.status = 404;
return;
}
let collective = await Promise.all(
data.map(processProfile)
);
ctx.body = sortByPattern(collective, pattern, i => i.id);
}
));
}
function teacher() {
return route.get('/teacher/:id', json(
async (ctx, id) => {
ctx.type = 'application/json';
let data = await c('collective').findOne({id: id});
if (!data) {
ctx.status = 404;
return;
}
ctx.body = await processProfile(data);
}
))
}
let processProfile = profile => co(function *() {
let imageId = profile.picture;
profile.picture = yield c('images').findOne({_id: imageId});