123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- const ContactModel = require('../model/contact');
- const UserModel = require('../model/user');
- const ChatModel = require('../model/chat');
- const MessageModel = require('../model/message');
- const listContacts = async (req, res, next) => {
- try {
- const userId = req.user.id;
- const contacts = await ContactModel.getList({ owner: userId }, req.query);
- return res.json({
- status: 'success',
- code: 200,
- data: {
- ...contacts,
- },
- });
- } catch (e) {
- next(e);
- }
- };
- const getContactById = async (req, res, next) => {
- try {
- const id = req.params.id;
- const userId = req.user.id;
- const contact = await ContactModel.getById(id, userId);
- if (contact)
- return res.json({
- status: 'success',
- code: 200,
- data: {
- contact,
- },
- });
- return res.status(404).json({
- status: 'error',
- code: 404,
- data: 'Not Found',
- });
- } catch (e) {
- next(e);
- }
- };
- const addContact = async (req, res, next) => {
- try {
- const userId = req.user.id;
- const userNumber = req.user.number;
- const number = req.body.number;
- const user = await UserModel.findByNumber(number);
- const isExist = await ContactModel.getByField(number, userId);
- if (user && userNumber !== number && !isExist) {
- const { name, lastName, country, avatarUrl, color, _id } = user;
- const newContact = await ContactModel.add({
- companionId: _id,
- name,
- lastName,
- number,
- country,
- avatarUrl,
- color,
- owner: userId,
- });
- return res.status(201).json({
- status: 'success',
- code: 201,
- data: newContact,
- });
- }
- return res.status(404).json({
- status: 'error',
- code: 404,
- data: 'Not Found',
- });
- } catch (e) {
- next(e);
- }
- };
- const updateContact = async (req, res, next) => {
- try {
- const { id, _id, name, lastName, companionId } = req.body;
- const userId = req.user.id;
- await ContactModel.update(id, userId, { name, lastName });
- await ChatModel.update(_id, userId, { name, lastName });
- await MessageModel.updateOwnerMessages(
- { companionId, companionIdFlow: { $ne: userId }, owner: userId },
- { name, lastName }
- );
- return res.status(200).json({
- data: {},
- });
- } catch (e) {
- next(e);
- }
- };
- const removeContact = async (req, res, next) => {
- try {
- const id = req.params.id;
- const userId = req.user.id;
- const contact = await ContactModel.remove(id, userId);
- if (contact) {
- return res.json({
- status: 'success',
- code: 200,
- data: {
- contact,
- },
- });
- } else {
- return res.status(404).json({
- status: 'error',
- code: 404,
- data: 'Not Found',
- });
- }
- } catch (e) {
- next(e);
- }
- };
- module.exports = {
- listContacts,
- getContactById,
- addContact,
- removeContact,
- updateContact,
- };
|