From 872e237b48f3c1bdaebe521da46647f1382675b1 Mon Sep 17 00:00:00 2001 From: canove Date: Sat, 19 Sep 2020 09:59:10 -0300 Subject: [PATCH] add validation to whatsapp name --- backend/src/controllers/WhatsAppController.ts | 4 +--- backend/src/models/Whatsapp.ts | 5 ++++- .../WhatsappService/CreateWhatsAppService.ts | 19 +++++++++++++++++-- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/backend/src/controllers/WhatsAppController.ts b/backend/src/controllers/WhatsAppController.ts index 3262f74..dc1f9ef 100644 --- a/backend/src/controllers/WhatsAppController.ts +++ b/backend/src/controllers/WhatsAppController.ts @@ -17,15 +17,13 @@ export const index = async (req: Request, res: Response): Promise => { interface WhatsappData { name: string; - status: string; + status?: string; isDefault?: boolean; } export const store = async (req: Request, res: Response): Promise => { // const io = getIO(); - console.log("aqui"); - const { name, status, isDefault }: WhatsappData = req.body; const whatsapp = await CreateWhatsAppService({ name, status, isDefault }); diff --git a/backend/src/models/Whatsapp.ts b/backend/src/models/Whatsapp.ts index 6a590d3..6ba684e 100644 --- a/backend/src/models/Whatsapp.ts +++ b/backend/src/models/Whatsapp.ts @@ -9,7 +9,8 @@ import { AutoIncrement, Default, AllowNull, - HasMany + HasMany, + Unique } from "sequelize-typescript"; import Ticket from "./Ticket"; @@ -20,6 +21,8 @@ class Whatsapp extends Model { @Column id: number; + @AllowNull + @Unique @Column(DataType.TEXT) name: string; diff --git a/backend/src/services/WhatsappService/CreateWhatsAppService.ts b/backend/src/services/WhatsappService/CreateWhatsAppService.ts index 5127253..fbc3fa5 100644 --- a/backend/src/services/WhatsappService/CreateWhatsAppService.ts +++ b/backend/src/services/WhatsappService/CreateWhatsAppService.ts @@ -15,12 +15,27 @@ const CreateWhatsAppService = async ({ isDefault = false }: Request): Promise => { const schema = Yup.object().shape({ - name: Yup.string().required().min(2), + name: Yup.string() + .required() + .min(2) + .test( + "Check-name", + "This whatsapp name is already used.", + async value => { + if (value) { + const whatsappFound = await Whatsapp.findOne({ + where: { name: value } + }); + return !whatsappFound; + } + return true; + } + ), isDefault: Yup.boolean() .required() .test( "Check-default", - "Only one default whatsapp is permited", + "Only one default whatsapp is permitted", async value => { if (value === true) { const whatsappFound = await Whatsapp.findOne({