V
V
vladislav31012021-08-21 23:08:49
Node.js
vladislav3101, 2021-08-21 23:08:49

Is it correct to use such code (logic) in the repository pattern?

I'm just studying this pattern, and as I understand it, the repository does not have any business logic, it just takes and gives data.
Somewhere they wrote that it is not necessary to come up with solutions in advance, but write upon the fact of their need. That is, I need to execute a request in the service to search for a user by login and phone, which means I create the getWithPhoneAndLogin function (well, something like that), but when there are a lot of requests and with larger criteria, all these small functions lose their meaning.
I thought, what if I make a universal function for searching by criteria, if a column is suddenly added, I will change only 1 function and it will expand its capabilities. And so, did I do it right or is it bad and in the future there may be problems or is it more logical to implement it differently?
UserRepository.js:

const { User } = require('../models'); // Sequelize schema model

exports.findOne = async ({id, phone, email, login}) {
  const columns = [];
  if (id) {
     columns.push({id});
  }

  if (phone) {
    columns.push({phone});
  }

  if (email) {
    columns.push({email});
  }

  if (login) {
    columns.push({login});
  }

  const user = await User.findOne({where: {
    $or: columns,
  }})

 return user;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2021-08-21
@notiv-nt

not?

exports.findOne = async (columnsObject) => {
  const columns = [];

  Object.entries(columnsObject).forEach(([key, value]) => {
    columns.push({ [key]: value });
  });

  const user = await User.findOne({
    where: {
      $or: columns,
    },
  });

  return user;
};

In general, a repository is an abstraction over data, in fact, just a set of functions for accessing and manipulating data.

V
vladislav3101, 2021-11-27
@vladislav3101

And so, having studied this pattern a little "deeper", and how Mikhail painted it for me. It is necessary to transfer this logic to the service, and the repository, in turn, will already accept the finished object with all the correct criteria. And of course, the name of the findOne method is considered incorrect for the repository. IMHO.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question