From 1439f659a8cb12f6e4f9d8527206d233e5615750 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20FAMIBELLE-PRONZOLA?= Date: Fri, 20 May 2022 00:06:15 +0400 Subject: [PATCH] Create custom commentaire controller --- .../commentaire/controllers/commentaire.js | 55 ++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/src/api/commentaire/controllers/commentaire.js b/src/api/commentaire/controllers/commentaire.js index 76bc735..a19ef6f 100644 --- a/src/api/commentaire/controllers/commentaire.js +++ b/src/api/commentaire/controllers/commentaire.js @@ -1,5 +1,58 @@ 'use strict'; const { createCoreController } = require('@strapi/strapi').factories; +const { ValidationError, NotFoundError, UnauthorizedError } = require("@strapi/utils").errors -module.exports = createCoreController('api::commentaire.commentaire') +module.exports = createCoreController('api::commentaire.commentaire', ({strapi}) => ({ + async create(ctx) { + const {body} = ctx.request + let {data} = body + + if (ctx.request && ctx.request.header && ctx.request.header.authorization) { + try { + const {id} = await strapi.plugins[ + 'users-permissions' + ].services.jwt.getToken(ctx) + + if (id !== data.user.id) { + throw new UnauthorizedError('Opération non autorisée') + } + } catch (err) { + throw new UnauthorizedError(ctx, err, 'Opération non autorisée') + } + } + const user = await strapi.entityService.findOne('plugin::users-permissions.user', body.data.user.id) + + if (!user) { + throw new NotFoundError('Utilisateur introuvable.') + } + + if (user.id !== data.user.id || user.username !== data.user.username || user.email !== data.user.email) { + throw new ValidationError('Informations non valides.') + } + + data.user = user.id + + const parole = await strapi.entityService.findOne('api::parole.parole', data.parole, { + fields: ['id'] + }) + + if (!parole) { + throw new NotFoundError('Texte introuvable.') + } + + const newCommentaire = await strapi.entityService.create('api::commentaire.commentaire', { + data: { + ...data + } + }) + + await strapi.entityService.update('api::parole.parole', parole.id, { + data: { + commentaires: [newCommentaire.id] + } + }) + + return newCommentaire; + } +}))