changed whatsapp model

This commit is contained in:
canove
2020-09-19 09:52:39 -03:00
parent c77eacf341
commit eab7719583
3 changed files with 32 additions and 27 deletions

View File

@@ -18,6 +18,7 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
interface WhatsappData {
name: string;
status: string;
isDefault?: boolean;
}
export const store = async (req: Request, res: Response): Promise<Response> => {
@@ -25,9 +26,9 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
console.log("aqui");
const { name, status }: WhatsappData = req.body;
const { name, status, isDefault }: WhatsappData = req.body;
const whatsapp = await CreateWhatsAppService({ name, status });
const whatsapp = await CreateWhatsAppService({ name, status, isDefault });
// if (!whatsapp) {
// return res.status(400).json({ error: "Cannot create whatsapp session." });

View File

@@ -38,7 +38,7 @@ class Whatsapp extends Model<Whatsapp> {
@Default(false)
@AllowNull
@Column
default: boolean;
isDefault: boolean;
@CreatedAt
createdAt: Date;

View File

@@ -6,39 +6,43 @@ import Whatsapp from "../../models/Whatsapp";
interface Request {
name: string;
status?: string;
isDefault?: boolean;
}
const CreateWhatsAppService = async ({
name,
status = "INITIALIZING"
status = "INITIALIZING",
isDefault = false
}: Request): Promise<Whatsapp> => {
// const schema = Yup.object().shape({
// name: Yup.string().required().min(2),
// default: Yup.boolean()
// .required()
// .test(
// "Check-default",
// "Only one default whatsapp is permited",
// async value => {
// if (value === true) {
// const whatsappFound = await Whatsapp.findOne({
// where: { default: true }
// });
// return !Boolean(whatsappFound);
// } else return true;
// }
// )
// });
const schema = Yup.object().shape({
name: Yup.string().required().min(2),
isDefault: Yup.boolean()
.required()
.test(
"Check-default",
"Only one default whatsapp is permited",
async value => {
if (value === true) {
const whatsappFound = await Whatsapp.findOne({
where: { isDefault: true }
});
return !whatsappFound;
}
return true;
}
)
});
// try {
// await schema.validate({ name, status });
// } catch (err) {
// throw new AppError(err.message);
// }
try {
await schema.validate({ name, status, isDefault });
} catch (err) {
throw new AppError(err.message);
}
const whatsapp = await Whatsapp.create({
name,
status
status,
isDefault
});
return whatsapp;