Skip to content

Commit

Permalink
Add a check for length in the footer form to help lessen the amount o…
Browse files Browse the repository at this point in the history
…f spam received (#424)

* feature/lengthOfMessage - Add a check for length in the footer form to help lessen the amount of spam received

* Abstracted errors to object
  • Loading branch information
gixxerblade authored Sep 5, 2022
1 parent 53c88dd commit 6a73de4
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
13 changes: 13 additions & 0 deletions src/pages/api/api-helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
}
11 changes: 9 additions & 2 deletions src/pages/api/contact.js
Original file line number Diff line number Diff line change
@@ -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,
})
}

Expand Down
19 changes: 19 additions & 0 deletions tests/api/contact.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: '[email protected]',
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"}')
})
})

1 comment on commit 6a73de4

@vercel
Copy link

@vercel vercel bot commented on 6a73de4 Sep 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.