include another loopback project - node.js

I am trying to setup a project workflow in loopback which utilizes 2 different projects which include a base project.
Here is what I want to do:
loopback-project-1
|__loopback-project-2
|__loopback-project-3
So the idea would be to have all my basic tasks like authentication and authorization in loopback-project-1 and then include that in loopback-project-2 and loopback-project-3 to save me from re-creating that logic in the other projects. In other words, I need some way to share models across multiple loopback applications without having to duplicate code.
I tried creating a bootscript to try to load the other application as express middleware but that only seems to expose the REST API; NOT the models.
Here is my bootscript:
var boot = require('loopback-boot');
module.exports = function(app) {
app.use('/base', require('../../../loopback-project-1/server/server'));
boot(app, '../../../loopback-project-1/server/server', function(err) {
if (err) throw err;
});
};
Note: This bootscript would be included in loopback-project-2 and loopback-project-3.
My end goal is to be able to use loopback as the primary development stack for a multi-application architecture with a heavy focus on code re-use. The idea would be to include loopback-project-1 into other projects which would automatically include base models as well as any base functionality which resides in loopback-project-1; such as authentication / authorization.
Let me know how this can be accomplished.
Thanks

Related

Socket.io + REST API + REACT - is it better to separate socket.io from REST API

My question could be flagged as "opinion based" but I am wondering which approach is the best for my application as I am able to do it in both ways.
I am building chat application in which users and conversations are saved in MongoDB. I will have my react application consuming API/APIs. The question is - is it better to have REST API and Socket.io applications running separate? For example:
Have REST API running on port 3005
Have Socket.io running on port 3006
React Application consuming these 2 separately and basically they will not know about each other. My endpoints in REST API endpoints and socket.io will be invoked only in front-end.
On the other hand, I can have my socket.io application and REST API working together in 1 big application. I think it is possible to make it working without problems.
To sum up, at first glance I would take the first approach - more cleaner and easy to maintain. But I would like to hear other opinions or if somebody had a similar project. Usually how the things are made in this kind of projects when you have socket.io and REST API?
I would check the pros and cons for both scenario. For example code and resource reusability is better if you have a single application and you don't have to care about which versions are compatible with each other. On the other hand one error can kill both applications, so from security perspective it is better to have separate applications. I think the decision depends on what pros and cons are important to you.
you can make a separate file for socket.io logic like this:
// socket.mjs file
import { Server } from "socket.io"
let io = new Server()
const socketApi = {
io: io
}
io.on('connection',(socket)=>{
console.log('client connected:', socket.id)
socket.join('modbus-room')
socket.on('app-server', data=>{
console.log('**************')
console.log(data)
io.to('modbus-room').emit('modbus-client', data)
})
socket.on('disconnect',(reason)=>{
console.log(reason)
})
})
export default socketApi
and add it to your project like this:
// index.js or main file
//...
import socketApi from "../socket.mjs";
//...
//
/**
* Create HTTP server.
*/
const server = http.createServer(app);
socketApi.io.attach(server);
//

why is so differult between the app generated by fastify-cli and the example in the documentation?

where is the start.js in the project which is generated by fastify-cli ?
i think its big different between the getting start example and the app generated by fastify-cli?
should i write the start function like this in the project created by fastify-cli?
const start = async () => {
try {
await sequelize.sync({})
app.log.info('database sync correctly')
await app.listen(PORT, '0.0.0.0')
app.swagger()
} catch (err) {
app.log.error(err)
process.exit(1)
}
}
start()
there are just a app.js in the project generated by fastify-cli.what a different!
where is the start.js in the project which is generated by fastify-cli ?
There is not, it is replaced by the CLI utility fastify your-file.js in the package.json (like mocha, jest etc.. does to run tests)
Usually the starter file is always the same, so it has been integrated in the cli and you can use the args to set the PORT or to reload the server automatically when you edit one file.
i think its big different between the getting start example and the app generated by fastify-cli?
The docs teach all you need to know about the framework, the plugins and utility around it want to ease the developer experience.. like manage a mongodb-connectio: it is one line with the official plugin.
should i write the start function like this in the project created by fastify-cli?
If you use fastify my-file.js you don't need it.
After some experience you will understand when you need the fastify-cli or not.
I think the cli is useful in the most use cases and it suggests good ways to implement configurations loading and encapsulation.
You won't need it for special use cases that need to run some async operation before the server is created

session management using core node.js without express.js

How to handle/create middleware for server side session management in a core node.js /non express.js project. I can find modules for express based project but not for core node.js. Please suggest me any modules or middleware for non express.js project.
Session management can be implemented via database (MySQL, MongoDB, Redis etc.) or some local cache.
The main logic behind sessions - is object with data.
So you can provide user on first interaction with some random id, like uuid.
And save it to some module, which looks like this:
class OwnSession(){
constructor(){
this.sessions = {};
}
getUser(sessionId){
return this.sessions[sessionId];
}
setUser(sessionId, userData){
if(this.sessions[sessionId]){
Object.assign(this.sessions[sessionId], userData);
return;
}
this.sessions[sessionId] = userData;
}
}
// We export here new OwnSession() to keep singleton across your project.
module.exports = new OwnSession();
And then, in any module you require OwnSession and call the method.

How to separate express server code from Express business logic code?

All the Node.js tutorials that I have followed have put everything in one file. It includes importing of libraries, routing, database connecting and starting of the server, by say, express.js:
var app = require('express');
app.get('/somePath', blah blah);
app.listen(...);
Now, I have 4 node servers behind an Nginx load balancer. It then becomes very difficult to have the source code updated on all the four servers.
Is there a way to keep the source code out of the server creation code in such a way that I can deploy the source code on the servers as one package? The server creation code should not know anything about routing or database connections. It should only be listening to changes in a folder and the moment a new module meta file appears, it starts hosting that web application.
Much like how we deploy a Java code packaged as war by Maven and deployed to the webapp of Tomcat, because Tomcat instantiation is not part of the source code. In node.js it seems server is also part of the source code.
For now, the packaging is not my concern. My concern is how to separate the logic and how do I point all my servers to one source code base?
Node.js or JavaScript for that matter doesn't have a concept like WAR. But what it does have is something similar. To achieve something WAR like, you would essentially bundle the code into one source file using something like webpack. However, this will probably not work with Node.js modules like http (Express uses `http since it likely calls or relies on native V8/C++ functions/libraries.
You could also use Docker and think of the Docker containers as WARs.
Here is what I figured out as a work around:
Keep the servers under a folder say, "server_clusters" and put different node servers there, namely: node1.js, node2.js, node3.js, node4.js, etc (I know, in the real world, the clusters would be different VMs or CPUs altogether but for now, I simply want to separate server creation logic from source code). These files would have this code snippet:
var constants = require('./prop');
var appBasePath = constants.APP_BASE_DIR;
var appFilePath = appBasePath + "/main";
var app = require(appFilePath);
//each server would have just different port number while everything else would remain constant
app.listen(8080, function (req, res) {
console.log("server started up");
});
Create a properties file that would have the path to the source code and export the object. That simple. This is what is used on line#1 in the above code
Create the source directory project wherever you want on the machine and just update its home directory in the constant file above. The source code directory can export one landing file that will provide the express app to the servers to start:
var express = require('express');
var app = express();
module.exports = app;
With this, there are multiple servers that are pointing to the same source code.
Hope this helps to those who are facing the same problem.
Other approaches are welcome.

Test environment in Node.js / Express application

I've just starting working with Node, and I've been following along with various tutorials.
I've created an Express app, and setup Mongoose and Jasmine.
How can I configure my specs so that I can:
create models, automatically clean them up after each spec
use a different database for creating test objects (say myapp_test)
do this in a way that is as DRY as possible, i.e. not creating a before / after block with the teardown for each describe block
?
I'll try to answer you.
Create models, automatically clean them up after each spec.
To do that I'll assume you use Mocha as the testing framework you can simply use the function beforeEach like this :
describe('POST /api/users', function() {
beforeEach(function(done) {
User.remove({}, function (err) {
if (err) throw err;
done();
});
});
});
Basicly what I'm doing here is cleanning up my database before each it but you can make it do anything you want.
Use a different database for creating test objects
Here, you should use the node process.env method to setting your env. Here is a article to understand a little how it works. Take a lot to GRUNT projects, it helps a lot with your workflow and the configurations stuff.
do this in a way that is as DRY as possible, i.e. not creating a
before / after block with the teardown for each describe block
I'm not sure I got what you want but take a look at the doc for the hooks before, after, beforeEach, afterEach. I think you will find what you want here.

Resources