123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- const ContactModel = require('../model/contact');
- const UserModel = require('../model/user');
- const ChatModel = require('../model/chat');
- const listContacts = async (req, res, next) => {
- try {
- const userId = req.user.id;
- const contacts = await ContactModel.getList(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 number = req.body.number;
- const user = await UserModel.findByNumber(number);
- const isExist = await ContactModel.getByField(number, userId);
- if (user && !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 } = req.body;
- const userId = req.user.id;
- const contact = await ContactModel.update(id, userId, { name, lastName });
- const chat = await ChatModel.update(_id, userId, { name, lastName });
- if (contact && chat) {
- return res.status(200).json({
- data: {},
- });
- } else {
- return res.status(404).json({
- status: 'error',
- code: 404,
- data: 'Not Found',
- });
- }
- } 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,
- };
|