Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 2 additions & 40 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,40 +1,2 @@
# gitignore
# Logs
logs
*.log
lerna-debug.log
npm-debug.log
yarn-error.log
yarn.lock
stats.json
package-lock.json

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
bin/Release

# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
**/node_modules

#Webstorm metadata
.idea

# Mac files
.DS_Store
!.gitignore
/node_modules
19 changes: 19 additions & 0 deletions config/config.development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"ip": "127.0.0.1",
"port": 3000,
"log_path": "/var/log/NBA",
"mongo": {
"url": "172.16.11.201",
"port": 27017,
"db": "test_dev",
"auth": false,
"username": "",
"password": ""
},
"core": {

},
"redis_token": {

}
}
7 changes: 7 additions & 0 deletions models/mongo/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const playersModelsMakeup = require('./players');

const modelMakeup = {
...playersModelsMakeup,
};

module.exports = modelMakeup;
44 changes: 44 additions & 0 deletions models/mongo/players.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const mongoose = require('mongoose');
const uuid = require('uuid');

const { Schema } = mongoose;
/**
* 球员管理相关 models(MongoDB) 200223
* @author DZJ <duanzhenjie964@qq.com>
*/

/* 定义员工schema */
const PlayersSchema = new Schema({
name: String,
position: {
type: String,
enum : ['C','PF','SF','PG','SG']
},
});

/**
* 新建记录
* @param {Object} playerData
*/
PlayersSchema
.statics
.addNew = async function addNew(
playerData,
) {
const newData = {
name: playerData.name,
position: playerData.position,
add_datetime: new Date(),
};
const newObj = new this(newData);
await newObj.save();
return newObj;
};

const Players = mongoose.model('Players', PlayersSchema, 'players');

const makeup = {
Players: Players,
};

module.exports = makeup;
11 changes: 9 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,15 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"express": "^4.16.4",
"mongoose": "^5.4.8"
"mongoose": "^5.0.5",
"co": "^4.6.0",
"koa": "^2.5.3",
"koa-bodyparser": "^4.2.1",
"koa-router": "^7.4.0",
"koa-validate": "^1.0.7",
"bunyan": "^1.8.12",
"bunyan-format": "^0.2.1",
"uuid": "^3.3.2"
},
"devDependencies": {
"chai": "^4.2.0"
Expand Down
81 changes: 73 additions & 8 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,76 @@
const express = require('express');
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const validate = require('koa-validate');
const bunyan = require('bunyan');
const bformat = require('bunyan-format');
const cors = require('@koa/cors');
const http = require('http');
const mongoDBModels = require('./models/mongo');
const db = require('./utils/db');
const app = new Koa();
const config = require('./config/config.development');
const responseMiddleware = require('./utils/middleware');

const app = express();
const main = async () => {
try {
app.projConfig = {
...config,
};

app.get('/', (req, res) => {
res.json({"message": "Building a RESTful CRUD API with Node.js, Express/Koa and MongoDB."});
});
const formatOut = bformat({ outputMode: 'long' });
app.logger = bunyan.createLogger({
name: 'NBA_api',
src: true,
// streams: [{ stream: new BunyanLogStream() }],
streams: [{
level: 'debug',
stream: formatOut,
}, {
level: 'error',
path: `${config.log_path}/error_log.json`,
src: true,
}],
});

app.listen(3000, () => {
console.log("Server is listening on port 3000");
});
// Mongo DB
await db.mongo(config.mongo);
app.mongoDBModels = mongoDBModels;
app.logger.info('[OK] Mongo DB');

// Makeup App
app.use(bodyParser());
validate(app);

// 挂载封装好的返回逻辑
app.use(responseMiddleware);

let port;
app.use(cors());
const router = require('./swagger/api/router');
app.use(router.routes())
.use(router.allowedMethods());
app.logger.info('[OK] Apis');
port = config.port;

port = port || config.port;
http.createServer(app.callback()).listen(port, config.ip);

app.on('error', (err, ctx) => {
app.logger.error(err.stack);
});
app.proxy = true;
app.logger.info(`[OK] Start -> ${config.ip}:${port}`);
} catch (err) {
console.error(err.stack);
}
};

main();

// app.get('/', (req, res) => {
// res.json({"message": "Building a RESTful CRUD API with Node.js, Express/Koa and MongoDB."});
// });

// app.listen(3000, () => {
// console.log("Server is listening on port 3000");
// });
101 changes: 101 additions & 0 deletions swagger/api/Player.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
class PlayerAPIs {
// Demo
async demoAPI(ctx) {
try {
const resData = {
message: 'Building a RESTful CRUD API with Node.js, Express/Koa and MongoDB.',
};
return ctx.JSONRes(resData);
} catch (err) {
console.error(err.stack)
return ctx.JSONError(err.message);
}
}

async playerMiddleWare(player_id, ctx, next) {
try {
ctx.checkParams('player_id').notEmpty('球员id不能为空');
if (ctx.errors) {
return ctx.JSONError(ctx.errors);
}
const playerObj = await ctx.app.mongoDBModels.Players
.findOne({
_id: player_id,
});
if (!playerObj) {
return ctx.JSONError('球员不存在');
}
ctx.playerObj = playerObj;
return next();
} catch (err) {
ctx.app.logger.error(err.stack);
return ctx.JSONError(err.message);
}
}


// addPlayer
async addPlayer(ctx) {
try {
ctx.checkBody('name').notEmpty('请输入球员名称');
ctx.checkBody('position').notEmpty('请输入球员位置');
if (ctx.errors) {
return ctx.JSONError(ctx.errors);
}
const playerObj = ctx.request.body;
await ctx.app.mongoDBModels.Players.addNew(playerObj);

return ctx.JSONRes({ add_player: 'ok' });
} catch (err) {
ctx.app.logger.error(err.stack);
return ctx.JSONError(err.message);
}
}

// playerActionAPI
async playerActionAPI(ctx) {
try {
ctx.checkParams('action_type', '请输入操作类型').notEmpty();
if (ctx.params.action_type === 'update') {
ctx.checkBody('name').notEmpty('必须输入球员姓名');
ctx.checkBody('position').notEmpty('必须输入球员位置');
} else if (ctx.params.action_type === 'delete') {

}
if (ctx.errors) {
return ctx.JSONError(ctx.errors);
}
let resData = {};
if (ctx.params.action_type === 'update') {
const playerDate = ctx.request.body;
await ctx.playerObj.update(playerDate);
resData = { update_player: 'ok' };
} else if (ctx.params.action_type === 'delete') {
await ctx.playerObj.delete();
resData = { delete_player: 'ok' };
}
return ctx.JSONRes(resData);
} catch (err) {
ctx.app.logger.error(err.stack);
return ctx.JSONError(err.message);
}
}

// getPlayerById
async getPlayerById(ctx) {
try {
const res = {
id: ctx.playerObj._id,
name: ctx.playerObj.name,
age: ctx.playerObj.age,
};
return ctx.JSONRes(res);
} catch (err) {
ctx.app.logger.error(err.stack);
return ctx.JSONError(err.message);
}
}

}

module.exports = new PlayerAPIs();
27 changes: 27 additions & 0 deletions swagger/api/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const Router = require('koa-router');
const PlayerAPIs = require('./Player');

const PlayerControllers = require('./../controllers/Player');

// basePath
const router = new Router({
prefix: '/v1',
});

// 球员api路由
const PlayerRouter = new Router();

PlayerRouter
// demo
.get('/', PlayerAPIs.demoAPI)
// 有ID参数时默认查询Player对象
.param('player_id', PlayerAPIs.playerMiddleWare)
// 添加球员
.post('/', PlayerAPIs.addPlayer)
// 修改球员 || 删除球员 /id/操作类型
.post('/:player_id/:action_type', PlayerAPIs.playerActionAPI)
// 根据id获取球员
.get('/:player_id', PlayerAPIs.getPlayerById);

router.use('/player', PlayerRouter.routes(), PlayerRouter.allowedMethods());
module.exports = PlayerRouter;
Loading