-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposts.js
More file actions
90 lines (84 loc) · 2.26 KB
/
posts.js
File metadata and controls
90 lines (84 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
const url = "mongodb://localhost:27017/codebase";
// get the database object
var db=null;
MongoClient.connect(url)
.then(function callback(client){db=client.db("codebase")})
.catch((err)=>{throw err});
// returns a Promise that resolves when condition evaluates to non falsy value
function promiseWhen(condition, timeout){
if(!timeout){
timeout = 2000;
}
return new Promise((resolve, reject)=>{
setTimeout(()=>reject(new Error("Promise when expired.")), timeout);// reject promise if given timeout is exceeded
function loop(){
if(condition()){//check condition
resolve();
} else {
setTimeout(loop,0);
}
}
setTimeout(loop,0);
});
}
exports.create=(author, title, content, language, tags)=>{
return new Promise(async (resolve, reject)=>{
try {
await promiseWhen(()=>db);
var id = (await db.collection("posts").insertOne(
{"author" : author, "title" : title, "content" : content, "language" : language, "tags": tags})).insertedId;
resolve(id);
} catch(err){
reject(err);
}
});
}
exports.edit=(id, author, title, content, language, tags)=>{
return new Promise(async (resolve, reject)=>{
try {
await promiseWhen(()=>db);
resolve(await db.collection("posts").updateOne(
{"_id" : ObjectId(id)},
{$set : {"author" : author, "title" : title, "content" : content, "language" : language, "tags": tags}}
));
} catch(err){
reject(err);
}
});
}
exports.remove=(id)=>{
return new Promise(async (resolve, reject)=>{
try {
await promiseWhen(()=>db);
await db.collection("posts").remove({"_id" : ObjectId(id)});
resolve();
} catch(err){
reject(err);
}
});
}
exports.get=(id)=>{
return new Promise(async (resolve, reject)=>{
try {
await promiseWhen(()=>db);
resolve((await db.collection("posts").findOne(
{"_id" : ObjectId(id)}
)));
} catch(err){
reject(err);
}
});
}
exports.all=()=>{
return new Promise((resolve, reject)=>{
promiseWhen(()=>db)
.then(()=>{
db.collection("posts").find({}).toArray()
.then(resolve)
.catch(reject);
})
.catch(reject);
});
}