Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrating TODOs sample to gcloud #46

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 54 additions & 147 deletions nodejs/demos/todos/todo.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#! /usr/bin/env node
//
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -13,187 +11,96 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
var googleapis = require('googleapis'),
authclient = new googleapis.OAuth2Client(),
datasetId = 'gcd-codelab',
compute = new googleapis.auth.Compute(),
datastore = null,
todoListName = null;

// See https://github.com/GoogleCloudPlatform/gcloud-node#elsewhere
// to configure dataset ID and key filename.
var DATASET_ID = 'gcd-codelab',
KEY_FILENAME = '/path/to/key/file.json';

var gcloud = require('gcloud'),
datastore = gcloud.datastore;

var usage = 'usage todo.js <todolist> <add|get|del|edit|ls|archive> [todo-title|todo-id]';
compute.authorize(function(err, result) {
console.assert(!err, err);
googleapis.discover('datastore', 'v1beta1')
.withAuthClient(compute)
.execute(function(err, client) {
datastore = client.datastore.datasets;
todoListName = process.argv[2];
var cmd = process.argv[3];
console.assert(todoListName && cmd && commands[cmd], usage);
commands[cmd].apply(commands, process.argv.slice(4))
});
var cmd = process.argv[3];
todoListName = process.argv[2];

console.assert(todoListName && cmd && commands[cmd], usage);
commands[cmd].apply(commands, process.argv.slice(4));

var ds = gcloud.datastore.dataset({
projectId: DATASET_ID,
keyFilename: KEY_FILENAME
});

var commands = {
// level 0
add: function(title) {
datastore.blindWrite({
datasetId: datasetId,
mutation: {
insertAutoId: [{
key: {
path: [{ kind: 'TodoList', name: todoListName },
{ kind: 'Todo' }]
},
properties: {
title: { values: [{ stringValue: title }] },
completed: { values: [{ booleanValue: false }] }
}
}]
}
}).execute(function(err, result) {
ds.save({
key: datastore.key('TodoList', todoListName, 'Todo', null),
data: { title: title, completed: false }
}, function(err, key) {
console.assert(!err, err);
var key = result.mutationResult.insertAutoIdKeys[0];
console.log('%d: TODO %s', key.path[1].id, title);
});
console.log('Added TODO %s', title);
});
},
get: function(id, callback) {
datastore.lookup({
datasetId: datasetId,
keys: [{
path: [{ kind: 'TodoList', name: todoListName},
{ kind: 'Todo', id: id }]
}]
}).execute(function(err, result) {
var key = datastore.key('TodoList', todoListName, 'Todo', id);
ds.get(key, function(err, obj) {
console.assert(!err, err);
console.assert(!result.missing, 'todo %d: not found', id);
var entity = result.found[0].entity;
var title = entity.properties.title.values[0].stringValue;
var completed = entity.properties.completed.values[0].booleanValue == true;
if (callback) {
callback(err, id, title, completed);
} else {
console.log('%d: %s %s', id, completed && 'DONE' || 'TODO', title);
}
console.log('%d: %s %s', id, obj.data.completed && 'DONE' || 'TODO', obj.data.title);
});
},
// level 1
del: function(id) {
datastore.blindWrite({
datasetId: datasetId,
mutation: {
delete: [{
path: [{ kind: 'TodoList', name: todoListName },
{ kind: 'Todo', id: id }]
}]
}
}).execute(function(err, result) {
var key = datastore.key('TodoList', todoListName, 'Todo', id);
ds.delete(key, function(err) {
console.assert(!err, err);
console.log('%d: DEL', id);
});
},
// level 2
edit: function(id, title, completed) {
completed = completed === 'true';
datastore.blindWrite({
datasetId: datasetId,
mutation: {
update: [{
key: {
path: [{ kind: 'TodoList', name: todoListName },
{ kind: 'Todo', id: id } ]
},
properties: {
title: { values: [{ stringValue: title }] },
completed: { values: [{ booleanValue: completed }] }
}
}]
}
}).execute(function(err, result) {
ds.save({
key: datastore.key('TodoList', todoListName, 'Todo', id),
data: { title: title, completed: completed }
}, function(err, key) {
console.assert(!err, err);
console.log('%d: %s %s', id, completed && 'DONE' || 'TODO', title);
});
},
ls: function() {
datastore.runQuery({
datasetId: datasetId,
query: {
kinds: [{ name: 'Todo' }],
filter: {
propertyFilter: {
property: { name: '__key__' },
operator: 'hasAncestor',
value: {
keyValue: {
path: [{ kind: 'TodoList', name: todoListName }]
}
}
}
}
}
}).execute(function(err, result) {
var entityResults = result.batch.entityResults || [];
entityResults.forEach(function(entityResult) {
var entity = entityResult.entity;
var id = entity.key.path[1].id;
var properties = entity.properties;
var title = properties.title.values[0].stringValue;
var completed = properties.completed.values[0].booleanValue == true;
console.log('%d: %s %s', id, completed && 'DONE' || 'TODO', title);
var q = ds.createQuery('Todo')
.hasAncestor(datastore.key('TodoList', todoListName));
ds.runQuery(q, function(err, items) {
console.assert(!err, err);
items.forEach(function(item) {
console.log('%d: %s %s', id, item.data.completed && 'DONE' || 'TODO', item.title);
});

});
},
// level 3
archive: function() {
datastore.beginTransaction({
datasetId: datasetId
}).execute(function(err, result) {
var tx = result.transaction;
datastore.runQuery({
datasetId: datasetId,
readOptions: { transaction: tx },
query: {
kinds: [{ name: 'Todo' }],
filter: {
compositeFilter: {
operator: 'and',
filters: [{
propertyFilter: {
property: { name: '__key__' },
operator: 'hasAncestor',
value: { keyValue: {
path: [{ kind: 'TodoList', name: todoListName }]
}}
}
}, {
propertyFilter: {
property: { name: 'completed' },
operator: 'equal',
value: { booleanValue: true }
}
}]
}
}
// Deletes completed todos
ds.transaction(function(t, done) {
t.runQuery(q, function(err, items) {
if (err) {
t.rollback(done);
return;
}
}).execute(function(err, result) {
var keys = [];
var entityResults = result.batch.entityResults || [];
entityResults.forEach(function(entityResult) {
keys.push(entityResult.entity.key);
var keys = (items || []).map(function(item) {
return item.key;
});
datastore.commit({
datasetId: datasetId,
transaction: tx,
mutation: { delete: keys }
}).execute(function(err, result) {
console.assert(!err, err);
keys.forEach(function(key) {
console.log('%d: DEL', key.path[1].id);
});
t.delete(keys, function(err) {
if (err) {
t.rollback(done);
return;
}
// auto commits if no error.
});
});
}, function(err) {
console.assert(!err, err);
});
}
};