Skip to content

Commit 06bfa7c

Browse files
author
tsv2013
committed
Implemented no-sql CRUD adapter for MongoDB
1 parent 6bc7944 commit 06bfa7c

File tree

9 files changed

+77
-707
lines changed

9 files changed

+77
-707
lines changed

express-app/db-adapters/mongo.js

+18-14
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const fs = require("fs");
2+
const { MongoClient, ObjectId } = require('mongodb');
23
const NoSQLCRUDAdapter = require("./nosql-crud-adapter");
34
const SurveyStorage = require("./survey-storage");
45

@@ -14,25 +15,28 @@ const dbConfig = {
1415
: null
1516
};
1617

17-
const MongoClient = require('mongodb').MongoClient;
1818
const url = `mongodb://${dbConfig.user}:${dbConfig.password}@${dbConfig.host}:${dbConfig.port}/`;
19-
console.log(url);
19+
// console.log(url);
20+
const client = new MongoClient(url);
2021

2122
function MongoStorage(session) {
22-
function dbConnectFunction(callback) {
23-
MongoClient.connect(url, function(err, db) {
24-
if (err) throw err;
25-
var dbo = db.db(dbConfig.database);
26-
callback(dbo, () => {
27-
db.close();
28-
if(!process.env.DATABASE_LOG) {
29-
console.log(arguments[0]);
30-
console.log(arguments[1]);
31-
}
23+
function dbConnectFunction(dbCallback) {
24+
client.connect()
25+
.then(() => {
26+
const db = client.db(dbConfig.database);
27+
dbCallback(db, function() {
28+
if(!!process.env.DATABASE_LOG) {
29+
console.log(arguments[0]);
30+
console.log(arguments[1]);
31+
}
32+
client.close();
33+
});
34+
})
35+
.catch(() => {
36+
console.error(JSON.stringify(arguments));
3237
});
33-
});
3438
}
35-
const dbQueryAdapter = new NoSQLCRUDAdapter(dbConnectFunction);
39+
const dbQueryAdapter = new NoSQLCRUDAdapter(dbConnectFunction, () => new ObjectId().toString());
3640
return new SurveyStorage(dbQueryAdapter);
3741
}
3842

express-app/db-adapters/nosql-crud-adapter.js

+45-49
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,62 @@
1-
function NoSQLCRUDAdapter(dbConnectFunction) {
1+
function NoSQLCRUDAdapter(dbConnectFunction, getId) {
22
function getObjects(collectionName, filter, callback) {
33
filter = filter || [];
44
let query = {};
55
filter.forEach(fi => query[fi.name] = fi.value);
6-
dbConnectFunction((dbo, finalizeCallback) =>
7-
dbo.collection(collectionName).find(query).toArray((error, results) => {
8-
finalizeCallback();
9-
if (error) {
10-
throw error;
11-
}
12-
callback(results);
13-
})
6+
dbConnectFunction((db, finalizeCallback) => {
7+
db.collection(collectionName).find(query).toArray()
8+
.then((results) => {
9+
callback(results);
10+
finalizeCallback(results);
11+
})
12+
.catch(() => {
13+
console.error(JSON.stringify(arguments));
14+
});
15+
}
1416
);
1517
}
1618

17-
function deleteObject(tableName, idValue, callback) {
18-
const command = "DELETE FROM " + tableName + " WHERE id='" + idValue + "'";
19-
dbConnectFunction(command, (error, results) => {
20-
if (error) {
21-
throw error;
19+
function deleteObject(collectionName, idValue, callback) {
20+
dbConnectFunction((db, finalizeCallback) => {
21+
db.collection(collectionName).deleteMany({ id: idValue })
22+
.then((results) => {
23+
callback(results);
24+
finalizeCallback(results);
25+
})
26+
.catch(() => {
27+
console.error(JSON.stringify(arguments));
28+
});
2229
}
23-
callback(results);
24-
});
30+
);
2531
}
2632

27-
function createObject(tableName, object, callback) {
28-
const valueNames = [];
29-
const valueIndexes = [];
30-
const values = [];
31-
Object.keys(object).forEach((key, index) => {
32-
if(object[key] !== undefined) {
33-
valueNames.push(key);
34-
valueIndexes.push("$" + (index + 1));
35-
values.push(object[key]);
36-
}
37-
});
38-
const command = "INSERT INTO " + tableName + " (" + valueNames.join(", ") + ") VALUES (" + valueIndexes.join(", ") + ") RETURNING id";
39-
dbConnectFunction(command, values, (error, results) => {
40-
if (error) {
41-
throw error;
33+
function createObject(collectionName, object, callback) {
34+
object.id = object.id || getId();
35+
dbConnectFunction((db, finalizeCallback) => {
36+
db.collection(collectionName).insertOne(object)
37+
.then((results) => {
38+
callback(object.id);
39+
finalizeCallback(results);
40+
})
41+
.catch(() => {
42+
console.error(JSON.stringify(arguments));
43+
});
4244
}
43-
// console.log(JSON.stringify(results));
44-
callback(results.rows[0].id);
45-
});
45+
);
4646
}
4747

48-
function updateObject(tableName, object, callback) {
49-
const valueNames = [];
50-
const values = [];
51-
Object.keys(object).forEach((key, index) => {
52-
if(object[key] !== undefined) {
53-
valueNames.push(key + " = $" + (index + 1));
54-
values.push(object[key]);
55-
}
56-
});
57-
const command = "UPDATE " + tableName + " SET " + valueNames.join(", ") + " WHERE id = '" + object.id + "'";
58-
dbConnectFunction(command, values, (error, results) => {
59-
if (error) {
60-
throw error;
48+
function updateObject(collectionName, object, callback) {
49+
dbConnectFunction((db, finalizeCallback) => {
50+
db.collection(collectionName).updateOne({ id: object.id }, { $set: object })
51+
.then((results) => {
52+
callback(results);
53+
finalizeCallback(results);
54+
})
55+
.catch(() => {
56+
console.error(JSON.stringify(arguments));
57+
});
6158
}
62-
callback(object);
63-
});
59+
);
6460
}
6561

6662
return {

express-app/db-adapters/sql-crud-adapter.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ function SQLCRUDAdapter(queryExecutorFunction) {
33
filter = filter || [];
44
let where = "";
55
if(filter.length > 0) {
6-
where += " WHERE " + filter.map(fi => "" + fi.name + fi.op + fi.value).join(" AND ");
6+
where += " WHERE " + filter.map(fi => "" + fi.name + fi.op + "'" + fi.value + "'").join(" AND ");
77
}
88

99
const command = "SELECT * FROM " + tableName + where;

express-app/db-adapters/survey-storage.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ function SurveyStorage(dbQueryAdapter) {
2828
return {
2929
addSurvey: addSurvey,
3030
getSurvey: function (surveyId, callback) {
31-
dbQueryAdapter.retrieve("surveys", [{ name: "id", op: "=", value: "'" + surveyId + "'" }], function (results) { callback(results[0]); });
31+
dbQueryAdapter.retrieve("surveys", [{ name: "id", op: "=", value: surveyId }], function (results) { callback(results[0]); });
3232
},
3333
storeSurvey: function (id, name, json, callback) {
3434
dbQueryAdapter.update("surveys", { id: id, json: json }, function (results) { callback(results); });
@@ -41,7 +41,7 @@ function SurveyStorage(dbQueryAdapter) {
4141
},
4242
postResults: postResults,
4343
getResults: function (postId, callback) {
44-
dbQueryAdapter.retrieve("results", [{ name: "postid", op: "=", value: "'" + postId + "'" }], function (results) { callback({ id: postId, data: results.map(r => r.json)}); });
44+
dbQueryAdapter.retrieve("results", [{ name: "postid", op: "=", value: postId }], function (results) { callback({ id: postId, data: results.map(r => r.json)}); });
4545
},
4646
changeName: function (id, name, callback) {
4747
dbQueryAdapter.update("surveys", { id: id, name: name }, function (results) { callback(results); });

express-app/package-lock.json

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

express-app/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"name": "surveyjs-nodejs-postgres",
2+
"name": "surveyjs-nodejs-mongo",
33
"version": "0.1.0",
44
"description": "Sample NodeJS backend for SurveyJS: Survey Library and Survey Creator",
55
"main": "index.js",

0 commit comments

Comments
 (0)