From 0e21e4b136d2555f1bd61ae51e0925a77ba00b2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20FAMIBELLE-PRONZOLA?= Date: Fri, 20 May 2022 00:07:11 +0400 Subject: [PATCH] Fix error and improve commentaire lifecycles --- .../content-types/commentaire/lifecycles.js | 64 +++++++++++++------ 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/src/api/commentaire/content-types/commentaire/lifecycles.js b/src/api/commentaire/content-types/commentaire/lifecycles.js index 501deb3..73dab34 100644 --- a/src/api/commentaire/content-types/commentaire/lifecycles.js +++ b/src/api/commentaire/content-types/commentaire/lifecycles.js @@ -1,40 +1,64 @@ 'use strict'; -const jwennTeksEpiId = async teksId => { - const paroles = await strapi.db.query('api::parole.parole').findOne({id: teksId}) - return paroles -} +const { ValidationError, NotFoundError } = require("@strapi/utils").errors const jwennUserEpiId = async userId => { - const user = await strapi.db.query('plugin::users-permissions.user').findOne({id: userId}) + if (!userId) { + return null + } + + const user = await strapi.db.query('plugin::users-permissions.user').findOne({ + where: {id: userId} + }) + return user } +const jwennParoleEpiId = async paroleId => { + if (!paroleId) { + return null + } + + const parole = await strapi.db.query('api::parole.parole').findOne({ + where: {id: paroleId} + }) + + return parole +} + +const validateCommentaire = data => { + if (!data.contenu && !data.datePublication) { + throw new ValidationError('Mauvaise requête, contenu et datePublication sont obligatoires') + } + + if (!data.contenu || data.contenu.trim().length === 0) { + throw new ValidationError('Champ obligatoire. Veuillez renseigner le contenu du commentaire.') + } + + if (data.contenu.trim().length > 500) { + throw new ValidationError('Le commentaire doit contenir 500 caractères maximum.') + } +} + module.exports = { beforeCreate: async event => { - let {data} = event.params - - if (data.contenu && data.parole && data.user) { - const parole = await jwennTeksEpiId(data.parole) - const user = await jwennUserEpiId(data.user) - - if(!parole || !user) { - throw new NotFoundError('Introuvable') - } - - } else { - throw new ValidationError('Mauvaise requête') - } + const {data} = event.params + validateCommentaire(data) }, afterCreate: async event => { - const {data} = event.params + const {data, result} = event.params const user = await jwennUserEpiId(data.user) + const parole = await jwennParoleEpiId(data.parole) + + if (!parole) { + throw new NotFoundError('Texte introuvable.') + } if (user) { strapi.plugins['email'].services.email.send({ from: process.env.SMTP_FROM, to: process.env.SMTP_SEND_TO, - subject: `Nouveau commentaire de ${user.username}`, + subject: `Commentaire de ${user.username} sur "${parole.titre}"`, html: data.contenu }) }