-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add params checking in the api/score endpoint
- Loading branch information
1 parent
0c3e386
commit 2f93f4b
Showing
2 changed files
with
104 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,42 @@ | ||
import { calculateScore } from '~/utils/score'; | ||
|
||
function isJson(str) { | ||
try { | ||
JSON.parse(str); | ||
} catch (e) { | ||
return false; | ||
} | ||
return true; | ||
} | ||
|
||
/** | ||
* Endpoint that triggers the calculateScore function, checks that params are correct (jsonA and jsonB are JSON objects) | ||
* @param req | ||
* @param res | ||
* @return {*|void|Promise<any>} | ||
*/ | ||
export default (req, res) => { | ||
if (req.method === 'POST') { | ||
res.statusCode = 200; | ||
res.json(calculateScore(JSON.parse(req.body.jsonA), JSON.parse(req.body.jsonB))); | ||
const validParams = ['jsonA', 'jsonB'].map((json) => { | ||
res.statusCode = 422; | ||
if (!req.body[json]) { | ||
res.end(`Missing Param: Body must contain ${json}`); | ||
return false; | ||
} | ||
if (!isJson(req.body[json])) { | ||
res.end(`Could not parse ${json} param as a JSON object`); | ||
return false; | ||
} | ||
return true; | ||
}); | ||
|
||
if (validParams.every((isValid) => isValid === true)) { | ||
res.statusCode = 200; | ||
return res.json(calculateScore(JSON.parse(req.body.jsonA), JSON.parse(req.body.jsonB))); | ||
} | ||
} else { | ||
res.statusCode = 405; | ||
return res.end('Method not allowed'); | ||
} | ||
res.statusCode = 405; | ||
res.end('Method not allowed'); | ||
return null; | ||
}; |