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