Best Practice to create REST APIs using node.js - node.js

I am from .Net and C# background and I am new to Node.js. I am working on a project, which is mix of MongoDB and Node.JS.
In MongoDB, data from various tools is stored in different different collections. I have to create multiple REST APIs using Node.JS for CRUD operation on that data, these APIs will be called from React.JS application.
I want to keep APIs into separate files for seperate tool and then calling including all files into app.js file.
Please help me with best approach.
For POC purpose, I created a node.js application, where I created app.js file and written all my code for GET|POST|DELETE APIs. This is working fine.
var _expressPackage = require("express");
var _bodyParserPackage = require("body-parser");
var _sqlPackage = require("mssql");
var app = _expressPackage();
var cors = require("cors");
var auth = require('basic-auth');
var fs = require('fs');
const nodeMailer = require('nodemailer');
//Lets set up our local server now.
var server = app.listen(process.env.PORT || 4000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.get("/StudentList", function(_req ,_res){
console.log("Inside StudentList");
var Sqlquery = "select * from tbl_Host where HostId='1'";
GetQueryToExecuteInDatabase(_req,_res, Sqlquery,function(err,data){
console.log(data);
});
});

Don't know exactly what your app intends to do, but usually if you are not serving webpages and your API is not too complex, there is no need to use express. You can build a simple server natively in NodeJS to serve data.
Additionally, if your app has many routes (or is likely to in the future), it is a good idea to put helper functions like GetQueryToExecuteInDatabase() in a separate file outside of app.js such as utils.js.
Based on what I have understood about what you want to do, your file structure should look something like this:
data (db related files)
services (contains one file per api service)
app.js
utils.js
Hope this helps.

Related

Networking websockets on node.js servers

So I've been coding in web design for two weeks now and I've devolved the core for my io game on node.js just by using localhost:3000 now I'm trying to implement what I have so far into an actual web-server. It's one heck of a learning curve, so say I set up a virtual-machine in Google Cloud Platforms running node.js, socket.io what do I even set my ports too?
This is my Code currently server side:
var express = require('express'); //adds express library
var app = express();
var server = app.listen(3000); //listens on port 3000
app.use(express.static('public')); //sends the public(client data)
console.log("Server Has Started");
var socket = require('socket.io'); //starts socket
var io = socket(server);
This is my Code currently client side:
var socket = io.connect("http://localhost:3000")
my website is gowar.io and it currently resides as a static file in googles "bucket". How do I hook up my websockets with something like a virtual machine?
Typically, cloud ecosystems will give you an endpoint for your storage or allow you to configure one.
Skim through Google's Docs about WebSockets to learn more about their recommended implementation of WebSockets.

How to embed multiple instances of node-red in node app

Node-red documentation here gives info on how to embed a single node-red app inside a nodejs app - http://nodered.org/docs/embedding
We wanted our site's users to have their own node-red's on different ports for some custom programming. Is it possible to embed multiple node-red apps in a nodejs applicaiton?
I tried repeating same steps for embedding by changing settings of each call with different port but only one time it is created. First time, a node-red instance is created based on settings. Next time we call, we get port in use. I assume this has something to do with node require doing caching and all... Any workaround for this issue?
If you're interested I created a fork of the node-red project allowing this feature.
this is how you would initiate it:
var http = require('http');
var express = require("express");
var RED = require("node-red")();
var RED2 = require("node-red")();
// Create an Express app
var app = express();
// Add a simple route for static content served from 'public'
app.use("/",express.static("public"));
// Create a server
var server = http.createServer(app);
// Create the settings object - see default settings.js file for other options
var settings = {
httpAdminRoot:"/red1",
httpNodeRoot: "/api",
userDir:"./hhh",
functionGlobalContext: { } // enables global context
};
// Initialise the runtime with a server and settings
RED.init(server,settings);
console.log(RED2.settings === RED.settings, 888, RED2.settings.userSettings);
// Serve the editor UI from /red
app.use(settings.httpAdminRoot,RED.httpAdmin);
// Serve the http nodes UI from /api
app.use(settings.httpNodeRoot,RED.httpNode);
server.listen(8005);
// Start the runtime
RED.start();
var app2 = express();
app2.use("/",express.static("public"));
var server2 = http.createServer(app2);
var settings2 = {
httpAdminRoot:"/red2",
httpNodeRoot: "/api",
userDir:"./hhhh",
functionGlobalContext: { }
};
RED2.init(server2,settings2);
app2.use(settings2.httpAdminRoot,RED2.httpAdmin);
app2.use(settings2.httpNodeRoot,RED2.httpNode);
RED2.start();
server2.listen(8006);
console.log(RED.settings.httpAdminRoot);
console.log(RED2.settings.httpAdminRoot);
console.log(RED2.settings === RED.settings);
also, works on the same port. but make sure to use different paths is so.
https://github.com/aryeharmon/node-red
No, currently Node-RED has no multi-user capabilities and no way to instantiate multiple instances in one process.
You'll have to run separate instances of the application for each user. Have a look at something like FRED for an example of this. This runs individual instances and proxies them to make the integration look like it's all on the same port/domain

Node.JS express server creation methods difference

I have recently inherited a project of a Node.JS and Express based API, and I have noticed express server creation is as such (simplified version):
// http is required.
var http = require('http');
var express = require('express');
var app = express();
// Note http is used to create server, and app is used as param:
http.createServer(app).listen(3000, function (request, response) {
console.log('listening on port 3000');
});
Everything works as expected of course.
I have been trying to figure out what exactly is happening behind the scenes here, mostly in comparison to the method in Express API, which shows:
// http is not required.
var express = require('express');
var app = express();
// Note Express is used to create the server:
var server = app.listen(3000, function () {
console.log('listening on port 3000');
})
Note the difference in server creation using http, and using Express directly.
Is there any benefit in using a specific one of the two method? What is the actual difference between the two?
Micro-optimization-wise, is it preferred to avoid requiring 'http', which is probably required by express anyway?
Thanks from ahead!
Both are more or less functionally equivalent, in the second example the express constructor returns a new object which effectively wraps up the http.createServer call internally (i.e. when you call app.listen).
If you are going to use express then you should use it's recommended APIs, the first approach is considered outdated.

Heroku Postgres Connecting in Node.js

I want to use a heroku database (already deployed in heroku) for my AngularJS application created using Yeoman. I want to persist my data that is currently an array of JSON objects that goes away when I refresh the page. I am trying to follow Heroku's guide for Node.js here (https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js) but it is very shot, no examples, and I am fairly new to servers/databases. I have a 'web.js' file and the Procfile int my root directories for Node.js and heroku to read that file. I have the "dependencies" already set but I am not sure what is happening in this code below that heroku provides
var pg = require('pg');
pg.connect(process.env.DATABASE_URL, function(err, client) {
var query = client.query('SELECT * FROM your_table');
query.on('row', function(row) {
console.log(JSON.stringify(row));
});
});
First: Where do I put this code?
Second: What is happening here?
and Third: How do I use it to upload my data that is currently an array of JSON objects that I
hardcode into my code into the heroku database?
My web.js file
var gzippo = require('gzippo');
var express = require('express');
var app = express();
app.use(express.logger('dev'));
app.use(gzippo.staticGzip("" + MyApp + "/dist"));
app.listen(process.env.PORT || 9000);
My Procfile
web: node web.js
That code goes in your web.js file.
I'm pretty sure it's accessing your database and setting the results to the variable query so you can access the data.
I think want you want for pushing the data is to look here, particularly at pg:push.

Referencing NodeJS MongoDB connection from AngularJS

I'm trying to set up a small development environment consisting of a node.js http server, a mongodb database and frontend in angular.js. For development purposes I've created an account with MongoHQ and can reference my db using a URL.
The issue I'm faced with is that I can easily connect to my db from my Angular code but then my connection info is exposed through my http server.
So what I would like to be able to is to create my connection in my NodeJS server.js file and reference it from eg. my AngularJS app.js file. Is that possible and if so how?
Thanks in advance
Try using express and mongoose.
Server side code
var express = require('express');
var app = express();
//start server with port of choice here
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Foo=mongoose.model('foo');
//foo is a model. Check mongoose documentation from collections and schemas
app.get('/hello', function(req, res){
//get data from mongo using mongoose
foo.find({},function(err,docs){
//do stuff here
res.send(docs)
})
});
Front end code
$http.get('/hello').success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
//data is the data from mongodb
})
Follow this tutorial to get an idea
There is a stack called MEAN Stack. See if it fits your needs. Very easy to set up and develop.

Resources