diff --git a/backend/src/middleware/validation/validationMiddleware.js b/backend/src/middleware/validation/validationMiddleware.js index 9ac15a60f..77282b6b5 100644 --- a/backend/src/middleware/validation/validationMiddleware.js +++ b/backend/src/middleware/validation/validationMiddleware.js @@ -1,6 +1,9 @@ import { UserInputError } from 'apollo-server' import Joi from '@hapi/joi' +const COMMENT_MIN_LENGTH = 1 +const NO_POST_ERR_MESSAGE = 'Comment cannot be created without a post!' + const validate = schema => { return async (resolve, root, args, context, info) => { const validation = schema.validate(args) @@ -15,8 +18,36 @@ const socialMediaSchema = Joi.object().keys({ .required(), }) +const validateCommentCreation = async (resolve, root, args, context, info) => { + const content = args.content.replace(/<(?:.|\n)*?>/gm, '').trim() + const { postId } = args + + if (!args.content || content.length < COMMENT_MIN_LENGTH) { + throw new UserInputError(`Comment must be at least ${COMMENT_MIN_LENGTH} character long!`) + } + const session = context.driver.session() + const postQueryRes = await session.run( + ` + MATCH (post:Post {id: $postId}) + RETURN post`, + { + postId, + }, + ) + const [post] = postQueryRes.records.map(record => { + return record.get('post') + }) + + if (!post) { + throw new UserInputError(NO_POST_ERR_MESSAGE) + } else { + return resolve(root, args, context, info) + } +} + export default { Mutation: { CreateSocialMedia: validate(socialMediaSchema), + CreateComment: validateCommentCreation, }, } diff --git a/backend/src/schema/resolvers/comments.js b/backend/src/schema/resolvers/comments.js index 7aef63c59..31219d6d9 100644 --- a/backend/src/schema/resolvers/comments.js +++ b/backend/src/schema/resolvers/comments.js @@ -1,40 +1,15 @@ import { neo4jgraphql } from 'neo4j-graphql-js' -import { UserInputError } from 'apollo-server' - -const COMMENT_MIN_LENGTH = 1 -const NO_POST_ERR_MESSAGE = 'Comment cannot be created without a post!' export default { Mutation: { CreateComment: async (object, params, context, resolveInfo) => { - const content = params.content.replace(/<(?:.|\n)*?>/gm, '').trim() const { postId } = params // Adding relationship from comment to post by passing in the postId, // but we do not want to create the comment with postId as an attribute // because we use relationships for this. So, we are deleting it from params // before comment creation. delete params.postId - - if (!params.content || content.length < COMMENT_MIN_LENGTH) { - throw new UserInputError(`Comment must be at least ${COMMENT_MIN_LENGTH} character long!`) - } - const session = context.driver.session() - const postQueryRes = await session.run( - ` - MATCH (post:Post {id: $postId}) - RETURN post`, - { - postId, - }, - ) - const [post] = postQueryRes.records.map(record => { - return record.get('post') - }) - - if (!post) { - throw new UserInputError(NO_POST_ERR_MESSAGE) - } const commentWithoutRelationships = await neo4jgraphql( object, params,