forked from GoogleCloudPlatform/google-cloud-node-todos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
todos.js
115 lines (104 loc) · 2.59 KB
/
todos.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
'use strict';
var projectId = process.env.GAE_LONG_APP_ID || process.env.DATASET_ID;
if (!projectId) {
var MISSING_ID = [
'Cannot find your project ID. Please set an environment variable named ',
'"DATASET_ID", holding the ID of your project.'
].join('');
throw new Error(MISSING_ID);
}
var gcloud = require('gcloud')({
projectId: projectId,
credentials: require('./key.json')
});
var ds = gcloud.datastore.dataset();
var LIST_NAME = 'default-list';
function entityToTodo(item) {
var todo = item.data;
todo.id = item.key.path.pop();
return todo;
}
module.exports = {
delete: function(id, callback) {
ds.delete(ds.key(['TodoList', LIST_NAME, 'Todo', id]), function(err) {
callback(err || null);
});
},
deleteCompleted: function(callback) {
ds.runInTransaction(function(transaction, done) {
var q = ds.createQuery('Todo')
.hasAncestor(ds.key(['TodoList', LIST_NAME]))
.filter('completed =', true);
transaction.runQuery(q, function(err, items) {
if (err) {
transaction.rollback(done);
return;
}
var keys = items.map(function(todo) {
return todo.key;
});
transaction.delete(keys, function(err) {
if (err) {
transaction.rollback(done);
return;
}
done();
});
});
}, callback);
},
get: function(id, callback) {
ds.get(ds.key(['TodoList', LIST_NAME, 'Todo', id]), function(err, item) {
if (err) {
callback(err);
return;
}
if (!item) {
callback({
code: 404,
message: 'No matching entity was found.'
});
return;
}
callback(null, entityToTodo(item));
});
},
getAll: function(callback) {
var q = ds.createQuery('Todo')
.hasAncestor(ds.key(['TodoList', LIST_NAME]));
ds.runQuery(q, function(err, items) {
if (err) {
callback(err);
return;
}
callback(null, items.map(entityToTodo));
});
},
insert: function(data, callback) {
data.completed = false;
ds.save({
key: ds.key(['TodoList', LIST_NAME, 'Todo']),
data: data
}, function(err, key) {
if (err) {
callback(err);
return;
}
data.id = key.path.pop();
callback(null, data);
});
},
update: function(id, data, callback) {
ds.save({
key: ds.key(['TodoList', LIST_NAME, 'Todo', id]),
data: data
}, function(err) {
if (err) {
callback(err);
return;
}
data.id = id;
callback(null, data);
});
}
};