Add dao support to express

This commit is contained in:
Arti Zirk 2017-05-11 11:36:13 +03:00
parent 002e0c079f
commit 8ce91cca9b
2 changed files with 35 additions and 5 deletions

16
dao.js
View File

@ -2,7 +2,7 @@
const mongodb = require('mongodb'); const mongodb = require('mongodb');
const ObjectID = require('mongodb').ObjectID; const ObjectID = require('mongodb').ObjectID;
const COLLECTION = 'test-collection'; const COLLECTION = 'contacts';
class Dao { class Dao {
@ -15,6 +15,18 @@ class Dao {
return this.db.collection(COLLECTION).find().toArray(); 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() { close() {
if (this.db) { if (this.db) {
this.db.close(); this.db.close();
@ -22,4 +34,4 @@ class Dao {
} }
} }
module.exports=Dao; module.exports = Dao;

View File

@ -2,19 +2,37 @@
const express = require('express'); const express = require('express');
const app = 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', getContacts);
app.get('/api/contacts/:id', getContact); app.get('/api/contacts/:id', getContact);
app.listen(3000); var dao = new Dao();
dao.connect(url).then(() => {
app.listen(3000);
})
function getContacts(request, response) { function getContacts(request, response) {
response.set('Content-Type', 'application/json'); 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) { function getContact(request, response) {
var id = request.params.id; var id = request.params.id;
response.set('Content-Type', 'application/json'); 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);
})
} }