From d1baa61f61ade0c171305ab32862af9ac1090e8f Mon Sep 17 00:00:00 2001 From: Diego Garcia Date: Sat, 13 Apr 2019 17:38:49 -0700 Subject: [PATCH] Adding Lugares API --- README.md | 24 ++++++++++++++++++++++++ lib/lugares-client.js | 36 ++++++++++++++++++++++++++++++++++++ routes/index.js | 20 ++++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 lib/lugares-client.js diff --git a/README.md b/README.md index 4abb103..2368697 100644 --- a/README.md +++ b/README.md @@ -100,3 +100,27 @@ Eg schema type: '' } ``` + + +__lugares:__ collection for places/landmarks + +- name: landmark name. +- attributes: JSON field of landmark atteributes. Eg. Hospital Type +- location: GeoJSON field of point type. +- created_at: date the data is inserted/created +- type: the type of the place. Eg. "hospital", "school" + +Eg schema + +``` +{ + location: { + type: "point", + coordinates: [ 40, 5 ] + }, + name: '', + attributes: '', + create_at: '2019-01-01 01:00:00', + type: '' +} +``` diff --git a/lib/lugares-client.js b/lib/lugares-client.js new file mode 100644 index 0000000..5fcb8a9 --- /dev/null +++ b/lib/lugares-client.js @@ -0,0 +1,36 @@ +const MongoClient = require('mongodb').MongoClient; + +class LugaresClient { + constructor(db) { + this.db = db; + } + async insert(data) { + try { + if(Array.isArray(data)) { + return await this.db.collection('lugares').insertMany(data); + } + return await this.db.collection('lugares').insertOne(data); + } catch(error) { + throw error; + } + } + async find(query={}) { + try { + return await this.db.collection('lugares').find(query).toArray(); + } catch (error) { + throw error; + } + } +} + +async function getLugaresDBClient() { + try { + const client = new MongoClient(process.env.MONGODB_URI); + await client.connect(); + return new LugaresClient(client.db()); + } catch(error) { + throw error; + } +} + +module.exports = getLugaresDBClient; \ No newline at end of file diff --git a/routes/index.js b/routes/index.js index c2c3427..8f73d6f 100644 --- a/routes/index.js +++ b/routes/index.js @@ -27,5 +27,25 @@ router.post('/apagon', async (req, res, next) => { } }); +// API routes +router.get('/lugar', async (req, res, next) => { + const dbClient = await getLugaresDBClient(); + const results = await dbClient.find(); + + res.json(results); +}); + + +router.post('/lugar', async (req, res, next) => { + const dbClient = await getLugaresDBClient(); + const data = req.body; + try { + const results = await dbClient.insert(data); + res.json(results); + } catch (error) { + console.error(error); + } +}); + module.exports = router;