Skip to content Skip to sidebar Skip to footer

Setup An Authentication Middleware To Reduce Duplicate Code In Express.js

As the title suggests, I want to reduce duplicate authorization code for each new route I call. My problem is exactly the same as the user in this post, because apparently we downl

Solution 1:

In the answer you referenced, it appears that user installed and is using Sequelize to store an individual's user data. If you would like to utilize that approach, I would look into Sequelize. As you mentioned on the other thread, User is not defined. For the other question, the asker most likely set up a model called User.

In Sequelize, each model (like User) defines a table that has its own rows and columns. Each column represents a field that applies to an individual row of data. For example, for a User model, one user may have a username, an email, and a password. You would specify what data types these columns should be and any other necessary information for each column of the Sequelize model definition. Each row represents one data-entry, or in this case, one user. I had previously built a sample web app that maps students to specific classes; below I have copied the Sequelize model definition I wrote for that project. It's quite simple and I would recommend watching some YouTube tutorials or checking out the Sequelize documentation at sequelize.org if this library is foreign to you.

Student.js

'use strict';

const Sequelize = require('sequelize');
const db = require('./_db');

const Student = db.define('student', {
    name: {
        type: Sequelize.STRING,
        allowNull: false,
        validate: {
            notEmpty: true
        }
    },
    phase: {
        type: Sequelize.STRING,
        allowNull: true,
        validate: {
            isIn: [['junior', 'senior', null]]
        }
    }
});

Student.findByPhase = async function(phase) {
    const students = await Student.findAll({
        where: {
            phase: phase
        }
    })
    return students
}

module.exports = Student;

It may also help to check out PostgreSQL or SQL in general as well to understand the basic framework that Sequelize lies on top of.


Post a Comment for "Setup An Authentication Middleware To Reduce Duplicate Code In Express.js"