我最近学习了一点 ES6,并使用在 io.js 上运行的 koa.js 开始了我的新项目。
在下面的代码中,我试图检查是否已经有另一个具有相同url slug
.
但是 的值counter.next().value
总是返回一个函数,因此函数_slugExists
总是返回true
'use strict';
let _ = require('lodash');
let config = require('../../config');
let monk = require('monk');
let wrap = require('co-monk');
let db = monk(config.db);
let _apps = wrap(db.get('apps'));
function _validateApp(app) {
let slug = app.slug.trim();
if (!app.name.trim()) {
throw new Error('App name was not specified.');
}
if (!slug) {
throw new Error('App URL was not specified.');
}
if (_slugExists(slug)) {
throw new Error('Another app with the same URL already exists.');
}
}
function* _count(filter) {
yield _apps.count(filter);
}
function _slugExists(slug) {
let counter = _count({
slug: slug
});
return counter.next().value !== 0;
}
module.exports = {
list: function*(next) {
this.status = 200;
this.body = yield _apps.find({});
},
create: function*(next) {
try {
let app = this.request.body;
_validateApp(app);
this.status = 201;
this.body = {
id: yield _apps.insert({
name: app.name.trim(),
slug: app.slug.trim(),
created_at: new Date()
})
};
} catch (error) {
console.log(`[ERROR] ${error.message}`);
this.status = 500;
this.body = {
error: error.message
};
}
}
}