Step 1: Install Node JS.
(By clicking the given link here)
(By clicking the given link here)
(For a complete download click here)
Note: Run the below command with Node.js command prompt in administrative mode.
Step 4: After installation completion, your MongoDB is ready to connect, so you can connect your MongoDB just like the below image.
Step 5: Create a database with the name TestDB and a collection named employee as shown in
the below image.
(Import sample data of employees in your TestDB.employee collection.)
Sample Data of employee
(Please copy and paste the following sample data in your JSON file and import as shown in the above image.)
[
{
"jobTitleName":"Developer",
"firstName":"Ram",
"lastName":"Kumar",
"employeeCode":"E1",
"employeeId":"100"
},
{
"jobTitleName":"Developer",
"firstName":"Shyam",
"lastName":"Kumar",
"employeeCode":"E2",
"EmployeeId":"101"
},
{
"jobTitleName":"Program Directory",
"firstName":"Ashok",
"lastName":"Kumar",
"employeeCode":"E3",
"employeeId":"102"
}
]
By the above steps your MongoDB is ready for connection.
Image of the Node Project is shown below.
Step 6: Install Express
Web Server through VS Code Extension as shown below.
Details of the .js pages are given below.
(You can copy and paste the following code to get the result.)
Page 1: empCtrl.js
const _employeeService = require('../services/employeeService');
async function GetEmployee(req, res){
let empNo ="0";
if(req.params != {})
{
empNo = req.params.employeeNo;
}
let emp = [] ;
try {
emp = await _employeeService.GetEmployee(empNo);
} catch (error) {
console.log(error);
}
res.json(emp);
}
async function GetEmployeeById(req, res){
let empNo ="4122000";
if(req.params != {})
{
empNo = req.body;
}
let emp = [];
let obj = [];
try {
emp = await _employeeService.GetEmployeeById(empNo);
} catch (error) {
console.log(error);
}
res.json(emp);
}
module.exports = {
GetEmployee,
GetEmployeeById,
}
Page 2: Employee.js
const mongooes = require('mongoose');
const schemaEmployee = new mongooes.Schema({
EmployeeId: { type: String },
EmployeeCode: { type: String },
FirstName: { type: String },
LastName: { type: String },
JobTitleName: { type: String },
},
{
versionKey: false
}
);
module.exports = mongooes.model('Employee', schemaEmployee, 'employee');
Page 3: searchRoutes.js
const express = require("express");
const {GetEmployee,GetEmployeeById} = require("../controller/empCtrl")
const router = express.Router();
router.get("/getEmployee", async (req, res) => await GetEmployee(req, res));
router.post("/GetEmployeeById", async (req, res) => await GetEmployeeById(req, res));
module. Exports = router;
Page 4: employeeService.js
const connect = require("../db");
const Employee = require("../models/Employee");
async function GetEmployee()
{
// await connect();
let emp = [];
try {
emp = await Employee.find({},{_id:0}).lean();
} catch (error) {
console.log(error);
}
return await emp;
}
async function GetEmployeeByNo(EmployeeNo)
{
//await connect();
let emp = [];
try {
emp = await Employee.find({EmployeeNo: EmployeeNo}).lean();
} catch (error) {
console.log(error);
}
return await emp;
}
module.exports = {
GetEmployee,
GetEmployeeByNo,
}
Page 5: app.js
const express = require("express");
const app = express();
const BodyParser = require("body-parser");
const cors = require('cors');
const router = require("./routes/searchRoutes");
app.use(express.json());
// parse application/json
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.use('/api/',router);
// Handling Errors
app.use((err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.message = err.message || "Internal Server Error";
res.status(err.statusCode).json({
message: err.message,
});
});
module. Exports = app;
Page 6: db.js
const mongoose = require('mongoose');
const appConfig = require('../config');
///import promiseRetry from 'promise-retry';
let timer = 0;
const options = {
reconnectTries: 60,
reconnectInterval: 1000,
poolSize: 10,
bufferMaxEntries: 0, // If not connected, return errors immediately rather than waiting for reconnect
user: appConfig.db.user,
pass: appConfig.db.pass,
useCreateIndex: true,
useNewUrlParser: true,
};
mongoose.connection.on('connected', function (ref) {
console.log(new Date().toLocaleString(), `mongo connected to ${appConfig.db.url}`);
clearTimeout(timer);
});
mongoose.connection.on('error', function (err) {
console.error(new Date().toLocaleString(), String(err));
reconnectMongo(err);
});
mongoose.connection.on('disconnected', function () {
console.error(new Date().toLocaleString(), 'mongo server is disconnected');
reconnectMongo();
});
mongoose.connection.on('connecting', function () {
console.log(new Date().toLocaleString(), 'connecting mongo server...');
});
function reconnectMongo(err) {
if (err && err.message && err.message.match(/failed to connect to server .* on first connect/)) {
timer = setTimeout(function () {
console.log(new Date().toLocaleString(), 'Retrying first connect...');
mongoose.connect(appConfig.db.url, options).catch(err => {
console.log(new Date().toLocaleString(), String(err));
});
// Why the empty catch?
// Well, errors thrown by db.open() will also be passed to .on('error'),
// so we can handle them there, no need to log anything in the catch here.
// But we still need this empty catch to avoid unhandled rejections.
}, 20 * 1000);
} else {
// Some other error occurred. Log it.
console.error(new Date(), String(err + ''));
}
}
const connect = () => {
return mongoose.connect(appConfig.db.url, options).catch();
};
module.exports = connect;
Page 7: Server.js
const app = require("./app");
const connect = require("./db");
connect();
app.set("port", 8080);
app.get("/", (req,res)=>{
res.send("Welcome to hotels search apis!!!");
})
app.listen(app.get("port"), () => {
console.log(`Express hotel search server started and running on port ${app.get("port")}!`);
});
Page 8: Config.js
module.exports = {
rootPath: __dirname,
//SavefilePath: "\\files\\empFileSave.json",
//SchedInfoFilePath:"\\files\\empInfoSave.json",
db:
{ // It's case-sensitive, Database name must match with mongoDB DB name.
url: 'mongodb://localhost:27017/TestDB',
user: '',
pass: ''
}
}
Page 9: package.json
{
"name": "test-api-node",
"version": "0.0.1",
"description": "Test-API",
"main": "src/app.js",
"scripts": {
"start": "nodemon src/server.js"
},
"author": "abc",
"license": "ab",
"dependencies": {
"-": "0.0.1",
"axios": "^0.25.0",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.3",
"express-validator": "^6.14.0",
"g": "^2.0.1",
"moment": "^2.29.1",
"mongoose": "^5.13.14",
"node-cache": "^5.1.2",
"nodemon": "^2.0.15"
}
}
Page 10: webpack.config.js
module.exports = {
entry: {
nodeJsService: './src/server.js'
},
target: 'node',
output: {
path: __dirname + '/build',
filename: '[name].js',
chunkFilename: "[id].bundle.js"
},
externals: {
},
optimization: {
minimize: false,
}
};
Step 7: Open a new terminal to execute the service from the given code.
(Details are shown in the below image.)
npm start
Note: To execute the above command the marked ("start":"nodemon src/server.js") setting in package.json is mendetory. Result:
http://localhost:8080/api/getemployee
No comments:
Post a Comment