Поясните за преимущества коа перед эксперссом?
В экспрессе нельзя сделать конвейерную обработку запросов потому что express отбрасывает значения middleware-функции и вот такое без патча экспресса сделать не получится
//log requests
middlewares.push(async(next, req, res) => {
console.log('request start:', req.method, req.url);
var response = await next();
console.log('request send:', response);
res.end(JSON.stringify(response));
console.log('request end:', req.method, req.url);
});
//catch errors
middlewares.push(async(req, res, next) => {
try {
return await next();
} catch (e) {
console.log('error:', e);
res.status(400);
return {error: e.message};
}
});
middlerawe.push(staticServer)
//connect to database
middlewares.push(async(next, req, res) => {
req.db = await new DB(schema);
req.data = {};
try {
return await next();
} catch (err) {
await req.db.disconnect();
throw err;
}
});
middlerawe.push(cookieParser)
middlewares.push(getCurrentUserOrCreateGuest)
middlerawe.push(bodyParser)
//map request info to crud operation
middlewares.push(async(next, req, res) => {
var [table, id] = req.url.split('/').slice(1);
var dbActions = {
"GET": 'get',
"POST": 'add',
"PUT": 'update',
"DELETE": 'delete'
};
req.data.action = dbActions[req.method];
req.data.table = table;
req.data.id = id;
return await next();
});
//process request in database
middlewares.push(async(next, req, res) => {
var {table, id, action} = req.data;
if(!table) throw new Error('no table');
var index = req.query.index;
var body = req.body;
if (action == 'get') {
return await req.db.get(table, id, {index})
}
if (action == 'add') {
return await req.db.add(table, body)
}
if (action == 'update') {
return await req.db.update(table, id, body)
}
if (action == 'delete') {
return await req.db.delete(table, id)
}
});