samedi 21 août 2021

Am I using the Repository pattern correctly in NodeJS?

I use Sequelize to work with the database.
In my project, I encountered code duplication, and decided to study the repository design pattern, which will separate the work with the database and data output from the business logic. Having studied the information on the Internet, I decided to consolidate the material and check with more experienced programmers. I use the repository pattern correctly? controller/user.controller.js

const userService = require('../services/user.service');

exports.userCreate = async (req, res, next) => {
 try {
   const user = await userService.userCreate(req.body);
   return res.status(201).json(user);
 } catch (e) {
   return next(e);
 }
}

services/user.service.js

const ApiError = require('../utils/error');
const userRepo = require('../repositories/user.repository');

exports.userCreate = async (data) => {
  if (!data) throw ApiError.badRequest('Bad');

  const { login } = data;

  if (!login) throw ApiError.badRequest('Bad');
   
  const password = 'hash';
  const user = await userRepo.userCreate({login, password});
  
  return user;
}

repositories/user.repository.js

const User = require('../models/User');

exports.userCreate = async (data) => {
  const { login, passowrd } = data;
  const user = await User.create({login, password});
  
  return {
    login: user.login,
  }
}

models/User.js

const { sequelize, Sequelize } = require('../config/db');

const User = sequelize.define('users', {
 id: {
   type: Sequelize.INTEGER,
   autoIncrement: true,
   allowNull: false,
   primaryKey: true,
 },
 login: {
  type: Sequelize.STRING,
  allowNull: false,
 },
 password: {
  type: Sequelize.STRING,
  allowNull: false,
 }
});

module.exports = User;

Aucun commentaire:

Enregistrer un commentaire