Plan
- Part 1 : introduction
- Part 2 : Implementation of server side
- Part 3 : implementation of client side
Introduction
In this chapter we will implement the Rest server application by usingnodejs
and express.js
framework.the server will be an intermediary between client and DataBase, it will accept the HTTP requests sent by client, processes them , and return a Rest response to client (JSON or Text data).
Using the code
I) Description of requests can be sent by client
the aim of our application is to ensure the implementation of CRUD operations , and following this logic our services will be developed.1) getPersons
: get all available persons in database .- Input parameters :
- Output parameters
1) addPerson
: create a new person in database .- Input parameters :
- Output parameters
1) updatePerson
: create a new person in dataBase .- Input parameters :
_id
. this argument is in json format.- Output parameters
1) removePerson
: remove an existing person identified by _id
from database.- Input parameters :
- Output parameters
II) Server implementation
1) include the requirement modules
var mongodb = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/db';
var express = require('express');
var app = express();
to fix the issue of :
No 'Access-Control- Allow-Origin',
i add the following middleware to my NodeJS/Express app : app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
next();
});
var server = require('http').createServer(app);
var io = require('C:\\Users\\onasri\\AppData\\Roaming\\npm\\node_modules\\socket.io')(server);
io = io.listen(server, {log:false, origins:'*:*'});
2) implement crud methods by using Mongodb client :
//insert a new person
var insertPerson = function(db, obj, callback) {
db.collection('persons').insertOne( obj, function(err, result) {
assert.equal(err, null);
console.log("Inserted a new person into the persons collection.");
callback();
});
};
//get all persons
var findPersons = function(db, callback) {
var cursor = db.collection('persons').find();
cursor.toArray(function(err, items) {
console.log(items);
callback(items);
});
};
//update an existing person in persons collection
var updatePersons = function(db, arg, callback) {
var obj = JSON.parse(arg);
var key = obj["_id"];
db.collection('persons').updateOne(
{"_id": new mongodb.ObjectID(""+key)},
{
$set: { "firstname": obj.firstname, "lastname": obj.lastname,
"adress":{"zipcode": obj.adress.zipcode, "country": obj.adress.country}}
}, function(err, results) {
console.log(results);
callback();
});
};
//remove existing person from persons collection
var removePersons = function(db, key, callback) {
db.collection('persons').deleteMany(
{ "_id": new mongodb.ObjectID(key)},
function(err, results) {
console.log(results);
callback();
}
);
};
3) implement a rest services
//RESTFUL methods
app.get('/getPersons', function (req, res) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findPersons(db, function(data){ db.close(); res.end(JSON.stringify(data)); });
});
});
app.get('/addPerson', function (req, res) {
MongoClient.connect(url, function(err, db) {
//to process other instructions we check if err != null
assert.equal(null, err);
//get parameter from url request
var obj = req.query.obj;
insertPerson(db, JSON.parse(obj), function(){
db.close();
res.end("true");
});
});
});
app.get('/updatePerson', function (req, res) {
MongoClient.connect(url, function(err, db) {
//to process other instructions we check if err != null
assert.equal(null, err);
//get parameter from url request
var obj = req.query.obj;
updatePersons(db, obj, function(){
db.close();
res.end("true");
});
});
});
app.get('/removePerson', function (req, res) {
MongoClient.connect(url, function(err, db) {
//to process other instructions we check if no error occurred
assert.equal(null, err);
//get id parameter from url request
var key = req.query.id;
removePersons(db, key, function(){
db.close();
res.end("true");
});
});
});
4) Extra code
the below code allow to extract from a json file a list of person to populate your database.
- person.json file :
[
{"firstname":"Nasri 0","lastname":"Omar 1","adress":{"zipcode":1,"country":"France"}},
{"firstname":"Nasri 1","lastname":"Omar 2","adress":{"zipcode":2,"country":"France"}},
{"firstname":"Nasri 2","lastname":"Omar 3","adress":{"zipcode":3,"country":"France"}}
]
- parsing and populate the database using an existing data
var fs = require("fs");
//populate the dataBase in first time
fs.readFile( "persons.json", 'utf8', function (err, data) {
persons = JSON.parse( data );
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
//purge the database by removing all document
db.collection('persons').remove({})
db.collection('persons').drop();
//create a new collection and insert data
db.collection('persons').insert( persons, function(err, result) {
console.log( result );
assert.equal(err, null);
console.log("Inserted many documents into persons collection.");
db.close();
});
});
});
5) create our server
//create our server that listening at 127.0.0.1:8081
server.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
6) start server
open nodejs command prompt and write the following code :
node CRUDnode.js
Conclusion
You can find the source code of CRUD node.js in attached file.
After we finished the implmentation of Server side by definining our Restful services, we can begin the coding of client side.
No comments:
Post a Comment