This commit is contained in:
Märt Kalmo 2017-03-27 14:58:24 +03:00
commit affc743063
5 changed files with 94 additions and 0 deletions

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
node_modules
bower_components
/.settings
/.classpath
/.project
/.idea
*.iml
*.log

25
dao.js Normal file
View File

@ -0,0 +1,25 @@
'use strict';
const mongodb = require('mongodb');
const ObjectID = require('mongodb').ObjectID;
const COLLECTION = 'test-collection';
class Dao {
connect(url) {
return mongodb.MongoClient.connect(url)
.then(db => this.db = db);
}
findAll() {
return this.db.collection(COLLECTION).find().toArray();
}
close() {
if (this.db) {
this.db.close();
}
}
}
module.exports=Dao;

26
mongo.js Normal file
View File

@ -0,0 +1,26 @@
'use strict';
const mongodb = require('mongodb');
const ObjectID = mongodb.ObjectID;
var url = 'mongodb://...';
// insert({ key: 'value1' });
// findAll().then(data => console.log(JSON.stringify(data)));
function insert(data) {
mongodb.MongoClient.connect(url).then(db => {
var c = db.collection('test-collection');
c.insertOne(data).then(() => db.close());
});
}
function findAll() {
return mongodb.MongoClient.connect(url).then(db => {
var c = db.collection('test-collection');
return c.find().toArray().then(data => {
db.close();
return data;
});
});
}

13
package.json Normal file
View File

@ -0,0 +1,13 @@
{
"name": "exback",
"version": "1.0.0",
"scripts": {
"start": "nodemon server.js"
},
"devDependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2",
"mongodb": "^2.2.25",
"nodemon": "^1.11.0"
}
}

20
server.js Normal file
View File

@ -0,0 +1,20 @@
'use strict';
const express = require('express');
const app = express();
app.get('/api/contacts', getContacts);
app.get('/api/contacts/:id', getContact);
app.listen(3000);
function getContacts(request, response) {
response.set('Content-Type', 'application/json');
response.end(JSON.stringify([{ id: 1 }, { id: 2 }]));
}
function getContact(request, response) {
var id = request.params.id;
response.set('Content-Type', 'application/json');
response.end(JSON.stringify({ id: id }));
}