diff --git a/backend/src/resolvers/comments.js b/backend/src/resolvers/comments.js index b3350ec8e..60ecbcc8e 100644 --- a/backend/src/resolvers/comments.js +++ b/backend/src/resolvers/comments.js @@ -1,5 +1,7 @@ import { neo4jgraphql } from 'neo4j-graphql-js' +import { UserInputError } from 'apollo-server' +const COMMENT_MIN_LENGTH = 3 export default { Query: { CommentByPost: async (object, params, context, resolveInfo) => { @@ -23,6 +25,11 @@ export default { }, Mutation: { CreateComment: async (object, params, context, resolveInfo) => { + const content = params.content.replace(/<(?:.|\n)*?>/gm, '').trim() + + if (!params.content || content.length < COMMENT_MIN_LENGTH) { + throw new UserInputError(`Comment must be at least ${COMMENT_MIN_LENGTH} characters long!`) + } const { postId } = params delete params.postId const comment = await neo4jgraphql(object, params, context, resolveInfo, false) diff --git a/backend/src/resolvers/comments.spec.js b/backend/src/resolvers/comments.spec.js index 9918038a7..eb4e39633 100644 --- a/backend/src/resolvers/comments.spec.js +++ b/backend/src/resolvers/comments.spec.js @@ -44,7 +44,7 @@ describe('CreateComment', () => { client = new GraphQLClient(host, { headers }) }) - it('creates a post', async () => { + it('creates a comment', async () => { variables = { postId: 'p1', content: 'I\'m authorised to comment' @@ -57,5 +57,25 @@ describe('CreateComment', () => { await expect(client.request(mutation, variables)).resolves.toMatchObject(expected) }) + + it('throw an error if an empty string is sent as content', async () => { + variables = { + postId: 'p1', + content: '
' + } + + await expect(client.request(mutation, variables)) + .rejects.toThrow('Comment must be at least 3 characters long!') + }) + + it('throws an error if a comment is less than 3 characters', async () => { + variables = { + postId: 'p1', + content: 'ab
' + } + + await expect(client.request(mutation, variables)) + .rejects.toThrow('Comment must be at least 3 characters long!') + }) }) })