diff --git a/lib/index.js b/lib/index.js index 575dd84..74140c7 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,5 +1,8 @@ const getApagonesDBClient = require('./apagones-client'); +const { validatePostData,transformGeoData } = require('./utils') module.exports = { - getApagonesDBClient + getApagonesDBClient, + validatePostData, + transformGeoData } \ No newline at end of file diff --git a/lib/utils.js b/lib/utils.js new file mode 100644 index 0000000..f7266ba --- /dev/null +++ b/lib/utils.js @@ -0,0 +1,38 @@ +function validatePostData(data) { + if(data.hasOwnProperty('location')) { + if(!data.location.hasOwnProperty('lat')) { + throw Error('`lat` property missing from location'); + } + if(!data.location.hasOwnProperty('lng')) { + throw Error('`lat` property missing from location'); + } + } else { + throw Error('`location` property is required'); + } + + if(!data.hasOwnProperty('type')) { + throw Error('`type` property is required'); + } + if(!data.hasOwnProperty('source')) { + throw Error('`source` property is required'); + } + + return true; +} + +function transformGeoData({ geoDataType="Point", data }) { + const transformedData = data; + const { lat, lng } = data.location; + + transformedData.location = { + type: geoDataType, + coordinates: [ lng, lat ] + } + + return transformedData; +} + +module.exports = { + validatePostData, + transformGeoData +} diff --git a/routes/index.js b/routes/index.js index ab9633d..9c621da 100644 --- a/routes/index.js +++ b/routes/index.js @@ -2,7 +2,11 @@ const express = require('express'); const apagonesCollection = 'apagones'; const lugaresCollection = 'lugares'; const router = express.Router(); -const { getApagonesDBClient }= require('../lib'); +const { + getApagonesDBClient, + validatePostData, + transformGeoData +} = require('../lib'); /* GET home page. */ router.get('/', function(req, res, next) { @@ -17,20 +21,19 @@ router.get('/apagon', async (req, res, next) => { res.json({ data: results }); }); - router.post('/apagon', async (req, res, next) => { const dbClient = await getApagonesDBClient(); const data = req.body; try { - - const results = await dbClient.insert(apagonesCollection, data); + validatePostData(data); + const transformedData = transformGeoData({ data } ); + const results = await dbClient.insert(apagonesCollection, transformedData); res.json({ data: results }); } catch(error) { console.error(error); } }); - router.get('/apagon/:id', async (req, res, next) => { const dbClient = await getApagonesDBClient(); const results = await dbClient.find(apagonesCollection ,{ @@ -60,7 +63,9 @@ router.post('/lugar', async (req, res, next) => { const dbClient = await getApagonesDBClient(); const data = req.body; try { - const results = await dbClient.insert(lugaresCollection, data); + validatePostData(data); + const transformedData = transformGeoData({ data } ); + const results = await dbClient.insert(lugaresCollection, transformedData); res.json({ data: results }); } catch (error) { console.error(error);