How to access a configuration object throughout the entire application? - javascript

I have created a simple Node.js application, throughout which I use static route paths. So I need to know how to access an object without requesting in every route in my application.
Current method =>
routeLink.js
var routesMap = [{
createUserRoute: '/create-user',
route2: '/user-profile',
// ...
}];
createUserRoute.js
var routLinks = require('./config/routeLink');
module.exports = function(router){
router.post('/', function(req, res){
// do the task
res.redirect(routLinks.createUserRoute);
});
}
Just like you see in this example, I have to
require('./config/routeLink')
without using this how to I access routesMap from all of the Routers?

You have two option if you don't want to require your config in each route file:
1/ make your config global in your whole application ( not recommended )
2/ use environment variables, take a look at dotenv

Related

Subroutes in Next Js

I´m new to next js, I have created a file called orders.js under pages directory, and I can access it correctly from localhost:3000/orders.
However, I want now to have a subroute, to access the order with id 1 (for example). So I have created a directory 'orders' inside the directory pages, and renamed order.js to index.js, after that, I have created another file inside the orders directory called id.js.
So my current structure is:
pages/
orders/
index.js
id.js
However I cannot access to localhost:3000/orders/1.
Using Nuxt js, this was trivial, how can I achieve the same with next.js ?
Thanks
This is also trivial with Nextjs, however, you're trying to achieve it the harder way.
Your first approach is correct. If you don't specify a route for your pages in the server.js file, Nextjs will automatically use them if the URL is correct (in this case orders leads to the orders.js page).
What you're looking for is to create a custom route. You can see the documentation for this here
I find the example in the documentation confusing, so I recommend using express instead. Here's an example for that. You can then see the express routes in the server.js file of the example.
Your route would end up looking something like this:
server.get('/orders/:id', (req, res) => {
return app.render(req, res, '/orders', req.query)
})
Where :id is a query param which you can then access in your getInitialProps inside your orders.js page.
You can check the express routing examples in the express documentation.
You can try using next-routes, dynamic routes for Next.js
And simply create a routes.js and add,
const routes = require('next-routes')
module.exports = routes()
.add('orders', '/orders/:id', 'orders/id')
// name, url, page folder
Or if you only want the server side routing,
server.get('/orders/:id', (req, res) => {
const actualPage = '/orders'
app.render(req, res, actualPage, req.query)
})
This might help you : https://nextjs.org/docs#dynamic-routing.
by adding [ ] to a page it creates a dynamic route, in this case [orderid].js can be used to map multiple orders to a single page.
pages/
orders/
[id].js
use
pages/
orders/
[dynamic_subroute].js
now catch it with
const router = useRoute();
const { dynamic_subroute } = router.query;
Now, you can catch the value (any) dynamically from the url which is used instead of dynamic_subroute
like- if the url is pages/orders/1
then value of dynamic_subroute will be 1 in your page

What's considered a good way to share "global" variables inside a node module?

How can I easily refer to other directories in my module without explicitly relative paths (../../../lib..)?
I'm writing a node module and there are some global things I want to reuse in my module.
Most basically - I want to set the root path of the module as a 'global' so I can easily call other sources without using a lot of relative paths ../../ and things like that. It can cause messy code and it's easy to mistake or miss it if the project structure changes.
So I've seen a lot of options in that post and some other libraries for dealing with those kind of things (such as modules that give the root path - app-module-path, rootpath, rfr etc.) but they all refer to a base project/application and not to a module that's being used by others.
Setting a global is a bad idea, and I understood that an environment variable is also not such a good idea.
Is there a good practice for that thing? Maybe there's something I haven't found or heard of.
Here's an example of what I'm trying to avoid and what I'm looking for:
// avoid things like that:
// ./lib/something/forthat/doit.js
var config = require('../../../config/project/type1/config.js');
// ./config/project/type1/config.js
module.exports = {
msg: 'hi'
};
// find somethings like that:
// when the root path/require can be found in every location of the module
// and is relative to my app and not the app using my module.
// ./lib/something/forthat/doit.js
var config = require(rootPath + 'config/project/type1/config.js');
// OR
var config = rootRequire('config/project/type1/config.js');
// OR anything else
// ./config/project/type1/config.js
module.exports = {
msg: 'hi'
};
For getting the current directory path you can use the global variable __dirname any where in your nodejs project. Example : console.log(__dirname) write this into any file in your project and console would print the current directory path as string.
Or, You can use express-session module like;
var express = require('express');
var session = require('express-session');
var app = express();
app.use(session({myVar: 'abc'}));
app.get('/',function(req,res){
var sess = req.session;
console.log(sess);
});
First of all..... relative paths doesn't create confusion at all. rather you can call it messy (if you want) and it is considered to be the best practice. But I can understand you too. That you don't like very messy codes. So for this situation you should serve that part/peice of code as static content. Hence easily you can access it with giving a very login tailing path. But remember this way is an alternate to relative path serving.

var express = require('express'); var app = express(), What is express()?? is it a method or a constructor? Where does it come from

var express = require('express');
var app = express();
This is how we create an express application. But what is this 'express()'? Is it a method or a constructor? Where does it come from??
Is it a method or a constructor?
Neither; it's a function, although if you said "method" I don't think anyone would give you a hard time.
A method is a function attached to an object. In JavaScript, methods are just mostly functions that you reference via object properties. (Update: As of ES2015, if you use method syntax to create them, they're slightly more than that because they have access to super.)
A constructor, in JavaScript, is a function you call via the new operator. Even though other functions may create things, we don't typically call them "constructors" to avoid confusion. Sometimes they may be "creator" or "builder" functions.
Where does it come from?
ExpressJS is a NodeJS module; express is the name of the module, and also the name we typically give to the variable we use to refer to its main function in code such as what you quoted. NodeJS provides the require function, whose job is to load modules and give you access to their exports. (You don't have to call the variable express, you can do var foo = require('express'); and use foo instead, but convention is that you'd use the module's name, or if only using one part of a module, to use the name of that part as defined by the module's documentation.)
The default export of express is a bit unusual in that it's a function that also has properties on it that are also functions (methods). That's perfectly valid in JavaScript,¹ but fairly unusual in some other languages. That's why you can create an Application object via express(), but also use express.static(/*...*/) to set up serving static files.
¹ In fact, it's completely normal. Functions have a couple of standard methods by default: call, apply, and toString for instance.
You’ll use Node’s require function to use the express module. require is similar to keywords like import or include in other languages. require takes the name of a package as a string argument and returns a package. There’s nothing special about the object that’s returned—it’s often an object, but it could be a function or a string or a number.
var express = require('express');
=> Requires the Express module just as you require other modules and and puts it in a variable.
var app = express();
=> Calls the express function "express()" and puts new Express application inside the app variable (to start a new Express application).
It's something like you are creating an object of a class. Where "express()" is just like class and app is it's newly created object.
By looking the code of express below you are good to go what is really happening inside.
File 1: index.js
'use strict';
module.exports = require('./lib/express');
File 2 : lib/express.js
'use strict';
var EventEmitter = require('events').EventEmitter;
var mixin = require('merge-descriptors');
var proto = require('./application');
var Route = require('./router/route');
var Router = require('./router');
var req = require('./request');
var res = require('./response');
/**
* Expose `createApplication()`.
*/
exports = module.exports = createApplication;
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
app.init();
return app;
}
exports.application = proto;
exports.request = req;
exports.response = res;
exports.Route = Route;
exports.Router = Router;
});
How require works
When you call require('some_module') in node here is what happens:
if a file called some_module.js exists in the current folder node will load that, otherwise:
Node looks in the current folder for a node_modules folder with a some_module folder in it.
If it doesn't find it, it will go up one folder and repeat step 2
This cycle repeats until node reaches the root folder of the filesystem, at which point it will then check any global module folders (e.g. /usr/local/node_modules on Mac OS) and if it still doesn't find some_module it will throw an exception.
Ancient post. I think the original poster was confused about why the syntax to call the function exported by module express is
var app = express()
instead of
var app = express.express()
To clarify: require() function does not create a reference to that 'module'. There's no such thing as reference to a module. There's only reference to thing(s) exported by a module.
require('xxx.js'), where the .js extension can be omitted, returns whatever is exported by that xxx.js file. If that xxx.js file exports an object, require('xxx.js') returns an object; if a function is exported, require('xxx.js') returns a function; if a single string is exported, require('xxx.js') returns a string...
If you check source code of file express.js, you will see that it exports a single function. So in
var express = require('express')
The first express is assigned whatever is exported by module express, which in this case happens to be a single function. express is a function, not a reference to a module. Hence on second row you just invoke that function:
var app = express()
Hope this helps!
let me answer this question by an example.
create 2 javascript files.
play1.js and express.js
//express.js
function createApplication(){
var app = 'app';
return app;
}
module.exports = createApplication;
//keep in mind that we are not doing module.exports = {createApplication}
now import express.js in play1.js file
//play1.js
var express = require('./express);
var app = express();
// this will call createApplication function as app is referencing to it.
console.log(app); // "app"
Whenever you import a module like
const express = require('express')
express is a module with functions or objects or variables assigned to it .
take a look at /lib/express
you are able to access the function createApplication inside express module as express() because the function is assigned directly to the module like
exports = module.exports = createApplication;
function createApplication(){
var app = function(req, res, next) {
app.handle(req, res, next);
};
//other codes
}
so you are able to access the function createApplication just calling express() as function
now when you check out the other section of the express library, you can see a bunch of other objects attached to the exports special object as well.
/**
* Expose the prototypes.
*/
exports.application = proto;
exports.request = req;
exports.response = res;
/**
* Expose constructors.
*/
exports.Route = Route;
exports.Router = Router;
// other exports
these objects or function assigned to export special object can be accessed from the import section using express as an object.
express.{name}
express.Route
express.Router etc
In the end you are just exporting a bunch of methods or objects that are attached to the module.export special object inside express js file
to read more on module.export special object go here
1- var express = require('express');
first line require the express package .js file, und "require" it's only returnd what was exported in the js file with (module.exports).
so we have only pointer to this function .
2- var app = express();
in second line, we use 'app' as pleaceholder to receive the output from express() function, which is an object, we can use it in our code (by accessing his methods and properties like any other Class )
in other words, we use the 'app' Object, which which produced from 'express()' function, that we imported from 'express.js' file .
NOTE 1) and of course we can give any name instead of 'app' , but it's a good practice when you follow what the most developers use to name this packages, that make easier to understand your code specialty when you work in team.
NOTE 2) after ES6, we use 'const' instead of 'var' .
Simple what we wrote in node js when we require a modules for our application
const modue_need1=require('module_name');
const modue_need2=require('module_name2');
const modue_need3=require('module_name3');
const modue_need4=require('module_name4');
const modue_need....=require('module_name.....');
So for every module, we need to write such a big code, and time-consuming now to reduce these lengthy codes and time slice what we do? We need node js Framework like Express js
which will overcome these problems mean "write less, do more"
we just use this two-line and all the requirement(modules) about our app will be their in-app object which we can use whenever we need so do not need to call require for every module.
"write less, do more"
const express=require('express');
const app=express();
console.log(app);

NodeJS and Express - separate my controllers and models

I'm building my first Express app. It's a bit messy as my controllers and my models are all in the same place: the app.js file.
Is there a way that I can separate those?
Even artificially, by creating different files and then using some third party program to compile them into the app.js file.
First of all, you need to create your controllers and model folders.
You can use a module called express-load which can be used to autoload models, routes, schemas, configs, controllers, object maps... etc...
in your main file, mine is called app.js you load them right before start the server code line.. it should look like
//requires....
var load = require('express-load');
//your code
load('models')
.then('controllers')
.then('routes')
.into(app);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express listening on port "+ app.get('port'));
});
module.exports = app;
Then, your view folder you can create folders to keep your code organized, then subfolders, I created a folder called home, and inside of it my index view.
In my controllers folder I created a js file called home.js, and which will look for my index view:
module.exports = function(app){
var HomeController = {
index: function(req, res){
res.render('home/index');
}
};
return HomeController;
}
At last in your routes folder, you can set your application routes, each view needs to be specified in your controller. My file for routes its called home.js
module.exports = function(app){
var home = app.controllers.home;
app.get('/', home.index);
}
What I generally do it is to write a module which contains all the routes definition and load it in app.js e.g
require('./routes')(app);
My ./routes.js generally looks like this
module.exports = function (app) {
log.info('Loading express routes...');
/* registration */
app.post('/users', require('./routes/register-users')); // register user
app.post('/agents', require('./routes/register-agents')); // register agents
};
and I keep all the routes (.js) files inside a directory call routes
Hope it is what you are looking for.
Is there a way that I can separate those?
Yes, and you should separate them.
What most people do is declare the routes in the main app.js file and include separate files for the controllers (just like Rituparna described).
Those controllers files will in turn very likely include your model files via a require. For example.
In app.js
var blogRoutes = require('./routes/blogRoutes');
app.get('/api/blog/all', blogRoutes.all);
In routes\blogRoutes.js
var model = require('../models/blogModel');
var all = function(req, res) {
// your controller logic
// and very likely calls to your model
var m = model.blog(whatever);
res.send(m.something());
};
module.exports = {
all: all
}
In models\blogModel.js
var something = function() {
return "something";
};
module.exports = {
something: something
}
You can see a working version of this in this repo https://github.com/hectorcorrea/hectorcorrea.com
You should checkout the examples from the Express Github repo, there are multiple ways to do this (based on personal preference):
https://github.com/visionmedia/express/tree/master/examples/mvc
https://github.com/visionmedia/express/blob/master/examples/resource/app.js
https://github.com/visionmedia/express/tree/master/examples/route-separation
There are some examples here that may help you..
Route Separation: https://github.com/visionmedia/express/tree/master/examples/route-separation
MVP: https://github.com/visionmedia/express/tree/master/examples/mvc

How can I do my routing without having one long file of all the routes in nodejs?

Using this link as a reference https://github.com/visionmedia/express/tree/master/examples/route-separation to what "could be done"
I AM NOT USING EXPRESS. I AM USING THEM AS AN EXAMPLE.
I want to do something like this but "simpler" ...
How can I get away from declaring all my routes in one long, complex list all in one file? Can I define them by passing a router into my modules, and then including all the code in one directory ... ok, I'll suffer having one long document that only does "require" includes, like an index.js, for this one ~ at least that one my build scripts can rebuild for me, but preferably not in my primary file for every single route that I may add.
So for instance, they use this code:
// General
app.get('/', site.index);
// User
app.all('/users', user.list);
app.all('/user/:id/:op?', user.load);
app.get('/user/:id', user.view);
app.get('/user/:id/view', user.view);
app.get('/user/:id/edit', user.edit);
app.put('/user/:id/edit', user.update);
// Posts
app.get('/posts', post.list);
I want to avoid making a list like that in my app.js. I want instead to have each file know what the routes are for that file.
Here's what I'm wanting to do: (please don't critique the code, I'm making it very simple so I make sure that I am illustrating my code the way I want to do it)
//app.js
var router = require('./myRouter.js')
var includes = require('./routes/*.js').register(router)
// do some stuff here with an https server and start the server here
and
//./routes/user.js
var myRouter;
exports.register(router){
myRouter = router;
}
router.addRoute(/* here I do the magic associated with this route */)
Can I do it just that simply? What am I missing here?
I haven't written this code because I'm just ever so certain that I'm going about this the wrong way.
And if I am going to have to use something like an index.js in the /routes/ folder, can I use that same concept that I demonstrated I would like to use in my code of .register(router) appended so I can pass that information down recursively? Would that work?
I use an index.js file for this and use require("routes") which is a folder.
// app.js
route = require("./routes"),
...
route(app);
// routes/index.js
var index = require("./index-route"),
about = require("./about-route"),
posts = require("./posts-route");
module.exports = function(app) {
index(app);
about(app);
posts(app);
};
This works because if you require a folder it will load index.js by default.
If you have a lot of routes you might want to load them based on convention
var routes = [];
// read all files
fs.readdir("./", function(files) {
files.forEach(function(val) {
// require all non-index.js files.
if (val !== "index.js") {
routes.push(require(val));
}
});
});
module.exports = function(app) {
// for each route you required call it with app.
routes.forEach(val.bind(null, app));
}
This would load all .js files that are not "index.js", so any file in your /routes/ folder would be loaded and run when you route them.
Your solution looks vaguely like you wish to use the Visitor Patern, in which case I suggest you make ./roots/ require-able (see this question) and in index.js you include all the files you wish (as local's) and export a register module which calls the register module on each of the required files.
Or you could copy the code from the above answer directly into your main file.

Categories

Resources