From 8db18cc9f60a51a21de7ac577d1517f66d4f2fc2 Mon Sep 17 00:00:00 2001 From: antoineludeau <52679050+antoineludeau@users.noreply.github.com> Date: Fri, 8 Nov 2024 16:37:07 +0100 Subject: [PATCH] Improved api response format and homogeneity --- lib/api/address/routes.js | 168 ++++++------------ lib/api/ban-id/routes.js | 28 +-- lib/api/certificate/routes.js | 31 ++-- lib/api/common-toponym/routes.js | 174 ++++++------------- lib/api/district/routes.js | 181 +++++++------------- lib/api/export-to-exploitation-db/routes.js | 25 +-- lib/api/helper.js | 9 + lib/api/job-status/routes.js | 26 ++- lib/api/postal-datanova/routes.js | 14 +- 9 files changed, 224 insertions(+), 432 deletions(-) diff --git a/lib/api/address/routes.js b/lib/api/address/routes.js index cf1ae38d..f63b93e3 100644 --- a/lib/api/address/routes.js +++ b/lib/api/address/routes.js @@ -4,6 +4,7 @@ import express from 'express' import queue from '../../util/queue.cjs' import auth from '../../middleware/auth.js' import analyticsMiddleware from '../../middleware/analytics.js' +import {handleAPIResponse} from '../helper.js' import {getAddress, deleteAddress} from './models.js' import {getDeltaReport, formatAddress} from './utils.js' @@ -18,207 +19,138 @@ const app = new express.Router() app.route('/') .post(auth, analyticsMiddleware, async (req, res) => { - let response try { const addresses = req.body - const statusID = nanoid() + if (!Array.isArray(addresses)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'address', jobType: 'insert', data: addresses, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) .put(auth, analyticsMiddleware, async (req, res) => { - let response try { const addresses = req.body - const statusID = nanoid() + if (!Array.isArray(addresses)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'address', jobType: 'update', data: addresses, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) .patch(auth, analyticsMiddleware, async (req, res) => { - let response try { const addresses = req.body - const statusID = nanoid() + if (!Array.isArray(addresses)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'address', jobType: 'patch', data: addresses, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) app.route('/:addressID') .get(analyticsMiddleware, async (req, res) => { - let response try { const {addressID} = req.params - const address = await getAddress(addressID) + if (!addressID) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const address = await getAddress(addressID) if (!address) { - res.status(404).send('Request ID unknown') + handleAPIResponse(res, 404, 'Request ID unknown', {}) return } const addressFormatted = formatAddress(address) - - response = { - date: new Date(), - status: 'success', - response: addressFormatted, - } + handleAPIResponse(res, 200, 'Address successfully retrieved', addressFormatted) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) .delete(auth, analyticsMiddleware, async (req, res) => { - let response try { const {addressID} = req.params const address = await getAddress(addressID) if (!address) { - res.status(404).send('Request ID unknown') + handleAPIResponse(res, 404, 'Request ID unknown', {}) return } await deleteAddress(addressID) - response = { - date: new Date(), - status: 'success', - response: {}, - } + handleAPIResponse(res, 200, 'Address successfully deleted', {}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) app.post('/delete', auth, analyticsMiddleware, async (req, res) => { - let response try { const addressIDs = req.body + if (!Array.isArray(addressIDs)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'address', jobType: 'delete', data: addressIDs, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) app.post('/delta-report', auth, analyticsMiddleware, async (req, res) => { - let response try { const {data, districtID} = req.body - if (!data || !districtID) { - res.status(404).send('Wrong request format') + handleAPIResponse(res, 400, 'Wrong request format', {}) return } const deltaReport = await getDeltaReport(data, districtID) - response = { - date: new Date(), - status: 'success', - response: deltaReport, - } + handleAPIResponse(res, 200, 'Delta report successfully generated', deltaReport) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) export default app diff --git a/lib/api/ban-id/routes.js b/lib/api/ban-id/routes.js index a09964ba..7aa2cf30 100644 --- a/lib/api/ban-id/routes.js +++ b/lib/api/ban-id/routes.js @@ -1,42 +1,26 @@ import 'dotenv/config.js' // eslint-disable-line import/no-unassigned-import import express from 'express' import analyticsMiddleware from '../../middleware/analytics.js' + +import {handleAPIResponse} from '../helper.js' import {getUuids, uncollidUuids} from './helpers.js' const app = new express.Router() app.get('/', analyticsMiddleware, async (req, res) => { - let response try { const length = Number(req.query.quantity) || 1 if (length > 100_000) { - res.status(400).send({ - date: new Date(), - status: 'error', - message: 'Quantity must be less than 100 000', - response: {}, - }) + handleAPIResponse(res, 400, 'Quantity must be less than 100 000', {}) return } const ids = await uncollidUuids(getUuids(length)) - - response = { - date: new Date(), - status: 'success', - response: ids, - } + handleAPIResponse(res, 200, 'Successfully generated UUIDs', ids) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) export default app diff --git a/lib/api/certificate/routes.js b/lib/api/certificate/routes.js index f430ec18..f07b06e4 100644 --- a/lib/api/certificate/routes.js +++ b/lib/api/certificate/routes.js @@ -1,6 +1,7 @@ import 'dotenv/config.js' // eslint-disable-line import/no-unassigned-import import express from 'express' import auth from '../../middleware/auth.js' +import {handleAPIResponse} from '../helper.js' import { getCertificate, setCertificate, @@ -15,43 +16,45 @@ app.get('/:id', async (req, res) => { const {id} = req.params try { const certificate = await getCertificate(id) - if (certificate) { - res.status(200).json(certificate) - } else { - res.status(404).json({message: 'Certificate not found'}) + if (!certificate) { + handleAPIResponse(res, 404, 'Certificate not found', {}) + return } + + handleAPIResponse(res, 200, 'Certificate retrieved', certificate) } catch (error) { - console.error(`Error retrieving certificate: ${error.message}`) - res.status(500).json({message: 'Internal server error'}) + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } }) app.post('/', auth, async (req, res) => { try { const {addressID} = req.body - if (!addressID) { - return res.status(400).json({message: 'addressID is required'}) + handleAPIResponse(res, 400, 'addressID is required', {}) + return } const data = await getDataForCertificate(addressID) - if (!data) { - return res.status(400).json({message: 'Address is not certified, not active, or has no parcels.'}) + handleAPIResponse(res, 403, 'Address is not certified, not active, or has no parcels.', {}) + return } const {districtConfig} = data if (!districtConfig.certificate) { - return res.status(400).json({message: 'District has not activated the certificate config.'}) + handleAPIResponse(res, 403, 'District has not activated the certificate config.', {}) + return } const certificate = await formatDataForCertificate(data) const newCertificate = await setCertificate(certificate) - res.status(201).json(newCertificate) + handleAPIResponse(res, 201, 'Certificate created', newCertificate) } catch (error) { - console.error(`Error creating certificate: ${error.message}`) - res.status(500).json({message: 'Internal server error'}) + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } }) diff --git a/lib/api/common-toponym/routes.js b/lib/api/common-toponym/routes.js index be88ddac..dd5e1a12 100644 --- a/lib/api/common-toponym/routes.js +++ b/lib/api/common-toponym/routes.js @@ -4,6 +4,7 @@ import express from 'express' import queue from '../../util/queue.cjs' import auth from '../../middleware/auth.js' import analyticsMiddleware from '../../middleware/analytics.js' +import {handleAPIResponse} from '../helper.js' import {getCommonToponym, deleteCommonToponym} from './models.js' import {getDeltaReport, formatCommonToponym} from './utils.js' @@ -18,207 +19,142 @@ const app = new express.Router() app.route('/') .post(auth, analyticsMiddleware, async (req, res) => { - let response try { const commonToponyms = req.body - const statusID = nanoid() + if (!Array.isArray(commonToponyms)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'commonToponym', jobType: 'insert', data: commonToponyms, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) .put(auth, analyticsMiddleware, async (req, res) => { - let response try { const commonToponyms = req.body - const statusID = nanoid() + if (!Array.isArray(commonToponyms)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'commonToponym', jobType: 'update', data: commonToponyms, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) .patch(auth, analyticsMiddleware, async (req, res) => { - let response try { const commonToponyms = req.body - const statusID = nanoid() + if (!Array.isArray(commonToponyms)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'commonToponym', jobType: 'patch', data: commonToponyms, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) app.route('/:commonToponymID') .get(analyticsMiddleware, async (req, res) => { - let response try { const {commonToponymID} = req.params - const commonToponym = await getCommonToponym(commonToponymID) + if (!commonToponymID) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const commonToponym = await getCommonToponym(commonToponymID) if (!commonToponym) { - res.status(404).send('Request ID unknown') + handleAPIResponse(res, 404, 'Request ID unknown', {}) return } const commonToponymFormatted = formatCommonToponym(commonToponym) - - response = { - date: new Date(), - status: 'success', - response: commonToponymFormatted, - } + handleAPIResponse(res, 200, 'Common toponym successfully retrieved', commonToponymFormatted) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) .delete(auth, analyticsMiddleware, async (req, res) => { - let response try { const {commonToponymID} = req.params - const commonToponym = await getCommonToponym(commonToponymID) + if (!commonToponymID) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const commonToponym = await getCommonToponym(commonToponymID) if (!commonToponym) { - res.status(404).send('Request ID unknown') + handleAPIResponse(res, 404, 'Request ID unknown', {}) return } await deleteCommonToponym(commonToponymID) - response = { - date: new Date(), - status: 'success', - response: {}, - } + handleAPIResponse(res, 200, 'Common toponym successfully deleted', {}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) app.post('/delete', auth, analyticsMiddleware, async (req, res) => { - let response try { const commonToponymIDs = req.body - const statusID = nanoid() + if (!Array.isArray(commonToponymIDs)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'commonToponym', jobType: 'delete', data: commonToponymIDs, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) app.post('/delta-report', auth, analyticsMiddleware, async (req, res) => { - let response try { const {data, districtID} = req.body if (!data || !districtID) { - res.status(404).send('Wrong request format') + handleAPIResponse(res, 400, 'Wrong request format', {}) return } const deltaReport = await getDeltaReport(data, districtID) - response = { - date: new Date(), - status: 'success', - response: deltaReport, - } + handleAPIResponse(res, 200, 'Delta report generated', deltaReport) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) export default app diff --git a/lib/api/district/routes.js b/lib/api/district/routes.js index 35353196..d6540ebf 100644 --- a/lib/api/district/routes.js +++ b/lib/api/district/routes.js @@ -4,6 +4,7 @@ import express from 'express' import queue from '../../util/queue.cjs' import auth from '../../middleware/auth.js' import analyticsMiddleware from '../../middleware/analytics.js' +import {handleAPIResponse} from '../helper.js' import {getDistrict, getDistrictsFromCog, deleteDistrict} from './models.js' import {formatDistrict} from './utils.js' @@ -18,209 +19,147 @@ const app = new express.Router() app.route('/') .post(auth, analyticsMiddleware, async (req, res) => { - let response try { const districts = req.body - const statusID = nanoid() + if (!Array.isArray(districts)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'district', jobType: 'insert', data: districts, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) .put(auth, analyticsMiddleware, async (req, res) => { - let response try { const districts = req.body - const statusID = nanoid() + if (!Array.isArray(districts)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'district', jobType: 'update', data: districts, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) .patch(auth, analyticsMiddleware, async (req, res) => { - let response try { const districts = req.body - const statusID = nanoid() + if (!Array.isArray(districts)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'district', jobType: 'patch', data: districts, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) app.route('/:districtID') .get(analyticsMiddleware, async (req, res) => { - let response try { const {districtID} = req.params - const district = await getDistrict(districtID) + if (!districtID) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const district = await getDistrict(districtID) if (!district) { - res.status(404).send('Request ID unknown') + handleAPIResponse(res, 404, 'Request ID unknown', {}) return } const districtFormatted = formatDistrict(district) - - response = { - date: new Date(), - status: 'success', - response: districtFormatted, - } + handleAPIResponse(res, 200, 'District successfilly retrieved', districtFormatted) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) .delete(auth, analyticsMiddleware, async (req, res) => { - let response try { const {districtID} = req.params - const district = await getDistrict(districtID) + if (!districtID) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const district = await getDistrict(districtID) if (!district) { - res.status(404).send('Request ID unknown') + handleAPIResponse(res, 404, 'Request ID unknown', {}) return } await deleteDistrict(districtID) - response = { - date: new Date(), - status: 'success', - response: {}, - } + handleAPIResponse(res, 200, 'District successfully deleted', {}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) app.post('/delete', auth, analyticsMiddleware, async (req, res) => { - let response try { const districtIDs = req.body - const statusID = nanoid() + if (!Array.isArray(districtIDs)) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const statusID = nanoid() await apiQueue.add( {dataType: 'district', jobType: 'delete', data: districtIDs, statusID}, {jobId: statusID, removeOnComplete: true} ) - response = { - date: new Date(), - status: 'success', - message: `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, - response: {statusID}, - } + handleAPIResponse(res, 200, `Check the status of your request : ${BAN_API_URL}/job-status/${statusID}`, {statusID}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) app.get('/cog/:cog', analyticsMiddleware, async (req, res) => { - let response try { const {cog} = req.params - const districts = await getDistrictsFromCog(cog) + if (!cog) { + handleAPIResponse(res, 400, 'Wrong request format', {}) + return + } + const districts = await getDistrictsFromCog(cog) if (!districts || districts.length === 0) { - res.status(404).send('Request ID unknown') + handleAPIResponse(res, 404, 'Request ID unknown', {}) return } const districtBodies = districts.map(district => formatDistrict(district)) - - response = { - date: new Date(), - status: 'success', - response: districtBodies, - } + handleAPIResponse(res, 200, 'Districts successfully retrieved', districtBodies) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) export default app diff --git a/lib/api/export-to-exploitation-db/routes.js b/lib/api/export-to-exploitation-db/routes.js index 3cf96a62..469d8c42 100644 --- a/lib/api/export-to-exploitation-db/routes.js +++ b/lib/api/export-to-exploitation-db/routes.js @@ -2,6 +2,7 @@ import 'dotenv/config.js' // eslint-disable-line import/no-unassigned-import import express from 'express' import queue from '../../util/queue.cjs' import auth from '../../middleware/auth.js' +import {handleAPIResponse} from '../helper.js' import {getDistricts} from '../district/models.js' const exportToExploitationDBQueue = queue('export-to-exploitation-db') @@ -10,37 +11,27 @@ const app = new express.Router() app.route('/districts') .post(auth, async (req, res) => { - let response try { const {districtIDs} = req.body if (!districtIDs || districtIDs.length === 0) { - res.status(400).send('districtIDs should not be empty') + handleAPIResponse(res, 400, 'districtIDs should not be empty', {}) + return } const districts = await getDistricts(districtIDs) if (districts.length !== districtIDs.length) { - res.status(404).send('Some districts not found') + handleAPIResponse(res, 404, 'Some districts not found', {}) + return } await Promise.all(districtIDs.map(async districtID => exportToExploitationDBQueue.add({districtID}, {removeOnComplete: true, removeOnFail: true}))) - response = { - date: new Date(), - status: 'success', - response: {}, - } + handleAPIResponse(res, 200, 'Districts successfully exported to exploitation DB', {}) } catch (error) { - const {message} = error - response = { - date: new Date(), - status: 'error', - message, - response: {}, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) export default app diff --git a/lib/api/helper.js b/lib/api/helper.js index 3c56d1de..6544a600 100644 --- a/lib/api/helper.js +++ b/lib/api/helper.js @@ -170,3 +170,12 @@ export const formatPayloadDates = payload => payload.map(item => ({ ...((item.updateDate) ? {updateDate: new Date(item.updateDate)} : {}) }) ) + +export const handleAPIResponse = (res, status, message, response) => { + res.status(status).json({ + date: new Date(), + status: status >= 200 && status < 300 ? 'success' : 'error', + message, + response, + }) +} diff --git a/lib/api/job-status/routes.js b/lib/api/job-status/routes.js index 52e79d63..2219f4d4 100644 --- a/lib/api/job-status/routes.js +++ b/lib/api/job-status/routes.js @@ -1,5 +1,6 @@ import express from 'express' import queue from '../../util/queue.cjs' +import {handleAPIResponse} from '../helper.js' import {getJobStatus} from './models.js' const apiQueue = queue('api') @@ -7,36 +8,31 @@ const apiQueue = queue('api') const app = new express.Router() app.get('/:statusID', async (req, res) => { - let response try { const {statusID} = req.params - const job = await apiQueue.getJob(statusID) + if (!statusID) { + handleAPIResponse(res, 400, 'Request ID missing', {}) + } + const job = await apiQueue.getJob(statusID) if (job) { const status = job?.processedOn ? 'processing' : 'pending' - response = {status} + handleAPIResponse(res, 200, 'Job status has not been yet processed', {status}) } else { const jobStatus = await getJobStatus(statusID) if (jobStatus) { const {id, ...jobStatusBody} = jobStatus if (jobStatusBody) { - response = jobStatusBody + handleAPIResponse(res, 200, 'Job status has been processed', jobStatusBody) } + } else { + handleAPIResponse(res, 404, 'Request ID unknown', {}) } } - - if (!response) { - return res.status(404).send('Request ID unknown') - } } catch (error) { - const {message} = error - response = { - status: 'error', - message, - } + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } - - res.send(response) }) export default app diff --git a/lib/api/postal-datanova/routes.js b/lib/api/postal-datanova/routes.js index 83b73ba3..bc3bc942 100644 --- a/lib/api/postal-datanova/routes.js +++ b/lib/api/postal-datanova/routes.js @@ -1,6 +1,7 @@ import 'dotenv/config.js' // eslint-disable-line import/no-unassigned-import import express from 'express' import auth from '../../middleware/auth.js' +import {handleAPIResponse} from '../helper.js' import {updateMultipleDatanova} from './models.js' const app = new express.Router() @@ -11,7 +12,8 @@ app.put('/', auth, async (req, res) => { const items = req.body if (!Array.isArray(items) || items.length === 0) { - return res.status(400).json({message: 'An array of items is required'}) + handleAPIResponse(res, 400, 'An array of items is required', {}) + return } const results = await updateMultipleDatanova(items) @@ -20,17 +22,17 @@ app.put('/', auth, async (req, res) => { const failedUpdates = results.filter(({updatedRowsCount, error}) => updatedRowsCount === 0 || error) if (failedUpdates.length > 0) { - return res.status(207).json({ - message: 'Partial success', + handleAPIResponse(res, 207, 'Partial success', { totalUpdated, failedUpdates: failedUpdates.map(({inseeCom, error}) => ({inseeCom, error})) }) + return } - res.status(200).json({message: 'Records updated successfully', totalUpdated}) + handleAPIResponse(res, 200, 'Records updated successfully', {totalUpdated}) } catch (error) { - console.error('Error updating records:', error) - res.status(500).json({message: 'Failed to update records', error: error.message}) + console.error(error) + handleAPIResponse(res, 500, 'Internal server error', {}) } })