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
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,34 @@ $ cd node-examination/swagger
$ npm start

$ open http://localhost:3030


// API server
$ cd node-examination/
$ npm install
$ node server.js

$ open http://localhost:3000


// MongoDB url
development: mongodb://localhost:27017/node-examination
test: mongodb://localhost:27017/node-examination-test
(defined in /config/database.config.js)


// API urls
[POST] http://localhost:3000/player
[GET] http://localhost:3000/players
[GET] http://localhost:3000/player/{playerId}
[PUT] http://localhost:3000/player
[DELETE] http://localhost:3000/player/{playerId}


// Run tests
$ cd node-examination/
$ npm install -g mocha
$ mocha
```

## Tasks
Expand Down
158 changes: 158 additions & 0 deletions app/controllers/player.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
const Player = require('../models/player.model.js');

// Create a new player
exports.create = (req, res) => {
// Validate request
if(!req.body.id) {
return res.status(405).send({
message: "Invalid input: Player id can not be empty"
});
}
if(!req.body.name) {
return res.status(405).send({
message: "Invalid input: Player name can not be empty"
});
}
if(!req.body.position) {
return res.status(405).send({
message: "Invalid input: Player position can not be empty"
});
}

// Check player with same id
var query = { id: req.body.id };
Player.find(query)
.then(players => {
if(players && players.length > 0){
return res.status(405).send({
message: "Invalid input: Player with id " + req.body.id + " already exist"
});
}else{
// Create a player
const player = new Player({
id: req.body.id,
name: req.body.name,
position: req.body.position
});

// Save player in the database
player.save()
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while creating the player."
});
});
}
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving players."
});
});
};

// Get all players from the database.
exports.findAll = (req, res) => {
Player.find()
.then(players => {
res.send(players);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving players."
});
});
};

// Find player by ID
exports.findOne = (req, res) => {
var query = { id: req.params.playerId };

Player.findOne(query)
.then(player => {
if(!player) {
return res.status(404).send({
message: "Player not found with id " + req.params.playerId
});
}
res.send(player);
}).catch(err => {
if(err.kind === 'ObjectId') {
return res.status(404).send({
message: "Player not found with id " + req.params.playerId
});
}
return res.status(500).send({
message: err.message || "Error retrieving player with id " + req.params.playerId
});
});
};

// Update player
exports.update = (req, res) => {
// Validate Request
if(!req.body.id) {
return res.status(405).send({
message: "Invalid input: Player id can not be empty"
});
}
if(!req.body.name) {
return res.status(405).send({
message: "Invalid input: Player name can not be empty"
});
}
if(!req.body.position) {
return res.status(405).send({
message: "Invalid input: Player position can not be empty"
});
}

// Find player and update it with the request body
var query = { id: req.body.id };

Player.findOneAndUpdate(query, {
name: req.body.name,
position: req.body.position
}, {new: true})
.then(player => {
if(!player) {
return res.status(404).send({
message: "Player not found with id " + req.body.id
});
}
res.send(player);
}).catch(err => {
if(err.kind === 'ObjectId') {
return res.status(404).send({
message: "Player not found with id " + req.body.id
});
}
return res.status(500).send({
message: err.message || "Error updating player with id " + req.body.id
});
});
};

// Delete player by ID
exports.delete = (req, res) => {
var query = { id: req.params.playerId };

Player.findOneAndRemove(query)
.then(player => {
if(!player) {
return res.status(404).send({
message: "Player not found with id " + req.params.playerId
});
}
res.send({message: "Player deleted successfully!"});
}).catch(err => {
if(err.kind === 'ObjectId' || err.name === 'NotFound') {
return res.status(404).send({
message: "Player not found with id " + req.params.playerId
});
}
return res.status(500).send({
message: err.message || "Could not delete player with id " + req.params.playerId
});
});
};
17 changes: 17 additions & 0 deletions app/models/player.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const mongoose = require('mongoose');

const PlayerSchema = mongoose.Schema({
id: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
position: String
}, {
timestamps: true
});

module.exports = mongoose.model('Player', PlayerSchema);
18 changes: 18 additions & 0 deletions app/routes/player.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module.exports = (app) => {
const players = require('../controllers/player.controller.js');

// Create a new player
app.post('/player', players.create);

// Get all players
app.get('/players', players.findAll);

// Find player by ID
app.get('/player/:playerId', players.findOne);

// Update player
app.put('/player', players.update);

// Delete player by ID
app.delete('/player/:playerId', players.delete);
}
6 changes: 6 additions & 0 deletions config/database.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
url: {
development: 'mongodb://localhost:27017/node-examination',
test: 'mongodb://localhost:27017/node-examination-test'
}
}
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4",
"mongoose": "^5.4.8"
"mongoose": "^5.4.8",
"mongoose-long": "^0.2.1"
},
"devDependencies": {
"chai": "^4.2.0"
"chai": "^4.2.0",
"chai-http": "^4.2.1"
},
"engines": {
"node": ">=10.15.0"
Expand Down
30 changes: 29 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,39 @@
const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// parse requests of content-type - application/json
app.use(bodyParser.json());

// Configuring the database
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

// Connecting to the database
mongoose.connect(dbConfig.url[app.settings.env], {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});

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

// Require API routes
require('./app/routes/player.routes.js')(app);

app.listen(3000, () => {
console.log("Server is listening on port 3000");
});
});

module.exports = app;
Loading