Skip to content

finish #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
9 changes: 9 additions & 0 deletions app/config/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
db: {
user: 'admin',
password: '123456',
host: 'localhost',
port: 27017,
name: 'nba'
}
}
3 changes: 3 additions & 0 deletions app/constant/error-code.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
'ParameterError': -2001
}
5 changes: 5 additions & 0 deletions app/constant/status-code.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
Ok: 200,
BadRequest: 400,
NotFound: 404
}
27 changes: 27 additions & 0 deletions app/lib/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const mongoose = require('mongoose');
const config = require('../config');
const util = require('../utils');
const schema = require('../schema');

const log = util.log;

const connectionString = `mongodb://${config.db.host}:${config.db.port}/${config.db.name}`;

const db = module.exports = {};

db.Table = {};

db.Table.Player = mongoose.model('Player', schema.PlayerSchema);

db.connect = function() {
return new Promise(resolve => {
mongoose.connect(connectionString, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }, err => {
if(err) {
log('Mongodb occured error when it was connecting.')
throw err;
}
log('Mongodb has been connected.');
resolve();
});
});
}
5 changes: 5 additions & 0 deletions app/routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const PlayerRouter = require('./player');

module.exports = {
PlayerRouter
}
136 changes: 136 additions & 0 deletions app/routes/player.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
const express = require('express');
const db = require('../lib/database');
const util = require('../utils');

const log = util.log;

const router = express.Router();

function checkParameter(data) {
if(data.hasOwnProperty('id') && data.hasOwnProperty('name') && data.hasOwnProperty('position')) {
return true;
}
return false;
}

router.post('/', async (req, res) => {
let payload = {};

if(req.headers['content-type'] === 'application/xml') {
if(!checkParameter(req.body.Player)) {
res.status(405).send();
return;
} else {
payload.id = req.body.Player['id'][0];
payload.name = req.body.Player['name'][0];
payload.position = req.body.Player['position'][0];
}
} else {
if(!checkParameter(req.body)) {
res.status(405).send();
return;
} else {
payload.id = req.body.id
payload.name = req.body.name;
payload.position = req.body.position;
}
}

await db.Table.Player.create([
{
id: payload.id,
name: payload.name,
position: payload.position
}
], (err, ret) => {
if(err) {
log(`Add player failed. [${err}]`);
res.status(405).send();
return;
}
res.status(200).send();
});
});

router.put('/', async (req, res) => {
let payload = {};

if(req.headers['content-type'] === 'application/xml') {
if(!checkParameter(req.body.Player)) {
res.status(405).send();
return;
} else {
payload.id = req.body.Player['id'][0];
payload.name = req.body.Player['name'][0];
payload.position = req.body.Player['position'][0];
}
} else {
if(!checkParameter(req.body)) {
res.status(405).send();
return;
} else {
payload.id = req.body.id
payload.name = req.body.name;
payload.position = req.body.position;
}
}

await db.Table.Player.findOneAndUpdate({id: payload.id}, payload, (err, ret) => {
if(err) {
log(`Update player failed. [${err}]`);
res.status(405).send();
return;
}
if(ret === null) {
res.status(404).send();
return;
}
res.status(200).send();
});
});

router.get('/:id', async (req, res) => {
if(!req.params.hasOwnProperty('id')) {
res.status(400).send();
return;
}

await db.Table.Player.findOne({ id: req.params.id }, (err, ret) => {
if(err) {
log(`Get player failed. [${err}]`);
res.status(400).send();
return;
}
if(ret == null) {
res.status(404).send();
return;
}
res.send({
id: ret.id,
name: ret.name,
position: ret.position
});
});
});

router.delete('/:id', async (req, res) => {
if(!req.params.hasOwnProperty('id')) {
res.status(400).send();
return;
}

await db.Table.Player.deleteOne({ id: req.params.id }, (err, ret) => {
if(err) {
log(`Delete player failed. [${err}]`);
res.status(400).send();
return;
}
if(ret.deletedCount === 0) {
res.status(404).send();
return;
}
res.sendStatus(200);
});
});

module.exports = router;
5 changes: 5 additions & 0 deletions app/schema/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const PlayerSchema = require('./player.schema');

module.exports = {
PlayerSchema
}
9 changes: 9 additions & 0 deletions app/schema/player.schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const { Schema } = require('mongoose');

let PlayerSchema = new Schema({
id: { type: Number },
name: { type: String },
position: { type: String, enum: ['C', 'PF', 'SF', 'PG', 'SG'] }
});

module.exports = PlayerSchema;
22 changes: 19 additions & 3 deletions app/server.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
const express = require('express');
const bodyParser = require('body-parser');
const xmlBodyParser = require('body-parser-xml')(bodyParser);
const db = require('./lib/database');
const router = require('./routes');
const util = require('./utils');

const app = express();

app.use(bodyParser.urlencoded({ extended: false, limit: '20mb' }));
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.xml());

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");
});
app.use('/player', router.PlayerRouter);

const appStart = async () => {
await db.connect();
app.listen(3000, () => {
util.log("RESTful Server is listening on port 3000");
});
}

appStart();
7 changes: 7 additions & 0 deletions app/utils/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const log = function(msg) {
console.log(`[${new Date()}] ${msg}`);
}

module.exports = {
log
}
32 changes: 32 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "node-examination",
"version": "1.0.0",
"description": "Building a RESTful CRUD API with Node.js(>=v10.15.0), Express/Koa and MongoDB/MySQL.",
"main": "index.js",
"scripts": {
"start": "node app/server.js",
"test": "mocha"
},
"repository": {
"type": "git",
"url": "git+https://github.com/bridge5/node-examination.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/bridge5/node-examination/issues"
},
"homepage": "https://github.com/bridge5/node-examination#readme",
"dependencies": {
"body-parser": "^1.19.0",
"body-parser-xml": "^1.1.0",
"express": "^4.17.1",
"express-xml-bodyparser": "^0.3.0",
"mongoose": "^5.9.2"
},
"devDependencies": {
"mocha": "^7.1.0",
"supertest": "^4.0.2"
}
}
Loading