From b12b0097e1dc72eb4b97c776a05d9fe1d76b6ff7 Mon Sep 17 00:00:00 2001 From: Jack Hu Date: Sun, 10 Apr 2016 20:36:56 +0800 Subject: [PATCH] update to v1.3.0 --- .travis.yml | 1 + History.md | 9 + LICENSE | 3 +- README.md | 33 +- gulp/config.js | 1 - gulp/server.js | 52 +- gulp/test.js | 82 +-- gulpfile.js | 6 +- package.json | 63 ++- process.json | 32 +- server/api/article/article.controller.js | 44 +- server/api/user/user.controller.js | 9 +- server/config/env/development.js | 5 + server/config/env/index.js | 11 + server/config/env/production.js | 6 + server/config/env/test.js | 3 + server/config/express.js | 10 +- server/config/seed.js | 12 +- server/util/qiniu/index.js | 16 +- server/util/redis/index.js | 14 + server/util/tools/index.js | 2 + test/api/article.test.js | 65 +-- test/api/comment.test.js | 44 +- test/api/logs.test.js | 25 +- test/api/tags.test.js | 26 +- test/api/user.test.js | 621 +++++++++++------------ test/middlewares/authHelper.js | 33 ++ test/util/qiniu.test.js | 27 +- 28 files changed, 651 insertions(+), 604 deletions(-) create mode 100644 server/util/redis/index.js create mode 100644 test/middlewares/authHelper.js diff --git a/.travis.yml b/.travis.yml index 29d4eb5..f852181 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,6 +18,7 @@ addons: services: - mongodb + - redis-server before_install: - $CXX --version diff --git a/History.md b/History.md index 366dfc5..605fe19 100644 --- a/History.md +++ b/History.md @@ -1,3 +1,12 @@ +1.3.0 / 2016-04-10 +================== + +* 更新依赖包到最新 +* 增加redis支持 +* 使用connect-redis 替换 connect-mongo +* 使用redis 缓存首页图片列表. + + 1.2.1 / 2016-01-28 ================== diff --git a/LICENSE b/LICENSE index fa1571d..91f1f81 100644 --- a/LICENSE +++ b/LICENSE @@ -18,5 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 38b6e60..3f03842 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ [![build status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] +[![Dependency Status](https://david-dm.org/jackhutu/jackblog-api-express.svg)](https://david-dm.org/jackhutu/jackblog-api-express) +[![devDependency Status](https://david-dm.org/jackhutu/jackblog-api-express/dev-status.svg)](https://david-dm.org/jackhutu/jackblog-api-express#info=devDependencies) [travis-image]: https://travis-ci.org/jackhutu/jackblog-api-express.svg?branch=master [travis-url]: https://travis-ci.org/jackhutu/jackblog-api-express @@ -10,21 +12,17 @@ [coveralls-url]: https://coveralls.io/github/jackhutu/jackblog-api-express?branch=master ## 简介 -Jackblog 是使用 Node.js + MongoDB + 其它客户端框架, 开发的个人博客系统,前后端分离,仿简书模板.此为服务端express版. -服务端有: -[express版](https://github.com/jackhutu/jackblog-api-express) -[koa版](https://github.com/jackhutu/jackblog-api-koa) -客户端有: -[angular1.x版](https://github.com/jackhutu/jackblog-angular1) -[react redux 版](https://github.com/jackhutu/jackblog-react-redux) -[vue 版](https://github.com/jackhutu/jackblog-vue) -移动端有: -[react native 版](https://github.com/jackhutu/jackblog-react-native-redux) +Jackblog 是使用 Node.js + MongoDB + Redis + 其它客户端框架开发的个人博客系统,前后端分离,仿简书模板. +服务端有: [express 版](https://github.com/jackhutu/jackblog-api-express) , [koa 版](https://github.com/jackhutu/jackblog-api-koa) +客户端有: [angular1.x 版](https://github.com/jackhutu/jackblog-angular1) , [angular2.x 版](https://github.com/jackhutu/jackblog-angular2) , [react redux 版](https://github.com/jackhutu/jackblog-react-redux) , [vue 版](https://github.com/jackhutu/jackblog-vue) +移动端有: [react native 版](https://github.com/jackhutu/jackblog-react-native-redux), [ionic2.0 版](https://github.com/jackhutu/jackblog-ionic2) +##### 此为服务端Express版, 为客户端提供api. ## 环境准备 ``` node.js 4.0+ mognodb 3.0+ +redis 2.8+ ``` ## 配置 @@ -40,27 +38,30 @@ mognodb 3.0+ }, ``` + ## 开发 ``` +$ git clone git@github.com:jackhutu/jackblog-api-express.git +$ cd jackblog-api-express $ npm install $ gulp serve ``` -配合客户端测试的测试模式 - -``` -$ gulp serve:test -``` ## 线上布署 ``` $ pm2 start process.json ``` -可参考[利用git和pm2一键布署项目到vps](http://angular1.jackhu.top/article/55cd8e00c6e998b817a930c7) +可参考[利用git和pm2一键布署项目到vps](http://jackhu.top/article/55cd8e00c6e998b817a930c7) ## 测试 ``` $ gulp test ``` +配合客户端测试的测试模式 + +``` +$ gulp serve:test +``` ## License MIT \ No newline at end of file diff --git a/gulp/config.js b/gulp/config.js index 05ec964..d7dd947 100644 --- a/gulp/config.js +++ b/gulp/config.js @@ -7,7 +7,6 @@ exports.paths = { istanbul: 'test_coverage', server:'server' }; - /** * 错误处理 */ diff --git a/gulp/server.js b/gulp/server.js index 562dab3..84630ca 100644 --- a/gulp/server.js +++ b/gulp/server.js @@ -8,40 +8,38 @@ var nodemon = require('gulp-nodemon'); //默认development模式 gulp.task('nodemon',function () { - nodemon({ - script: path.join(config.paths.server,'/app.js'), - ext: 'js', - watch: [ - path.join(config.paths.server,'/') - ] - }) + nodemon({ + script: path.join(config.paths.server,'/app.js'), + ext: 'js', + watch: [ + path.join(config.paths.server,'/') + ] + }) }); //test模式 gulp.task('nodemon:test',function () { - //http://localhost:8080 test mode - nodemon({ - script: path.join(config.paths.server,'/app.js'), - ext: 'js json', - watch: [ - path.join(config.paths.server,'/') - ], - env: { 'NODE_ENV': 'test' } - }) + //http://localhost:8080 test mode + nodemon({ + script: path.join(config.paths.server,'/app.js'), + ext: 'js json', + watch: [ + path.join(config.paths.server,'/') + ], + env: { 'NODE_ENV': 'test' } + }) }); //production模式 gulp.task('nodemon:production',function () { - nodemon({ - script: path.join(config.paths.server,'/app.js'), - ext: 'js json', - watch: [ - path.join(config.paths.server,'/') - ], - env: { 'NODE_ENV': 'production' } - }) + nodemon({ + script: path.join(config.paths.server,'/app.js'), + ext: 'js json', + watch: [ + path.join(config.paths.server,'/') + ], + env: { 'NODE_ENV': 'production' } + }) }); - gulp.task('serve',['nodemon']); gulp.task('serve:test',['nodemon:test']); -gulp.task('serve:production',['nodemon:production']); - +gulp.task('serve:production',['nodemon:production']); \ No newline at end of file diff --git a/gulp/test.js b/gulp/test.js index 587fb2f..8c078c9 100644 --- a/gulp/test.js +++ b/gulp/test.js @@ -11,62 +11,62 @@ var coveralls = require('gulp-coveralls'); //设置环境变量,mocha,istanbul测试必须在test mode gulp.task('set-env', function () { - env({ - vars: { - 'NODE_ENV':'test' - } - }); + env({ + vars: { + 'NODE_ENV':'test' + } + }); }); //istanbul gulp.task('pre-test', function () { return gulp.src([ - path.join(config.paths.server,'/**/*.js'), - path.join('!' + config.paths.server,'/config/**/*.js'), - path.join('!' + config.paths.server,'/auth/**/*.js'), - path.join('!' + config.paths.server,'/{app,routes}.js'), - path.join('!' + config.paths.server,'/model/**/*.js') - ]) - .pipe(istanbul()) // Covering files - .pipe(istanbul.hookRequire()) + path.join(config.paths.server,'/**/*.js'), + path.join('!' + config.paths.server,'/config/**/*.js'), + path.join('!' + config.paths.server,'/auth/**/*.js'), + path.join('!' + config.paths.server,'/{app,routes}.js'), + path.join('!' + config.paths.server,'/model/**/*.js') + ]) + .pipe(istanbul()) // Covering files + .pipe(istanbul.hookRequire()) }); gulp.task('test:istanbul',['set-env','pre-test'],function () { - gulp.src(path.join(config.paths.mocha,'/**/*.test.js'),{read: false}) - .pipe(mocha({ - require: ['should'], - timeout: 5000 - })) - .pipe(istanbul.writeReports({ - dir: path.join(config.paths.istanbul,'/') - })) - .once('error', function () { - process.exit(1); - }) - .once('end', function () { - process.exit(); - }); + gulp.src(path.join(config.paths.mocha,'/**/*.test.js'),{read: false}) + .pipe(mocha({ + require: ['should'], + timeout: 5000 + })) + .pipe(istanbul.writeReports({ + dir: path.join(config.paths.istanbul,'/') + })) + .once('error', function () { + process.exit(1); + }) + .once('end', function () { + process.exit(); + }); }); //mocha test gulp.task('test:mocha',['set-env'],function () { - gulp.src(path.join(config.paths.mocha,'/**/*.test.js'),{read: false}) - .pipe(mocha({ - reporter: 'list', //list,nyan,spec(default),progress - require: ['should'], - timeout: 5000 - })) - .once('error', function () { - process.exit(1); - }) - .once('end', function () { - process.exit(); - }); + gulp.src(path.join(config.paths.mocha,'/**/*.test.js'),{read: false}) + .pipe(mocha({ + reporter: 'list', //list,nyan,spec(default),progress + require: ['should'], + timeout: 5000 + })) + .once('error', function () { + process.exit(1); + }) + .once('end', function () { + process.exit(); + }); }); //coveralls gulp.task('coveralls',function () { - gulp.src(path.join(config.paths.istanbul, '/lcov.info')) - .pipe(coveralls()); + gulp.src(path.join(config.paths.istanbul, '/lcov.info')) + .pipe(coveralls()); }); gulp.task('test',gulpSequence('test:istanbul')); diff --git a/gulpfile.js b/gulpfile.js index cd6a487..ba91c9b 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -4,9 +4,9 @@ var gulp = require('gulp'); var fs = require('fs'); fs.readdirSync('./gulp').forEach(function (file) { - if((/\.(js|coffee)$/i).test(file)){ - require('./gulp/' + file); - } + if((/\.(js|coffee)$/i).test(file)){ + require('./gulp/' + file); + } }); gulp.task('default', ['serve']); \ No newline at end of file diff --git a/package.json b/package.json index ccf9097..118fd1c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "jackblog-api-express", - "version": "1.2.1", + "version": "1.3.0", "description": "Jackblog API Express版", "main": "server/app.js", "scripts": { @@ -23,49 +23,46 @@ }, "homepage": "https://github.com/jackhutu/jackblog-api-express#readme", "dependencies": { - "bluebird": "^2.10.2", - "body-parser": "^1.14.1", - "bunyan": "^1.5.1", + "bluebird": "^3.3.4", + "body-parser": "^1.15.0", + "bunyan": "^1.8.0", "ccap": "^0.6.4", "composable-middleware": "^0.3.0", - "compression": "^1.6.0", - "connect-mongo": "^0.8.2", - "cookie-parser": "^1.4.0", + "compression": "^1.6.1", + "connect-redis": "^3.0.2", + "cookie-parser": "^1.4.1", "cors": "^2.7.1", - "errorhandler": "^1.4.2", - "express": "^4.13.3", - "express-jwt": "^3.1.0", - "express-session": "^1.12.0", - "jsonwebtoken": "^5.4.0", - "lodash": "^3.10.1", - "markdown-it": "^5.0.0", + "errorhandler": "^1.4.3", + "express": "^4.13.4", + "express-jwt": "^3.3.0", + "express-session": "^1.13.0", + "ioredis": "^1.15.1", + "jsonwebtoken": "^5.7.0", + "lodash": "^4.9.0", + "markdown-it": "^6.0.1", "method-override": "^2.3.5", - "moment": "^2.10.6", - "mongoose": "^4.2.2", + "moment": "^2.12.0", + "mongoose": "^4.4.12", "multer": "^1.1.0", - "passport": "^0.3.0", - "passport-github": "^1.0.0", + "passport": "^0.3.2", + "passport-github": "^1.1.0", "passport-local": "^1.0.0", "passport-qq": "0.0.3", "passport-weibo": "^0.1.2", - "pm2": "^0.15.7", - "qiniu": "^6.1.8" + "pm2": "^1.1.1", + "qiniu": "^6.1.9" }, "devDependencies": { - "del": "^2.0.2", - "gulp": "^3.9.0", + "gulp": "^3.9.1", "gulp-coveralls": "^0.1.4", - "gulp-env": "^0.2.0", - "gulp-istanbul": "^0.10.2", - "gulp-mocha": "^2.1.3", - "gulp-nodemon": "^2.0.4", - "gulp-sequence": "^0.4.1", + "gulp-env": "^0.4.0", + "gulp-istanbul": "^0.10.4", + "gulp-mocha": "^2.2.0", + "gulp-nodemon": "^2.0.6", + "gulp-sequence": "^0.4.5", "gulp-util": "^3.0.7", - "mocha": "^2.3.3", - "nock": "^2.15.0", - "should": "^7.1.1", - "should-promised": "^0.3.1", - "sinon": "^1.17.2", - "supertest": "^1.1.0" + "should": "^8.3.0", + "sinon": "^1.17.3", + "supertest": "^1.2.0" } } diff --git a/process.json b/process.json index fdb03a7..7b5ac94 100644 --- a/process.json +++ b/process.json @@ -1,18 +1,18 @@ { - "apps" : [ - { - "name" : "jackblog-api", - "script" : "./server/app.js", - "log_date_format" : "YYYY-MM-DD HH:mm Z", - "out_file" : "./logs/pm2-out.log", - "error_file" : "./logs/pm2-err.log", - "pid_file" : "./logs/jackblog-api.pid", - "ignoreWatch" : ["[\\/\\\\]\\./", "node_modules"], - "watch" : "false", - "exec_mode" : "fork_mode", //cluster_mode - "env": { - "NODE_ENV": "production" - } - } - ] + "apps": [ + { + "name" : "jackblog-api", + "script" : "./server/app.js", + "log_date_format" : "YYYY-MM-DD HH:mm Z", + "out_file" : "./logs/pm2-out.log", + "error_file" : "./logs/pm2-err.log", + "pid_file" : "./logs/jackblog-api.pid", + "ignoreWatch" : ["[\\/\\\\]\\./", "node_modules"], + "watch" : "false", + "exec_mode" : "fork_mode", //cluster_mode + "env": { + "NODE_ENV": "production" + } + } + ] } diff --git a/server/api/article/article.controller.js b/server/api/article/article.controller.js index bebbac9..d6103bf 100644 --- a/server/api/article/article.controller.js +++ b/server/api/article/article.controller.js @@ -12,6 +12,7 @@ var MarkdownIt = require('markdown-it'); var config = require('../../config/env'); var Promise = require("bluebird"); var tools = require('../../util/tools'); +var redis = require('../../util/redis'); //添加博客 exports.addArticle = function (req,res,next) { @@ -253,30 +254,31 @@ exports.getPrenext = function (req,res,next) { }).catch(function (err) { return next(err); }) - - } + //获取首页图片 -exports.getIndexImage = function (req,res) { - //直接从七牛获取会很慢,改为从配置数组中获取. - if(!config.indexImages || config.indexImages.length < 1){ - res.status(200).json({success:true,img:config.defaultIndexImage}); - qiniuHelper.list('blog/index','',10).then(function(result){ - return Promise.map(result.items,function (item) { - return config.qiniu.domain + item.key + '-600x1500q80'; - }) - }).then(function (images) { - config.indexImages = images; - }).catch(function (err) { - config.indexImages = []; - }); - return; - }else{ - var images = config.indexImages; - var index = _.random(images.length - 1); - return res.status(200).json({success:true,img:images[index]}); - } +exports.getIndexImage = function (req,res,next) { + //使用redis缓存图片列表. + redis.llen('indexImages').then(function (imagesCount) { + if(imagesCount < 1){ + res.status(200).json({success:true,img:config.defaultIndexImage}); + return qiniuHelper.list('blog/index','',30).then(function(result){ + return Promise.map(result.items,function (item) { + return redis.lpush('indexImages',config.qiniu.domain + item.key + '-600x1500q80'); + }); + }); + }else{ + return redis.lrange('indexImages', 0, 30).then(function (images) { + var index = _.random(images.length - 1); + return res.status(200).json({success:true,img:images[index]}); + }); + } + }).catch(function (err) { + redis.del('indexImages'); + return next(err); + }); } + //用户喜欢 exports.toggleLike = function (req,res,next) { var aid = new mongoose.Types.ObjectId(req.params.id); diff --git a/server/api/user/user.controller.js b/server/api/user/user.controller.js index d073ad1..5935177 100644 --- a/server/api/user/user.controller.js +++ b/server/api/user/user.controller.js @@ -74,7 +74,8 @@ exports.addUser = function (req,res) { var newUser = new User(req.body); newUser.role = 'user'; - newUser.saveAsync().spread(function(user,number) { + + newUser.saveAsync().then(function(user) { Logs.create({ uid:req.user._id, content:"创建新用户 "+ (user.email || user.nickname), @@ -82,7 +83,7 @@ exports.addUser = function (req,res) { }); return res.status(200).json({success:true,user_id:user._id}); }).catch(function (err) { - if(err.errors.nickname){ + if(err.errors && err.errors.nickname){ err = {error_msg:err.errors.nickname.message} } return res.status(500).send(err); @@ -141,7 +142,7 @@ exports.updateUser = function (req,res) { if(req.body.newPassword){ user.password = req.body.newPassword; } - return user.saveAsync().spread(function (user,number) { + return user.saveAsync().then(function (user) { Logs.create({ email:req.user._id, content:"编辑用户"+ (user.email || user.nickname), @@ -178,7 +179,7 @@ exports.mdUser = function (req,res,next) { var user = req.user; user.nickname = nickname; - user.saveAsync().spread(function (result,number) { + user.saveAsync().then(function (result) { return res.status(200).json({success:true,data:result.userInfo}); }).catch(function (err) { if(err.errors.nickname){ diff --git a/server/config/env/development.js b/server/config/env/development.js index 10a8a35..c86b83f 100644 --- a/server/config/env/development.js +++ b/server/config/env/development.js @@ -3,9 +3,14 @@ // 开发环境配置 // ================================== module.exports = { + //开发环境mongodb配置 mongo: { uri: 'mongodb://localhost/jackblog-dev' }, + //开发环境redis配置 + redis: { + db: 0 + }, seedDB: true, session:{ cookie: {maxAge: 60000*5} diff --git a/server/config/env/index.js b/server/config/env/index.js index 7e9f834..85e4035 100644 --- a/server/config/env/index.js +++ b/server/config/env/index.js @@ -8,6 +8,7 @@ var all = { env: process.env.NODE_ENV, root: path.normalize(__dirname + '/../../..'), port: process.env.PORT || 9000, + //mongodb配置 mongo: { options: { db: { @@ -15,11 +16,19 @@ var all = { } } }, + //redis 配置 + redis: { + host: '127.0.0.1', + port: 6379 + }, + //是否初始化数据 seedDB: false, session:{ secrets: 'jackblog-secret', }, + //用户角色种类 userRoles: ['user', 'admin'], + //七牛配置 qiniu:{ app_key:"app_key", app_secret:"app_secret", @@ -28,6 +37,7 @@ var all = { }, //默认首页图片. defaultIndexImage:"http://upload.jackhu.top/blog/index/8x7hVJvpE3Z6ruwgtd2G.jpg", + //第三方登录配置 github:{ clientID:"github", clientSecret:"clientSecret", @@ -43,6 +53,7 @@ var all = { clientSecret:"clientSecret", callbackURL:"/auth/qq/callback" }, + //移动APP列表 apps:[ { name:'React Native', diff --git a/server/config/env/production.js b/server/config/env/production.js index da1ad28..127b4c3 100644 --- a/server/config/env/production.js +++ b/server/config/env/production.js @@ -4,6 +4,7 @@ // ================================= module.exports = { port: process.env.PORT || 8800, + //生产环境mongodb配置 mongo: { uri: 'mongodb://localhost/jackblog', options: { @@ -11,6 +12,11 @@ module.exports = { pass:'pass' //生产环境密码 } }, + //生产环境redis配置 + redis: { + db: 1 + }, + //生产环境cookie是否需要domain视具体情况而定. session:{ cookie: {domain:'.jackhu.top',maxAge: 60000*5} } diff --git a/server/config/env/test.js b/server/config/env/test.js index 4cf4878..f05b2be 100644 --- a/server/config/env/test.js +++ b/server/config/env/test.js @@ -6,6 +6,9 @@ module.exports = { mongo: { uri: 'mongodb://localhost/jackblog-test' }, + redis: { + db: 2 + }, port: process.env.PORT || 8080, seedDB: true }; \ No newline at end of file diff --git a/server/config/express.js b/server/config/express.js index 160df31..bf4c95e 100644 --- a/server/config/express.js +++ b/server/config/express.js @@ -10,11 +10,10 @@ var path = require('path'); var config = require('./env'); var passport = require('passport'); var session = require('express-session'); -var MongoStore = require('connect-mongo')(session); +var RedisStore = require('connect-redis')(session); var mongoose = require('mongoose'); module.exports = function(app) { - app.enable('trust proxy'); var options = { origin: true, @@ -30,9 +29,12 @@ module.exports = function(app) { secret: config.session.secrets, resave: false, saveUninitialized: false, - store: new MongoStore({ mongooseConnection: mongoose.connection }), + store: new RedisStore({ + host:config.redis.host, + port:config.redis.port, + pass:config.redis.password || '' + }), cookie: config.session.cookie })); app.use(passport.initialize()); - }; diff --git a/server/config/seed.js b/server/config/seed.js index f5ead52..6696e2a 100644 --- a/server/config/seed.js +++ b/server/config/seed.js @@ -4,15 +4,15 @@ 'use strict'; -var mongoose = require('mongoose'), - User = mongoose.model('User'), - Article = mongoose.model('Article'), - TagCategory = mongoose.model('TagCategory'), - Tag = mongoose.model('Tag'); +var mongoose = require('mongoose'); +var User = mongoose.model('User'); +var Article = mongoose.model('Article'); +var TagCategory = mongoose.model('TagCategory'); +var Tag = mongoose.model('Tag'); var Promise = require('bluebird'); //初始化标签,文章,用户 - if(process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'){ + if(process.env.NODE_ENV === 'development'){ User.countAsync().then(function (count) { if(count === 0){ User.removeAsync().then(function () { diff --git a/server/util/qiniu/index.js b/server/util/qiniu/index.js index 3397527..dc58cc5 100644 --- a/server/util/qiniu/index.js +++ b/server/util/qiniu/index.js @@ -37,7 +37,7 @@ var bucket = config.qiniu.bucket; exports.bucket = bucket; //将网络图片上传到七牛服务器 exports.fetch = function (url,key) { - return this.fetchFile(url,bucket,key).spread(function (result,response) { + return this.fetchFile(url,bucket,key).then(function (result) { result.url = config.qiniu.domain + result.key; return result; }); @@ -47,7 +47,7 @@ exports.fetch = function (url,key) { exports.upload = function (path,key) { var extra = new qiniu.io.PutExtra(); var uptoken = getUptoken(config.qiniu.bucket); - return this.uploadFile(uptoken, key, path, extra).spread(function(result,response){ + return this.uploadFile(uptoken, key, path, extra).then(function(result){ result.url = config.qiniu.domain + result.key; return result; }); @@ -57,7 +57,7 @@ exports.upload = function (path,key) { exports.move = function(keySrc,keyDest){ var bucketSrc,bucketDest; bucketSrc = bucketDest = bucket; - return this.moveFile(bucketSrc, keySrc, bucketDest, keyDest).spread(function (result,response) { + return this.moveFile(bucketSrc, keySrc, bucketDest, keyDest).then(function (result) { return result; }); }; @@ -65,13 +65,13 @@ exports.move = function(keySrc,keyDest){ exports.copy = function(keySrc,keyDest){ var bucketSrc,bucketDest; bucketSrc = bucketDest = bucket; - return this.copyFile(bucketSrc, keySrc, bucketDest, keyDest).spread(function (result,response) { + return this.copyFile(bucketSrc, keySrc, bucketDest, keyDest).then(function (result) { return result; }); }; exports.remove = function(key){ - return this.removeFile(bucket,key).spread(function (result,response) { + return this.removeFile(bucket,key).then(function (result) { return result; }) }; @@ -81,9 +81,7 @@ prefix 想要查询的资源前缀缺省值为空字符串,limit 限制条数缺 marker 上一次列举返回的位置标记,作为本次列举的起点信息。缺省值为空字符串 */ exports.list = function(prefix, marker, limit){ - return this.allList(bucket, prefix, marker, limit).spread(function(result,response){ + return this.allList(bucket, prefix, marker, limit).then(function(result){ return result; }) -}; - - +}; \ No newline at end of file diff --git a/server/util/redis/index.js b/server/util/redis/index.js new file mode 100644 index 0000000..a9b3e83 --- /dev/null +++ b/server/util/redis/index.js @@ -0,0 +1,14 @@ +'use strict' + +var _ = require('lodash'); +var Redis = require("ioredis"); +var config = require('../../config/env'); +var logger = require('../logs'); + +var client = new Redis(config.redis) + +client.on("error", function (err) { + logger.error('redis error', err) +}) + +exports = module.exports = client \ No newline at end of file diff --git a/server/util/tools/index.js b/server/util/tools/index.js index de4450c..a2ab421 100644 --- a/server/util/tools/index.js +++ b/server/util/tools/index.js @@ -1,5 +1,7 @@ "use strict"; + var _ = require('lodash'); + //生成随机字符串 exports.randomString = function (len) {   len = len || 12; diff --git a/test/api/article.test.js b/test/api/article.test.js index e477d64..c41ee20 100644 --- a/test/api/article.test.js +++ b/test/api/article.test.js @@ -10,41 +10,37 @@ var Logs = mongoose.model('Logs'); var Promise = require('bluebird'); var qiniuHelper = require('../../server/util/qiniu'); var sinon = require('sinon'); +var authHelper = require('../middlewares/authHelper'); +var redis = require('../../server/util/redis'); describe('test/api/article.test.js',function () { //测试需要一篇文章 var token, mockArticleId,mockAdminId; var mockTagId = '55e127401cfddd2c4be93f6b'; var mockTagIds = ['55e127401cfddd2c4be93f6b']; - before(function (done) { - User.createAsync({ - nickname:'测试' + new Date().getTime(), - email:'test' + new Date().getTime() + '@tets.com', - password:'test', - role:'admin', - status:1 - }).then(function (user) { - mockAdminId = user._id; - request.post('/auth/local') - .send({ - email: user.email, - password: 'test' - }) - .end(function (err,res) { - token = res.body.token; - done(); - }) - }); + before(function (done) { + authHelper.createUser('admin').then(function (user) { + mockAdminId = user._id; + return user; + }).then(function (user) { + authHelper.getToken(request, user.email).then(function (result) { + token = result; + done(); + }); + }).catch(function (err) { + console.log(err); }); + }); - after(function (done) { - User.findByIdAndRemoveAsync(mockAdminId).then(function () { - Logs.removeAsync(); - done(); - }).catch(function (err) { - done(err); - }); + after(function (done) { + User.findByIdAndRemoveAsync(mockAdminId).then(function () { + Logs.removeAsync(); + redis.del('indexImages'); + done(); + }).catch(function (err) { + done(err); }); + }); describe('post /article/addArticle',function () { it('should not title return error',function (done) { @@ -349,8 +345,6 @@ describe('test/api/article.test.js',function () { }); }); - - describe('get /article/getIndexImage',function () { var stubQiniu; beforeEach(function () { @@ -361,9 +355,7 @@ describe('test/api/article.test.js',function () { }); it('should return index image',function (done) { - stubQiniu.returns(Promise.resolve({items:[{ - key:'aaaabbbbdddddcccc' - }]})); + stubQiniu.returns(Promise.resolve({items:[1, 2, 3, 4, 5].map(i=>({key:i}))})); request.get('/article/getIndexImage') .expect(200) .end(function (err,res) { @@ -375,6 +367,17 @@ describe('test/api/article.test.js',function () { }); }); + it('should return redis image',function (done) { + request.get('/article/getIndexImage') + .expect(200) + .end(function (err,res) { + if (err) return done(err); + res.body.success.should.be.true(); + res.body.img.should.be.String; + done(); + }); + }); + }); describe('get /article/:id/getPrenext', function() { diff --git a/test/api/comment.test.js b/test/api/comment.test.js index 4a7d312..f154164 100644 --- a/test/api/comment.test.js +++ b/test/api/comment.test.js @@ -8,38 +8,30 @@ var User = mongoose.model('User'); var Article = mongoose.model('Article'); var Comment = mongoose.model('Comment'); var Logs = mongoose.model('Logs'); +var authHelper = require('../middlewares/authHelper'); describe('test/api/comment.test.js',function () { //测试需要一篇文章,和这篇文章的评论. var token, mockUserId,mockArticleId, mockCommentId,mockReplyId; before(function (done) { - User.createAsync({ - nickname:'测试' + new Date().getTime(), - email:'test' + new Date().getTime() + '@tets.com', - password:'test', - role:'admin', - status:1 + authHelper.createUser('admin').then(function (user) { + mockUserId = user._id; + return Article.createAsync({ + author_id:user._id, + title:'第' + new Date().getTime() + '篇文章', + content:'

我第n次爱你.

', + status:1 + }).then(function (article) { + mockArticleId = article._id; + return user; + }); }).then(function (user) { - mockUserId = user._id; - return Article.createAsync({ - author_id:user._id, - title:'第' + new Date().getTime() + '篇文章', - content:'

我第n次爱你.

', - status:1 - }).then(function (article) { - mockArticleId = article._id; - return user; - }); - }).then(function (user) { - request.post('/auth/local') - .send({ - email: user.email, - password: 'test' - }) - .end(function (err,res) { - token = res.body.token; - done(); - }); + authHelper.getToken(request, user.email).then(function (result) { + token = result; + done(); + }); + }).catch(function (err) { + console.log(err); }); }); diff --git a/test/api/logs.test.js b/test/api/logs.test.js index 5045b2e..922b5a2 100644 --- a/test/api/logs.test.js +++ b/test/api/logs.test.js @@ -6,18 +6,13 @@ var should = require("should"); var mongoose = require('mongoose'); var User = mongoose.model('User'); var Logs = mongoose.model('Logs'); +var authHelper = require('../middlewares/authHelper'); describe('test/api/logs.test.js',function () { //测试需要一篇文章,和这篇文章的评论. var token, mockLogId,mockUserId; before(function (done) { - User.createAsync({ - nickname:'测试' + new Date().getTime(), - email:'test' + new Date().getTime() + '@tets.com', - password:'test', - role:'admin', - status:1 - }).then(function (user) { + authHelper.createUser('admin').then(function (user) { mockUserId = user._id; return Logs.createAsync({ content:'删除用户.', @@ -32,17 +27,13 @@ describe('test/api/logs.test.js',function () { return user; }); }).then(function (user) { - request.post('/auth/local') - .send({ - email: user.email, - password: 'test' - }) - .end(function (err,res) { - token = res.body.token; - done(); - }) + authHelper.getToken(request, user.email).then(function (result) { + token = result; + done(); + }); + }).catch(function (err) { + console.log(err); }); - }); after(function (done) { diff --git a/test/api/tags.test.js b/test/api/tags.test.js index e17e55f..2cf3897 100644 --- a/test/api/tags.test.js +++ b/test/api/tags.test.js @@ -8,27 +8,21 @@ var User = mongoose.model('User'); var TagCategory = mongoose.model('TagCategory'); var Tag = mongoose.model('Tag'); var Logs = mongoose.model('Logs'); +var authHelper = require('../middlewares/authHelper'); describe('test/api/tags.test.js',function () { var token, mockUserId,mockTagCatId,mockTagId; before(function (done) { - User.createAsync({ - nickname:'测试' + new Date().getTime(), - email:'test' + new Date().getTime() + '@tets.com', - password:'test', - role:'admin', - status:1 + authHelper.createUser('admin').then(function (user) { + mockUserId = user._id; + return user; }).then(function (user) { - mockUserId = user._id; - request.post('/auth/local') - .send({ - email: user.email, - password: 'test' - }) - .end(function (err,res) { - token = res.body.token; - done(); - }) + authHelper.getToken(request, user.email).then(function (result) { + token = result; + done(); + }); + }).catch(function (err) { + console.log(err); }); }); diff --git a/test/api/user.test.js b/test/api/user.test.js index 5520ce8..a72f199 100644 --- a/test/api/user.test.js +++ b/test/api/user.test.js @@ -8,344 +8,341 @@ var User = mongoose.model('User'); var TagCategory = mongoose.model('TagCategory'); var Tag = mongoose.model('Tag'); var Logs = mongoose.model('Logs'); +var authHelper = require('../middlewares/authHelper'); describe('test/api/user.test.js',function () { - var token,mockUserId,mockAdminId,mockUpdateNickName,mockAdminNickname = '测试' + new Date().getTime(); - before(function (done) { - User.createAsync({ - nickname:mockAdminNickname, - email:'test' + new Date().getTime() + '@tets.com', - password:'test', - role:'admin', - status:1 - }).then(function (user) { - mockAdminId = user._id; - request.post('/auth/local') - .send({ - email: user.email, - password: 'test' - }) - .end(function (err,res) { - token = res.body.token; - done(); - }) - }); - }); + var token,mockUserId,mockAdminId,mockNickname,mockUpdateNickName,mockAdminNickname; + before(function (done) { + authHelper.createUser('admin').then(function (user) { + mockAdminId = user._id; + mockAdminNickname = user.nickname; + return user; + }).then(function (user) { + authHelper.getToken(request, user.email).then(function (result) { + token = result; + done(); + }); + }).catch(function (err) { + console.log(err); + }); + }); - after(function (done) { - User.findByIdAndRemoveAsync(mockAdminId).then(function () { - Logs.removeAsync(); - done(); - }); - }); + after(function (done) { + User.removeAsync().then(function () { + Logs.removeAsync(); + done(); + }); + }); - describe('post /users/addUser', function() { - it('should when not nickname return error', function(done) { - request.post('/users/addUser') - .set('Authorization','Bearer ' + token) - .send({ - email:'test@test.com' + new Date().getTime(), - password:'test' - }) - .expect(422,done); - }); + describe('post /users/addUser', function() { + mockNickname = '呢称' + new Date().getTime(); - it('should when not email return error', function(done) { - request.post('/users/addUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname: "呢称" + new Date().getTime(), - password:'test' - }) - .expect(422,done); - }); + it('should when not nickname return error', function(done) { + request.post('/users/addUser') + .set('Authorization','Bearer ' + token) + .send({ + email:'test@test.com' + new Date().getTime(), + password:'test' + }) + .expect(422,done); + }); - it('should when nickname error return error', function(done) { - request.post('/users/addUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname: 'jakc^^&&', - email:'test@test.com' + new Date().getTime(), - password:'test' - }) - .expect(422,done); - }); + it('should when not email return error', function(done) { + request.post('/users/addUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname: "呢称" + new Date().getTime(), + password:'test' + }) + .expect(422,done); + }); - it('should when email error return error', function(done) { - request.post('/users/addUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname: "呢称" + new Date().getTime(), - email:'test.com' + new Date().getTime(), - password:'test' - }) - .expect(422,done); - }); - var nickname = '呢称' + new Date().getTime(); - it('should return new user', function(done) { - request.post('/users/addUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname: nickname, - email:'test@test.com' + new Date().getTime(), - password:'test' - }) - .expect(200) - .expect('Content-Type', /json/) - .end(function (err,res) { - if(err) return done(err); - mockUserId = res.body.user_id; - res.body.user_id.should.be.String(); - res.body.success.should.be.true(); - done(); - }) - }); + it('should when nickname error return error', function(done) { + request.post('/users/addUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname: 'jakc^^&&', + email:'test@test.com' + new Date().getTime(), + password:'test' + }) + .expect(422,done); + }); - it('should same nickname return error', function(done) { - request.post('/users/addUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname: nickname, - email:'test@test.com' + new Date().getTime(), - password:'test' - }) - .expect(500,done); - }); + it('should when email error return error', function(done) { + request.post('/users/addUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname: "呢称" + new Date().getTime(), + email:'test.com' + new Date().getTime(), + password:'test' + }) + .expect(422,done); + }); - }); + it('should return new user', function(done) { + request.post('/users/addUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname: mockNickname, + email:'test' + new Date().getTime() + '@test.com', + password:'test' + }) + .expect(200) + .expect('Content-Type', /json/) + .end(function (err,res) { + if(err) { return done(err); } + mockUserId = res.body.user_id; + res.body.user_id.should.be.String(); + res.body.success.should.be.true(); + done(); + }) + }); - describe('put /users/:id/updateUser', function() { - mockUpdateNickName = '呢称' + new Date().getTime(); + it('should same nickname return error', function(done) { + request.post('/users/addUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname: mockNickname, + email:'test@test.com' + new Date().getTime(), + password:'test' + }) + .expect(500,done); + }); - it('should when not nickname return error', function(done) { - request.put('/users/' + mockUserId + '/updateUser') - .set('Authorization','Bearer ' + token) - .send({ - email:'test@test.com' + new Date().getTime(), - status:1 - }) - .expect(422,done); - }); - it('should when not email return error', function(done) { - request.put('/users/' + mockUserId + '/updateUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname:mockUpdateNickName, - status:1 - }) - .expect(422,done); - }); - it('should when nickname error return error', function(done) { - request.put('/users/' + mockUserId + '/updateUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname:'jack^^%%', - email:'test@test.com' + new Date().getTime(), - status:1 - }) - .expect(422,done); - }); - it('should when email error return error', function(done) { - request.put('/users/' + mockUserId + '/updateUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname:mockUpdateNickName, - email:'test.com', - status:1 - }) - .expect(422,done); - }); - it('should return update user', function(done) { - request.put('/users/' + mockUserId + '/updateUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname:mockUpdateNickName, - email:'test@test.com' + new Date().getTime(), - status:1 - }) - .expect(200) - .expect('Content-Type', /json/) - .end(function (err,res) { - if(err) return done(err); - res.body.user_id.should.be.String(); - res.body.success.should.be.true(); - done(); - }) - }); - it('should update password return success', function(done) { - request.put('/users/' + mockUserId + '/updateUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname:mockUpdateNickName, - email:'test@test.com' + new Date().getTime(), - status:1, - newPassword:'testpwd' - }) - .expect(200) - .expect('Content-Type', /json/) - .end(function (err,res) { - if(err) return done(err); - res.body.user_id.should.be.String(); - res.body.success.should.be.true(); - done(); - }) - }); + }); - it('should same nickname return error', function(done) { - request.put('/users/' + mockUserId + '/updateUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname:mockAdminNickname, - email:'test@test.com' + new Date().getTime(), - status:1 - }) - .expect(500,done); - }); + describe('put /users/:id/updateUser', function() { + mockUpdateNickName = '呢称' + new Date().getTime(); + it('should when not nickname return error', function(done) { + request.put('/users/' + mockUserId + '/updateUser') + .set('Authorization','Bearer ' + token) + .send({ + email:'test@test.com' + new Date().getTime(), + status:1 + }) + .expect(422,done); + }); + it('should when not email return error', function(done) { + request.put('/users/' + mockUserId + '/updateUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname:mockUpdateNickName, + status:1 + }) + .expect(422,done); + }); + it('should when nickname error return error', function(done) { + request.put('/users/' + mockUserId + '/updateUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname:'jack^^%%', + email:'test@test.com' + new Date().getTime(), + status:1 + }) + .expect(422,done); + }); + it('should when email error return error', function(done) { + request.put('/users/' + mockUserId + '/updateUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname:mockUpdateNickName, + email:'test.com', + status:1 + }) + .expect(422,done); + }); - }); + it('should return update user', function(done) { + request.put('/users/' + mockUserId + '/updateUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname:mockUpdateNickName, + email:'test@test.com' + new Date().getTime(), + status:1 + }) + .expect(200) + .expect('Content-Type', /json/) + .end(function (err,res) { + if(err) return done(err); + res.body.user_id.should.be.String(); + res.body.success.should.be.true(); + done(); + }) + }); - describe('put /users/mdUser', function() { + it('should update password return success', function(done) { + request.put('/users/' + mockUserId + '/updateUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname:mockUpdateNickName, + email:'test@test.com' + new Date().getTime(), + status:1, + newPassword:'testpwd' + }) + .expect(200) + .expect('Content-Type', /json/) + .end(function (err,res) { + if(err) return done(err); + res.body.user_id.should.be.String(); + res.body.success.should.be.true(); + done(); + }) + }); - it('should when not nickname return error', function(done) { - request.put('/users/mdUser') - .set('Authorization','Bearer ' + token) - .expect(422,done); - }); + it('should update user same nickname return error', function(done) { + request.put('/users/' + mockUserId + '/updateUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname:mockAdminNickname, + email:'test@test.com' + new Date().getTime(), + status:1 + }) + .expect(500,done); + }); + }); - it('should when nickname error return error', function(done) { - request.put('/users/mdUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname:'jack^^&&' - }) - .expect(422,done); - }); - it('should return my user', function(done) { - request.put('/users/mdUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname:'呢称' + new Date().getTime() - }) - .expect(200) - .expect('Content-Type', /json/) - .end(function (err,res) { - if(err) return done(err); - res.body.data.nickname.should.be.String(); - res.body.success.should.be.true(); - done(); - }) - }); + describe('put /users/mdUser', function() { - it('should when same nickname return error', function(done) { - request.put('/users/mdUser') - .set('Authorization','Bearer ' + token) - .send({ - nickname: mockUpdateNickName - }) - .expect(500,done); - }); + it('should when not nickname return error', function(done) { + request.put('/users/mdUser') + .set('Authorization','Bearer ' + token) + .expect(422,done); + }); - }); + it('should when nickname error return error', function(done) { + request.put('/users/mdUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname:'jack^^&&' + }) + .expect(422,done); + }); + it('should return my user', function(done) { + request.put('/users/mdUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname:'呢称' + new Date().getTime() + }) + .expect(200) + .expect('Content-Type', /json/) + .end(function (err,res) { + if(err) return done(err); + res.body.data.nickname.should.be.String(); + res.body.success.should.be.true(); + done(); + }) + }); - describe('get /users/getUserList',function () { - it('should return users list',function (done) { - request.get('/users/getUserList') - .set('Authorization','Bearer ' + token) - .expect(200) - .expect('Content-Type', /json/) - .end(function (err,res) { - if(err) return done(err); - res.body.data.length.should.be.above(0); - res.body.count.should.be.above(0); - done(); - }) - }); - it('should sort false return users list',function (done) { - request.get('/users/getUserList') - .set('Authorization','Bearer ' + token) - .query({ - itemsPerPage:1, - sortName:'', - sortOrder:'false' - }) - .expect(200) - .expect('Content-Type', /json/) - .end(function (err,res) { - if(err) return done(err); - res.body.data.length.should.be.above(0); - res.body.count.should.be.above(0); - done(); - }) - }); - }); + it('should when same nickname return error', function(done) { + request.put('/users/mdUser') + .set('Authorization','Bearer ' + token) + .send({ + nickname: mockUpdateNickName + }) + .expect(500,done); + }); - describe('get /users/getUserProvider', function() { - it('should return User Provider', function(done) { - request.get('/users/getUserProvider') - .set('Authorization','Bearer ' + token) - .expect(200) - .expect('Content-Type', /json/) - .end(function (err,res) { - if(err) return done(err); - res.body.data.should.be.Object(); - done(); - }) - }); - }); + }); - describe('get /users/getCaptcha', function() { - it('should return captcha image', function(done) { - request.get('/users/getCaptcha') - .expect(200,done); - }); - }); + describe('get /users/getUserList',function () { + it('should return users list',function (done) { + request.get('/users/getUserList') + .set('Authorization','Bearer ' + token) + .expect(200) + .expect('Content-Type', /json/) + .end(function (err,res) { + if(err) return done(err); + res.body.data.length.should.be.above(0); + res.body.count.should.be.above(0); + done(); + }) + }); + it('should sort false return users list',function (done) { + request.get('/users/getUserList') + .set('Authorization','Bearer ' + token) + .query({ + itemsPerPage:1, + sortName:'', + sortOrder:'false' + }) + .expect(200) + .expect('Content-Type', /json/) + .end(function (err,res) { + if(err) return done(err); + res.body.data.length.should.be.above(0); + res.body.count.should.be.above(0); + done(); + }) + }); + }); - describe('get /users/snsLogins', function() { - it('should return status 200', function(done) { - request.get('/users/snsLogins') - .expect(200,done); - }); - }); + describe('get /users/getUserProvider', function() { + it('should return User Provider', function(done) { + request.get('/users/getUserProvider') + .set('Authorization','Bearer ' + token) + .expect(200) + .expect('Content-Type', /json/) + .end(function (err,res) { + if(err) return done(err); + res.body.data.should.be.Object(); + done(); + }) + }); + }); - describe('get /users/me', function() { - it('should return me info', function(done) { - request.get('/users/me') - .set('Authorization','Bearer ' + token) - .expect(200) - .expect('Content-Type', /json/) - .end(function (err,res) { - if(err) return done(err); - res.body.nickname.should.be.String(); - done(); - }) - }); - }); + describe('get /users/getCaptcha', function() { + it('should return captcha image', function(done) { + request.get('/users/getCaptcha') + .expect(200,done); + }); + }); - describe('del /users/:id', function() { - it('should if userid === req.user._id return error', function(done) { - request.del('/users/' + mockAdminId) - .set('Authorization','Bearer ' + token) - .expect(403,done); - }); + describe('get /users/snsLogins', function() { + it('should return status 200', function(done) { + request.get('/users/snsLogins') + .expect(200,done); + }); + }); - it('should if userId error return error', function(done) { - request.del('/users/dddddd') - .set('Authorization','Bearer ' + token) - .expect(500,done); - }); + describe('get /users/me', function() { + it('should return me info', function(done) { + request.get('/users/me') + .set('Authorization','Bearer ' + token) + .expect(200) + .expect('Content-Type', /json/) + .end(function (err,res) { + if(err) return done(err); + res.body.nickname.should.be.String(); + done(); + }) + }); + }); - it('should return me info', function(done) { - request.del('/users/' + mockUserId) - .set('Authorization','Bearer ' + token) - .expect(200) - .expect('Content-Type', /json/) - .end(function (err,res) { - if(err) return done(err); - res.body.success.should.be.true(); - done(); - }) - }); - }); + describe('del /users/:id', function() { + it('should if userid === req.user._id return error', function(done) { + request.del('/users/' + mockAdminId) + .set('Authorization','Bearer ' + token) + .expect(403,done); + }); + + it('should if userId error return error', function(done) { + request.del('/users/dddddd') + .set('Authorization','Bearer ' + token) + .expect(500,done); + }); + + it('should return me info', function(done) { + request.del('/users/' + mockUserId) + .set('Authorization','Bearer ' + token) + .expect(200) + .expect('Content-Type', /json/) + .end(function (err,res) { + if(err) return done(err); + res.body.success.should.be.true(); + done(); + }) + }); + }); }); \ No newline at end of file diff --git a/test/middlewares/authHelper.js b/test/middlewares/authHelper.js new file mode 100644 index 0000000..47cc3ca --- /dev/null +++ b/test/middlewares/authHelper.js @@ -0,0 +1,33 @@ +"use strict"; + +var should = require("should"); +var mongoose = require("mongoose"); +var User = mongoose.model('User'); +var Promise = require('bluebird'); + +exports.createUser = function (role,nickname,status) { + return User.createAsync({ + nickname: nickname || '测试' + new Date().getTime(), + email:'test' + new Date().getTime() + '@tets.com', + password:'test', + role: role || 'admin', + status: status || 1 + }); +} + +exports.getToken = function (agent, email) { + return new Promise(function (resolve, reject) { + agent + .post('/auth/local') + .set("Content-Type", "application/json") + .send({ email: email, password:'test' }) + .redirects(0) + .expect(200) + .end(function(err, res) { + if (err) { reject(err); } + should.exist(res.body); + should.exist(res.body.token); + resolve(res.body.token); + }); + }); +} \ No newline at end of file diff --git a/test/util/qiniu.test.js b/test/util/qiniu.test.js index 5caa23e..cc52b47 100644 --- a/test/util/qiniu.test.js +++ b/test/util/qiniu.test.js @@ -4,7 +4,6 @@ var should = require("should"); var qiniuHelper = require('../../server/util/qiniu'); var sinon = require('sinon'); var Promise = require('bluebird'); -require('should-promised'); describe('test/util/qiniu.js',function () { var mockKey = 'PwzqKey'; @@ -16,9 +15,9 @@ describe('test/util/qiniu.js',function () { var stubFetch; beforeEach(function () { stubFetch = sinon.stub(qiniuHelper,'fetchFile'); - stubFetch.withArgs(mockUrl,mockBucket,mockKey).returns(Promise.resolve([ - {key:'/blog/article/test.png'},{status:200} - ])); + stubFetch.withArgs(mockUrl,mockBucket,mockKey).returns( + Promise.resolve({key:'/blog/article/test.png'}) + ); //stubFetch.withArgs('errUrl',mockBucket,'errKey').returns(Promise.reject()); }); @@ -40,9 +39,7 @@ describe('test/util/qiniu.js',function () { var uploadStub; beforeEach(function () { uploadStub = sinon.stub(qiniuHelper,'uploadFile'); - uploadStub.returns(Promise.resolve([ - {key:'/blog/article/test.png'},{status:200} - ])); + uploadStub.returns(Promise.resolve({key:'/blog/article/test.png'})); }); afterEach(function () { @@ -62,9 +59,7 @@ describe('test/util/qiniu.js',function () { var moveStub; beforeEach(function () { moveStub = sinon.stub(qiniuHelper,'moveFile'); - moveStub.returns(Promise.resolve([ - {key:'/blog/article/test.png'},{status:200} - ])); + moveStub.returns(Promise.resolve({key:'/blog/article/test.png'})); }); afterEach(function () { @@ -84,9 +79,7 @@ describe('test/util/qiniu.js',function () { var copyStub; beforeEach(function () { copyStub = sinon.stub(qiniuHelper,'copyFile'); - copyStub.returns(Promise.resolve([ - {key:'/blog/article/test.png'},{status:200} - ])); + copyStub.returns(Promise.resolve({key:'/blog/article/test.png'})); }); afterEach(function () { @@ -105,9 +98,7 @@ describe('test/util/qiniu.js',function () { var removeStub; beforeEach(function () { removeStub = sinon.stub(qiniuHelper,'removeFile'); - removeStub.returns(Promise.resolve([ - {key:'/blog/article/test.png'},{status:200} - ])); + removeStub.returns(Promise.resolve({key:'/blog/article/test.png'})); }); afterEach(function () { @@ -127,9 +118,7 @@ describe('test/util/qiniu.js',function () { var listStub; beforeEach(function () { listStub = sinon.stub(qiniuHelper,'allList'); - listStub.returns(Promise.resolve([ - {items:[{key:'/blog/article/test.png'}]},{status:200} - ])); + listStub.returns(Promise.resolve({items:[{key:'/blog/article/test.png'}]})); }); afterEach(function () {