From 8ce91cca9b9c4d2637850f5f19fb6e6122ddfbd5 Mon Sep 17 00:00:00 2001 From: Arti Zirk Date: Thu, 11 May 2017 11:36:13 +0300 Subject: [PATCH] Add dao support to express --- dao.js | 16 ++++++++++++++-- server.js | 24 +++++++++++++++++++++--- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/dao.js b/dao.js index e6a7818..182e3b0 100644 --- a/dao.js +++ b/dao.js @@ -2,7 +2,7 @@ const mongodb = require('mongodb'); const ObjectID = require('mongodb').ObjectID; -const COLLECTION = 'test-collection'; +const COLLECTION = 'contacts'; class Dao { @@ -15,6 +15,18 @@ class Dao { return this.db.collection(COLLECTION).find().toArray(); } + findById(id) { + id = new ObjectID(id); + return this.db.collection(COLLECTION).findOne({_id:id}); + } + + update(id, data) { + id = new ObjectID(id); + data._id = id + return this.db.collection(COLLECTION) + .updateOne({_id:id}, data); + } + close() { if (this.db) { this.db.close(); @@ -22,4 +34,4 @@ class Dao { } } -module.exports=Dao; +module.exports = Dao; diff --git a/server.js b/server.js index 21dbefc..4b92285 100644 --- a/server.js +++ b/server.js @@ -2,19 +2,37 @@ const express = require('express'); const app = express(); +const Dao = require('./dao.js'); + +var url = 'mongodb://i399:salakala@ds137191.mlab.com:37191/i399'; app.get('/api/contacts', getContacts); app.get('/api/contacts/:id', getContact); -app.listen(3000); +var dao = new Dao(); +dao.connect(url).then(() => { + app.listen(3000); +}) function getContacts(request, response) { response.set('Content-Type', 'application/json'); - response.end(JSON.stringify([{ id: 1 }, { id: 2 }])); + dao.findAll().then(data => { + response.end(JSON.stringify(data)); + }).catch(error => { + console.log(error); + response.end("error"+error); + }) } function getContact(request, response) { var id = request.params.id; response.set('Content-Type', 'application/json'); - response.end(JSON.stringify({ id: id })); + dao.findById(id).then(data => { + response.end(JSON.stringify(data)); + }).catch(error => { + console.log(error); + response.end("error"+error); + }) + + }