Ver código fonte

add ability tcreate new contact

unknown 2 anos atrás
pai
commit
64d8f5ee5c

+ 1 - 1
app.js

@@ -20,7 +20,7 @@ app.use(logger(formatsLogger));
 app.use(cors());
 app.use(express.json());
 
-app.use('/contacts', apiLimiter, contactsRouter);
+app.use('/api/contacts', apiLimiter, contactsRouter);
 app.use('/api', apiLimiter, userRoute);
 
 app.use((_req, res) => {

+ 112 - 99
controllers/contacts.js

@@ -1,117 +1,130 @@
-const Contact = require("../model/contact");
+const Contact = 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);
-    return res.json({
-      status: "success",
-      code: 200,
-      data: {
-        ...contacts,
-      },
-    });
-  } catch (e) {
-    next(e);
-  }
+	try {
+		const userId = req.user.id;
+		const contacts = await Contact.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 Contact.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);
-  }
+	try {
+		const id = req.params.id;
+		const userId = req.user.id;
+		const contact = await Contact.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 contact = req.body;
-    const userId = req.user.id;
-    if (contact) {
-      await Contact.add({ ...contact, owner: userId });
-      return res.status(201).json({
-        status: "success",
-        code: 201,
-        data: {
-          contact,
-        },
-      });
-    }
-  } catch (e) {
-    next(e);
-  }
+	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({
+				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 removeContact = async (req, res, next) => {
-  try {
-    const id = req.params.id;
-    const userId = req.user.id;
-    const contact = await Contact.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);
-  }
+	try {
+		const id = req.params.id;
+		const userId = req.user.id;
+		const contact = await Contact.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);
+	}
 };
 
 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);
-    if (contact) {
-      return res.status(200).json({
-        status: "success",
-        code: 200,
-        data: {
-          contact,
-        },
-      });
-    } else {
-      return res.status(404).json({
-        status: "error",
-        code: 404,
-        data: "Not Found",
-      });
-    }
-  } catch (e) {
-    next(e);
-  }
+	try {
+		const id = req.params.id;
+		const userId = req.user.id;
+		const contact = await Contact.update(id, userId, req.body);
+		if (contact) {
+			return res.status(200).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,
+	listContacts,
+	getContactById,
+	addContact,
+	removeContact,
+	updateContact,
 };

+ 3 - 11
controllers/user.js

@@ -12,13 +12,14 @@ const SECRET_KEY = process.env.JWT_SECRET;
 const createNewUser = async (req, res, next) => {
 	try {
 		const code = phoneToken(4, { type: 'number' });
+		const color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
 		const { number, country } = req.body;
 		const isExist = await UserModel.findByNumber(number);
 		if (isExist) {
 			const id = isExist._id;
 			await UserModel.updateCode(id, code);
 		} else {
-			await UserModel.createUser({ number, country, code });
+			await UserModel.createUser({ number, country, color, code });
 		}
 		client.messages.create({
 			body: `${code}`,
@@ -94,19 +95,10 @@ const getCurrent = async (req, res, next) => {
 				data: 'UNAUTHORIZED',
 				message: 'Invalid credentials',
 			});
-		const { name, lastName, country, number, token, avatarUrl: url } = user;
-		const avatarUrl = `localhost:3000/${url}`;
 		return res.status(200).json({
 			status: 'success',
 			code: 200,
-			data: {
-				name,
-				lastName,
-				country,
-				number,
-				token,
-				avatarUrl,
-			},
+			data: user,
 		});
 	} catch (e) {
 		next(e);

BIN
images/6213605caf94c83914c70056/clipart289625.png


BIN
images/62136a16c07bc339f8a8dde4/clipart289625.png


BIN
images/62137f8cc0d62421b053d95c/telegram.png


BIN
images/621381b9be322341e880f309/telegram.png


BIN
images/62138202be322341e880f30a/telegram.png


BIN
images/6213822abe322341e880f30b/telegram.png


BIN
images/62138409d5f2ae2a5076e0fb/clipart289625.png


BIN
images/6213843cd5f2ae2a5076e0fc/telegram.png


BIN
images/6213848cd5f2ae2a5076e0fd/telegram.png


+ 37 - 45
model/contact.js

@@ -1,60 +1,52 @@
-const Contact = require("./schemas/contact");
+const Contact = require('./schemas/contact');
 
 const getList = async (
-  userId,
-  { sortBy, sortByDesc, filter, limit = "5", page = "1", sub }
+	userId,
+	{ sortBy, sortByDesc, filter, limit = '5', page = '1', sub }
 ) => {
-  const options = { owner: userId };
-  if (sub) options.subscription = { $all: [sub] };
-  const results = await Contact.paginate(options, {
-    limit,
-    page,
-    sort: {
-      ...(sortBy ? { [`${sortBy}`]: 1 } : {}),
-      ...(sortByDesc ? { [`${sortByDesc}`]: -1 } : {}),
-    },
-    select: filter ? filter.split("|").join(" ") : "",
-    populate: {
-      path: "owner",
-      select: "email password subscription token -_id",
-    },
-  });
-  const { docs: contacts, totalDocs: total } = results;
-  return { total: total.toString(), limit, page, contacts };
+	const options = { owner: userId };
+	if (sub) options.subscription = { $all: [sub] };
+	const results = await Contact.paginate(options, {
+		limit,
+		page,
+		sort: {
+			...(sortBy ? { [`${sortBy}`]: 1 } : {}),
+			...(sortByDesc ? { [`${sortByDesc}`]: -1 } : {}),
+		},
+		select: filter ? filter.split('|').join(' ') : '',
+		populate: {
+			path: 'owner',
+			select: 'email password subscription token -_id',
+		},
+	});
+	const { docs: contacts, totalDocs: total } = results;
+	return { total: total.toString(), limit, page, contacts };
 };
 
 const getById = async (id, userId) => {
-  const foundContact = await Contact.findById({
-    _id: id,
-    owner: userId,
-  });
-  return foundContact;
+	const foundContact = await Contact.findById({
+		_id: id,
+		owner: userId,
+	});
+	return foundContact;
 };
+
 const add = async (obj) => {
-  const contact = await Contact.create(obj);
-  return contact;
+	const contact = await Contact.create(obj);
+	return contact;
 };
 
 const remove = async (id, userId) => {
-  const removedContact = await Contact.findByIdAndRemove({
-    _id: id,
-    owner: userId,
-  });
-  return removedContact;
-};
-const update = async (id, userId, body) => {
-  const contact = await Contact.findByIdAndUpdate(
-    { _id: id, owner: userId },
-    { ...body },
-    { new: true }
-  );
-  return contact;
+	const removedContact = await Contact.findByIdAndRemove({
+		_id: id,
+		owner: userId,
+	});
+	return removedContact;
 };
 
 module.exports = {
-  getList,
-  getById,
-  add,
-  remove,
-  update,
+	getList,
+	getById,
+	add,
+	remove,
 };

+ 35 - 24
model/schemas/contact.js

@@ -1,34 +1,45 @@
-const mongoose = require("mongoose");
+const mongoose = require('mongoose');
 const { Schema, model, SchemaTypes } = mongoose;
-const mongoosePaginate = require("mongoose-paginate-v2");
+const mongoosePaginate = require('mongoose-paginate-v2');
 
 mongoose.Types.ObjectId.isValid();
 
 const contactSchema = new Schema(
-  {
-    name: {
-      type: String,
-      required: [true, "Set name for contact"],
-    },
-    phone: {
-      type: String,
-      unique: true,
-      required: [true, "Set phone number for current user"],
-    },
-    subscription: {
-      type: String,
-      enum: ["free", "pro", "premium"],
-      required: [true, "Set subscription for current user"],
-    },
-    owner: {
-      type: SchemaTypes.ObjectId,
-      ref: "user",
-    },
-  },
+	{
+		name: {
+			type: String,
+			default: null,
+		},
+		lastName: {
+			type: String,
+			default: null,
+		},
+		number: {
+			type: String,
+			unique: true,
+			default: null,
+		},
+		country: {
+			type: String,
+			default: null,
+		},
+		avatarUrl: {
+			type: String,
+			default: null,
+		},
+		color: {
+			type: String,
+			default: null,
+		},
+		owner: {
+			type: SchemaTypes.ObjectId,
+			ref: 'user',
+		},
+	},
 
-  { timestamps: true }
+	{ timestamps: true }
 );
 contactSchema.plugin(mongoosePaginate);
-const Contact = model("contact", contactSchema);
+const Contact = model('contact', contactSchema);
 
 module.exports = Contact;

+ 4 - 0
model/schemas/user.js

@@ -29,6 +29,10 @@ const userSchema = new Schema(
 			type: String,
 			default: null,
 		},
+		color: {
+			type: String,
+			default: null,
+		},
 		token: {
 			type: String,
 			default: null,

+ 8 - 9
routes/contacts.js

@@ -1,15 +1,14 @@
-const express = require("express");
+const express = require('express');
 const router = express.Router();
-const guard = require("../helpers/guard");
-const controllers = require("../controllers/contacts");
-const validation = require("../validation/contact");
+const guard = require('../helpers/guard');
+const controllers = require('../controllers/contacts');
+const validation = require('../validation/contact');
 router
-  .get("/", guard, controllers.listContacts)
-  .post("/", guard, validation.createContact, controllers.addContact);
+	.get('/', guard, controllers.listContacts)
+	.post('/', guard, validation.createContact, controllers.addContact);
 
 router
-  .get("/:id", guard, controllers.getContactById)
-  .delete("/:id", guard, controllers.removeContact)
-  .patch("/:id", guard, validation.update, controllers.updateContact);
+	.get('/:number', guard, controllers.getContactById)
+	.delete('/:number', guard, controllers.removeContact);
 
 module.exports = router;

+ 5 - 27
validation/contact.js

@@ -1,33 +1,11 @@
-const Joi = require("joi");
+const Joi = require('joi');
 
-const validate = require("./validate");
+const validate = require('./validate');
 
 const schemaCreateContact = Joi.object({
-  name: Joi.string().alphanum().min(3).max(30).trim().required(),
-  phone: Joi.string()
-    .regex(/^[0-9]{10}$/)
-    .messages({
-      "string.pattern.base": `Phone number must have 10 digits and only numbers characters.`,
-    })
-    .required(),
-  subscription: Joi.string().optional(),
-}).min(3);
-
-const schemaUpdateContact = Joi.object({
-  name: Joi.string().alphanum().min(3).max(30).optional().trim().optional(),
-  phone: Joi.string()
-    .regex(/^[0-9]{10}$/)
-    .messages({
-      "string.pattern.base": `Phone number must have 10 digits and only numbers characters.`,
-    })
-    .optional(),
-  subscription: Joi.string().optional(),
-}).min(1);
+	number: Joi.string().min(8).max(14).required(),
+});
 
 module.exports.createContact = (req, _res, next) => {
-  return validate(schemaCreateContact, req.body, next);
-};
-
-module.exports.update = (req, _res, next) => {
-  return validate(schemaUpdateContact, req.body, next);
+	return validate(schemaCreateContact, req.body, next);
 };

+ 0 - 1
validation/user.js

@@ -10,7 +10,6 @@ const schemaCreateNewUser = Joi.object({
 const schemaUpdateUser = Joi.object({
 	name: Joi.string().min(3).max(30).optional().trim().optional(),
 	lastName: Joi.string().min(3).max(30).optional().trim().optional(),
-	number: Joi.string().min(8).max(14).optional(),
 }).min(1);
 
 const schemaLogIn = Joi.object({