ソースを参照

done chat model

unknown 3 年 前
コミット
1bff23d6dc

+ 2 - 0
app.js

@@ -5,6 +5,7 @@ const cors = require('cors');
 const helmet = require('helmet');
 const apiLimiter = require('./helpers/apiLimiter');
 
+const chatsRouter = require('./routes/chats');
 const contactsRouter = require('./routes/contacts');
 const userRoute = require('./routes/user');
 const app = express();
@@ -20,6 +21,7 @@ app.use(logger(formatsLogger));
 app.use(cors());
 app.use(express.json());
 
+app.use('/api/chats', apiLimiter, chatsRouter);
 app.use('/api/contacts', apiLimiter, contactsRouter);
 app.use('/api', apiLimiter, userRoute);
 

+ 81 - 0
controllers/chats.js

@@ -0,0 +1,81 @@
+const ChatModel = require('../model/chat');
+const UserModel = require('../model/user');
+
+const listChats = async (req, res, next) => {
+	try {
+		const userId = req.user.id;
+		const chats = await ChatModel.getList(userId, req.query);
+		return res.json({
+			status: 'success',
+			code: 200,
+			data: {
+				...chats,
+			},
+		});
+	} catch (e) {
+		next(e);
+	}
+};
+
+const startChat = async (req, res, next) => {
+	try {
+		const id = req.body.id;
+		const user = req.user;
+		const userId = user.id;
+		const companion = await UserModel.findById(id);
+		const isUser = await ChatModel.getByField(id, userId);
+		const isCompanion = await ChatModel.getByField(userId, id);
+		const { name, lastName, avatarUrl, color } = companion;
+		const {
+			name: Name,
+			lastName: LastName,
+			avatarUrl: AvatarUrl,
+			color: Color,
+		} = user;
+		if ((companion && isUser) || isCompanion) {
+			await ChatModel.update(isUser._id, { name, lastName, avatarUrl, color });
+			await ChatModel.update(isCompanion._id, {
+				name: Name,
+				lastName: LastName,
+				avatarUrl: AvatarUrl,
+				color: Color,
+			});
+			return res.status(200).json({
+				status: 'success',
+				code: 200,
+				data: companion,
+			});
+		}
+
+		if (companion && !isUser && !isCompanion) {
+			await ChatModel.add({
+				name,
+				lastName,
+				avatarUrl,
+				color,
+				companionId: id,
+				owner: userId,
+			});
+			await ChatModel.add({
+				name: Name,
+				lastName: LastName,
+				avatarUrl: AvatarUrl,
+				color: Color,
+				companionId: userId,
+				owner: id,
+			});
+			return res.status(201).json({
+				status: 'success',
+				code: 201,
+				data: companion,
+			});
+		}
+	} catch (e) {
+		next(e);
+	}
+};
+
+module.exports = {
+	listChats,
+	startChat,
+};

+ 13 - 10
controllers/contacts.js

@@ -1,10 +1,10 @@
-const Contact = require('../model/contact');
+const ContactModel = require('../model/contact');
 const UserModel = require('../model/user');
 
 const listContacts = async (req, res, next) => {
 	try {
 		const userId = req.user.id;
-		const contacts = await Contact.getList(userId, req.query);
+		const contacts = await ContactModel.getList(userId, req.query);
 		return res.json({
 			status: 'success',
 			code: 200,
@@ -21,7 +21,7 @@ const getContactById = async (req, res, next) => {
 	try {
 		const id = req.params.id;
 		const userId = req.user.id;
-		const contact = await Contact.getById(id, userId);
+		const contact = await ContactModel.getById(id, userId);
 		if (contact)
 			return res.json({
 				status: 'success',
@@ -42,11 +42,14 @@ const getContactById = async (req, res, next) => {
 
 const addContact = async (req, res, next) => {
 	try {
-		const { name, lastName, number, country, avatarUrl, color } =
-			await UserModel.findByNumber(req.body.number);
-		if (avatarUrl) {
-			const userId = req.user.id;
-			const newContact = await Contact.add({
+		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,
@@ -75,7 +78,7 @@ const removeContact = async (req, res, next) => {
 	try {
 		const id = req.params.id;
 		const userId = req.user.id;
-		const contact = await Contact.remove(id, userId);
+		const contact = await ContactModel.remove(id, userId);
 		if (contact) {
 			return res.json({
 				status: 'success',
@@ -100,7 +103,7 @@ const updateContact = async (req, res, next) => {
 	try {
 		const id = req.params.id;
 		const userId = req.user.id;
-		const contact = await Contact.update(id, userId, req.body);
+		const contact = await ContactModel.update(id, userId, req.body);
 		if (contact) {
 			return res.status(200).json({
 				status: 'success',

BIN
images/6214c3f21784bb3a843aacc9/clipart289625.png


BIN
images/6214c4381784bb3a843aacca/telegram.png


BIN
images/6214ddc1344fef42a89f0761/monkey.png


BIN
images/62151cee9936e92efc688793/qrcode_telegram.png


+ 48 - 0
model/chat.js

@@ -0,0 +1,48 @@
+const Chat = require('./schemas/chat');
+
+const getList = async (
+	userId,
+	{ sortBy, sortByDesc, filter, limit = '5', page = '1', sub }
+) => {
+	const options = { owner: userId };
+	if (sub) options.subscription = { $all: [sub] };
+	const results = await Chat.paginate(options, {
+		limit,
+		page,
+		sort: {
+			...(sortBy ? { [`${sortBy}`]: 1 } : {}),
+			...(sortByDesc ? { [`${sortByDesc}`]: -1 } : {}),
+		},
+		select: filter ? filter.split('|').join(' ') : '',
+		populate: {
+			path: 'owner',
+			select: '_id',
+		},
+	});
+	const { docs: chats, totalDocs: total } = results;
+	return { total: total.toString(), limit, page, chats };
+};
+
+const getByField = async (companionId, userId) => {
+	const chat = await Chat.findOne({
+		companionId,
+		owner: userId,
+	});
+	return chat;
+};
+
+const add = async (obj) => {
+	const chat = await Chat.create(obj);
+	return chat;
+};
+
+const update = async (id, obj) => {
+	return await Chat.updateOne({ _id: id }, { ...obj });
+};
+
+module.exports = {
+	getList,
+	getByField,
+	add,
+	update,
+};

+ 10 - 1
model/contact.js

@@ -16,7 +16,7 @@ const getList = async (
 		select: filter ? filter.split('|').join(' ') : '',
 		populate: {
 			path: 'owner',
-			select: 'email password subscription token -_id',
+			select: '_id',
 		},
 	});
 	const { docs: contacts, totalDocs: total } = results;
@@ -31,6 +31,14 @@ const getById = async (id, userId) => {
 	return foundContact;
 };
 
+const getByField = async (number, userId) => {
+	const contact = await Contact.findOne({
+		number,
+		owner: userId,
+	});
+	return contact;
+};
+
 const add = async (obj) => {
 	const contact = await Contact.create(obj);
 	return contact;
@@ -46,6 +54,7 @@ const remove = async (id, userId) => {
 
 module.exports = {
 	getList,
+	getByField,
 	getById,
 	add,
 	remove,

+ 38 - 0
model/schemas/chat.js

@@ -0,0 +1,38 @@
+const mongoose = require('mongoose');
+const { Schema, model, SchemaTypes } = mongoose;
+const mongoosePaginate = require('mongoose-paginate-v2');
+
+mongoose.Types.ObjectId.isValid();
+
+const chatSchema = new Schema(
+	{
+		companionId: {
+			type: String,
+		},
+		name: {
+			type: String,
+			default: null,
+		},
+		lastName: {
+			type: String,
+			default: null,
+		},
+		avatarUrl: {
+			type: String,
+			default: null,
+		},
+		color: {
+			type: String,
+			default: null,
+		},
+		owner: {
+			type: SchemaTypes.ObjectId,
+			ref: 'user',
+		},
+	},
+	{ timestamps: true }
+);
+chatSchema.plugin(mongoosePaginate);
+const Chat = model('chat', chatSchema);
+
+module.exports = Chat;

+ 3 - 1
model/schemas/contact.js

@@ -6,6 +6,9 @@ mongoose.Types.ObjectId.isValid();
 
 const contactSchema = new Schema(
 	{
+		companionId: {
+			type: String,
+		},
 		name: {
 			type: String,
 			default: null,
@@ -16,7 +19,6 @@ const contactSchema = new Schema(
 		},
 		number: {
 			type: String,
-			unique: true,
 			default: null,
 		},
 		country: {

+ 11 - 0
routes/chats.js

@@ -0,0 +1,11 @@
+const express = require('express');
+const router = express.Router();
+const guard = require('../helpers/guard');
+const controllers = require('../controllers/chats');
+const validation = require('../validation/chats');
+
+router
+	.get('/', guard, controllers.listChats)
+	.post('/', guard, validation.startChat, controllers.startChat);
+
+module.exports = router;

+ 10 - 0
validation/chats.js

@@ -0,0 +1,10 @@
+const Joi = require('joi');
+
+const validate = require('./validate');
+
+const schemaStartChat = Joi.object({
+	id: Joi.string().required(),
+});
+module.exports.startChat = (req, _res, next) => {
+	return validate(schemaStartChat, req.body, next);
+};