How to implement `jwt` using express js in mvc pattern? - node.js

I have gone through this link. How can I implement this in mvc pattern?
This is my file structure
config
|----mongo.js //connection to mongoose
|----routes.js //all routes of all controllers
controllers
|----controller.js //all controller files
models
|----model.js //all models nothing but schemas of different collections
package.json
server.js
How to implement jwt in the above pattern so that it can be applied to all routes. Please help me out.

Related

Using mongoose.model without schema param

I'm working through this Node ToDoList App API tutorial. It has one model, one controller and one routes file:
https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd
Repo:
https://github.com/generalgmt/RESTfulAPITutorial
In the model, we use mongoose to define TaskSchema and export mongoose.model('Tasks', TaskSchema);
In the controller, we create a Task var, set equal to mongoose.model('Tasks', TaskSchema); and use it to define several controller methods.
The server.js requires Task from the model, but never seems to use it for anything. The server also requires the routes file, which in turn require the controller, but I can'a see how they ever interact with the model.
How does the rest of the app know about the model? How does the controller know the schema for Task? Is this all mongoose magic?
The Task schema is being called in the controller in line #4 https://github.com/generalgmt/RESTfulAPITutorial/blob/master/api/controllers/todoListController.js#L4
It does seem like the model being required in server.js is not used.
Server.js or routes don't need to interact with the schema, as all the methods required to interact with the schema are required in the Task constructor. The controller knows about the Task schema because it is being required in the controller.

How to separate controller layer from server.ts in node.js

I am using node.js with express for rest api and i have main file "server.ts" and i can write api routes in server.ts. But i wanna separate controller layer from server.ts even different controllers for their purpose. I have searched on google and found [link][1] for it.
[1]: http://bigspaceship.github.io/blog/2014/05/14/how-to-create-a-rest-api-with-node-dot-js/#toc_17 but i need this answer in typescript.

Where should I do the core logic code in express js?

I am using express.js for my website. I have created the directory structure using 'express-generator'. It contains 'views' folder to render views. It also has 'routes' folder for routing purpose. Now my question is where should I define or do the core logic code?
For organization purposes, I use /controllers for my, well, controllers (which I believe is what you mean). Express really doesn't care where you put your code, just as long as you correctly use require('./path/to/whatever/directoryname/you/choose/filename') in your routes and views and module.exports = controllerToExpose; in your controllers.

JavaScript Requires and Exports in Node.JS

I am writing a Node.JS REST API using Express, and I was a little confused about the require() and exports statements in Node.JS.
For instance, let's say I am writing a simple app wherein app.js contains the basic app.get statements, routes.js contains the functions passed as a callback to those app.get statements and events.js contains the Mongoose Schemas and Models.
Now, if routes.js requires events.js, can I call Model.find() and functions like those in routes.js and if yes, what exports will I have to make from events.js?
No need to export anything from model. Just require it.
In routes.js, you can access your model using mongoose.model('Schema')
routes.js
require('./events.js')
var mongoose = require('mongoose')
, Model = mongoose.model('myModel')

Organising folder structure and database queries with nodejs, express, mongoose using an MVC pattern

I am new to nodejs as well as mvc patterns. I am trying to create an app that utilises express, mongoose, ejs, passport. I am unsure as to where to place my database queries. At the moment I have started to add them into the controllers/routes.js file. Here is the approximate folder structure I have created so far:
|-- config
-- database.js // Exports just the db url
-- passport.js // Exports Passport local auth strategies (includes db connections)
|-- controllers
-- routes.js // Routes
|-- models
-- user.js // Exports mongoose user schema
|-- public
|-- views
-- home.ejs // Home ejs page
-- signup.ejs // Sign up page
-- user.ejs // User profile page
app.js // Express configure and server start etc...
I have followed a passport tutorial but the only db connections there exist in the config/passport.js file. At the moment I have placed a connection in the routes.js file but from what I have read these should go in the models folder. This is the code I have in my routes.js file:
//controllers/routes.js
//USER PROFILE ROUTE
app.get('/:user', function(req, res) {
var userRoute = req.params.user;
checkUserRoute(userRoute, res)
});
function checkUserRoute(userRoute, res){
var User = require('../models/user');
User.findOne({ 'local.email' : userRoute }, function(err, user) {
if (err){
return done(err);
}
if (user) {
res.render('user.ejs', { title: userRoute, message: '' });
} else {
res.send(404);
}
});
}
My (beginners) understanding of MVC is that it would go in the models folder but then why in the tutorial I followed for Passport are the db connections in the the config folder?
This is the folder structure of the tutorial I used for the passport authentication part of my app:
http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local#application-structure
Even the default express app install is confusing. The default express app has a folder called routes but then it places app.get code in the app.js file which sits in the root folder not in the routes(controllers) folder.
Is this right or wrong to place the db connection there in my controllers/routes.js file? If it is wrong where should I place it and how should I call the function which accesses the mongo database?
Is the mongoose user schema code in the correct place?
Should the config/passport.js file contain mongoose db connections?
1. Should the config/passport.js file contain mongoose db connections?
You can put your mongoose db connections in a separate file called db.js, then import or require that file in passport.js. So your config folder could look like this
/config
/db.js
/passport.js
2. Is the mongoose user schema code in the correct place?
Yes, but you should capitalize the first letter of your model files to follow convention User.js.
3. Is this right or wrong to place the db connection there in my controllers/routes.js file? If it is wrong where should I place it and how should I call the function which accesses the mongo database?
You are not placing your db connection in the routes.js file. Your connection to your db should go in your config folder config/db.js. You would then export the file module.exports = db; and require it var db = require('/config/db.js'); in your controllers/routes.js file. Now you will have access to your db connection. You could now run Mongo queries and methods in your controllers files, which is where your app's logic should go.
Your Model only speaks to your Controller, not the View. Similarly, your View only speaks to your Controller. Keeping your code organized this way will make your life much easier when your app gets more complicated.
I would add another 'services' folder and add some kind of db-accessor service in there.
You can still place all your db configs in your config file and let the service take it from there.
Another nice thing you can do is define the passport mongo-strategy in a separate module
so that it will also be replaceable.
If you want to get up and running more quickly with node, express, and mongo, take a look at sails.js. It's the most popular node.js MVC framework nowadays, and will help you spin up this type of project more easily.

Resources