diff --git a/src/pages/api/api-helpers/index.js b/src/pages/api/api-helpers/index.js index def403daa..a7763cbd0 100644 --- a/src/pages/api/api-helpers/index.js +++ b/src/pages/api/api-helpers/index.js @@ -9,3 +9,16 @@ export function checkParams(eventBody, params) { return hasError } + +export const checkLength = message => { + const length = message.trim().split(' ').length + if (length === 1) { + return true + } + return false +} + +export const contactErrors = { + missingOrRequired: 'Missing or incorrect required property', + tooShort: 'Message is too short for submission', +} diff --git a/src/pages/api/contact.js b/src/pages/api/contact.js index 23431abeb..6f9e6913f 100644 --- a/src/pages/api/contact.js +++ b/src/pages/api/contact.js @@ -1,15 +1,22 @@ import axios from 'axios' -import { checkParams } from './api-helpers' +import { checkParams, checkLength, contactErrors } from './api-helpers' export default async function handler(req, res) { const parsedBody = JSON.parse(req.body) const { name, email, phone, message } = parsedBody const requiredParams = ['email', 'message'] const hasErrors = checkParams(parsedBody, requiredParams) + const isPossiblySpam = checkLength(message) if (hasErrors) { return res.status(422).json({ - error: 'Missing or incorrect required property', + error: contactErrors.missingOrRequired, + }) + } + + if (isPossiblySpam) { + return res.status(400).json({ + error: contactErrors.tooShort, }) } diff --git a/tests/api/contact.test.js b/tests/api/contact.test.js index e72129f61..fad23426b 100644 --- a/tests/api/contact.test.js +++ b/tests/api/contact.test.js @@ -69,4 +69,23 @@ describe('contact handler', () => { expect(res._getStatusCode()).toBe(500) expect(res._getData()).toBe('{"message":"Failed post to #contact channel"}') }) + + test('should throw a 400 error when the length of the message is too short', async () => { + const body = { + name: 'Jody', + email: 'fake@email.com', + phone_number: '111-111-1111', + message: 'nope', + } + const { req, res } = createMocks({ + method: 'POST', + statusCode: 200, + body: JSON.stringify(body), + }) + + await contactApiHandler(req, res) + + expect(res._getStatusCode()).toBe(400) + expect(res._getData()).toBe('{"error":"Message is too short for submission"}') + }) })