Skip to content

Commit

Permalink
safelyParseJson
Browse files Browse the repository at this point in the history
  • Loading branch information
MrFjellstad committed Jan 22, 2025
1 parent 91aa058 commit 9c70d3e
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ const API_BASEPATH = process.env.API_BASEPATH || '';
// eslint-disable-next-line no-undef
const AUDIENCE = process.env.AUDIENCE || '';

function safelyParseJSON(json) {
let parsed;

try {
parsed = JSON.parse(json);
} catch (e) {
parsed = {};
}

return parsed; // Could be undefined!
}

const startServer = () => {
app.get('/health/is-alive', (req, res) => {
res.sendStatus(200);
Expand Down Expand Up @@ -71,7 +83,8 @@ const startServer = () => {
body: req.method === 'GET' || req.method === 'DELETE' ? undefined : JSON.stringify(req.body)
});

const json = req.method === 'DELETE' ? undefined : await data.json();
const json = req.method === 'DELETE' ? undefined : safelyParseJSON(data);

res.status(data.status);
res.send(json);
});
Expand Down

0 comments on commit 9c70d3e

Please sign in to comment.