Skip to content

Commit b6dd8c0

Browse files
committed
Split hello world "log" samples into separate samples, and added Cloud Functions Pub/Sub, Datastore, and GCS samples.
1 parent 92b9cb5 commit b6dd8c0

19 files changed

+1189
-65
lines changed

functions/datastore/README.md

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>
2+
3+
# Google Cloud Functions Cloud Datastore sample
4+
5+
This recipe shows you how to read and write an entity in Datastore from a Cloud Function.
6+
7+
View the [source code][code].
8+
9+
[code]: index.js
10+
11+
## Deploy and Test
12+
13+
1. Follow the [Cloud Functions quickstart guide](https://cloud.google.com/functions/quickstart) to setup Cloud Functions for your project.
14+
15+
1. Clone this repository:
16+
17+
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
18+
cd nodejs-docs-samples/functions/datastore
19+
20+
1. Create a Cloud Storage Bucket to stage our deployment:
21+
22+
gsutil mb gs://<your-bucket-name>
23+
24+
1. Ensure the Cloud Datastore API is enabled:
25+
26+
[Click here to enable the Cloud Datastore API](https://console.cloud.google.com/flows/enableapi?apiid=datastore.googleapis.com&redirect=https://github.com/GoogleCloudPlatform/nodejs-docs-samples/tree/master/functions/datastore)
27+
28+
1. Deploy the "ds-get" function with an HTTP trigger:
29+
30+
gcloud alpha functions deploy ds-get --bucket <your-bucket-name> --trigger-http --entry-point get
31+
32+
1. Deploy the "ds-set" function with an HTTP trigger:
33+
34+
gcloud alpha functions deploy ds-set --bucket <your-bucket-name> --trigger-http --entry-point set
35+
36+
1. Deploy the "ds-del" function with an HTTP trigger:
37+
38+
gcloud alpha functions deploy ds-del --bucket <your-bucket-name> --trigger-http --entry-point del
39+
40+
1. Call the "ds-set" function to create a new entity:
41+
42+
gcloud alpha functions call ds-set --data '{"kind":"gcf-test","key":"foobar","value":{"message": "Hello World!"}}'
43+
44+
1. Call the "ds-get" function to read the newly created entity:
45+
46+
gcloud alpha functions call ds-get --data '{"kind":"gcf-test","key":"foobar"}'
47+
48+
1. Call the "ds-del" function to delete the entity:
49+
50+
gcloud alpha functions call ds-del --data '{"kind":"gcf-test","key":"foobar"}'
51+
52+
1. Call the "ds-get" function again to verify it was deleted:
53+
54+
gcloud alpha functions call ds-get --data '{"kind":"gcf-test","key":"foobar"}'

functions/datastore/index.js

+154
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
// Copyright 2016, Google, Inc.
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
'use strict';
15+
16+
var gcloud = require('gcloud');
17+
18+
// Create a datastore client.
19+
var datastore = gcloud.datastore();
20+
21+
/**
22+
* Gets a Datastore key from the kind/key pair in the request.
23+
*
24+
* @param {Object} requestData Cloud Function request data.
25+
* @param {string} requestData.key Datastore key string.
26+
* @param {string} requestData.kind Datastore kind.
27+
* @returns {Object} Datastore key object.
28+
*/
29+
function getKeyFromRequestData (requestData) {
30+
if (!requestData.key) {
31+
throw new Error('Key not provided. Make sure you have a "key" property ' +
32+
'in your request');
33+
}
34+
35+
if (!requestData.kind) {
36+
throw new Error('Kind not provided. Make sure you have a "kind" property ' +
37+
'in your request');
38+
}
39+
40+
return datastore.key([requestData.kind, requestData.key]);
41+
}
42+
43+
/**
44+
* Creates and/or updates a record.
45+
*
46+
* @example
47+
* gcloud alpha functions call ds-set --data '{"kind":"gcf-test","key":"foobar","value":{"message": "Hello World!"}}'
48+
*
49+
* @param {Object} context Cloud Function context.
50+
* @param {Function} context.success Success callback.
51+
* @param {Function} context.failure Failure callback.
52+
* @param {Object} data Request data, in this case an object provided by the user.
53+
* @param {string} data.kind The Datastore kind of the data to save, e.g. "user".
54+
* @param {string} data.key Key at which to save the data, e.g. 5075192766267392.
55+
* @param {Object} data.value Value to save to Cloud Datastore, e.g. {"name":"John"}
56+
*/
57+
function set (context, data) {
58+
try {
59+
// The value contains a JSON document representing the entity we want to save
60+
if (!data.value) {
61+
throw new Error('Value not provided. Make sure you have a "value" ' +
62+
'property in your request');
63+
}
64+
65+
var key = getKeyFromRequestData(data);
66+
67+
return datastore.save({
68+
key: key,
69+
data: data.value
70+
}, function (err) {
71+
if (err) {
72+
console.error(err);
73+
return context.failure(err);
74+
}
75+
76+
return context.success('Entity saved');
77+
});
78+
} catch (err) {
79+
console.error(err);
80+
return context.failure(err.message);
81+
}
82+
}
83+
84+
/**
85+
* Retrieves a record.
86+
*
87+
* @example
88+
* gcloud alpha functions call ds-get --data '{"kind":"gcf-test","key":"foobar"}'
89+
*
90+
* @param {Object} context Cloud Function context.
91+
* @param {Function} context.success Success callback.
92+
* @param {Function} context.failure Failure callback.
93+
* @param {Object} data Request data, in this case an object provided by the user.
94+
* @param {string} data.kind The Datastore kind of the data to retrieve, e.g. "user".
95+
* @param {string} data.key Key at which to retrieve the data, e.g. 5075192766267392.
96+
*/
97+
function get (context, data) {
98+
try {
99+
var key = getKeyFromRequestData(data);
100+
101+
return datastore.get(key, function (err, entity) {
102+
if (err) {
103+
console.error(err);
104+
return context.failure(err);
105+
}
106+
107+
// The get operation will not fail for a non-existent entity, it just
108+
// returns null.
109+
if (!entity) {
110+
return context.failure('No entity found for key ' + key.path);
111+
}
112+
113+
return context.success(entity);
114+
});
115+
} catch (err) {
116+
console.error(err);
117+
return context.failure(err.message);
118+
}
119+
}
120+
121+
/**
122+
* Deletes a record.
123+
*
124+
* @example
125+
* gcloud alpha functions call ds-del --data '{"kind":"gcf-test","key":"foobar"}'
126+
*
127+
* @param {Object} context Cloud Function context.
128+
* @param {Function} context.success Success callback.
129+
* @param {Function} context.failure Failure callback.
130+
* @param {Object} data Request data, in this case an object provided by the user.
131+
* @param {string} data.kind The Datastore kind of the data to delete, e.g. "user".
132+
* @param {string} data.key Key at which to delete data, e.g. 5075192766267392.
133+
*/
134+
function del (context, data) {
135+
try {
136+
var key = getKeyFromRequestData(data);
137+
138+
return datastore.delete(key, function (err) {
139+
if (err) {
140+
console.error(err);
141+
return context.failure(err);
142+
}
143+
144+
return context.success('Entity deleted');
145+
});
146+
} catch (err) {
147+
console.error(err);
148+
return context.failure(err.message);
149+
}
150+
}
151+
152+
exports.set = set;
153+
exports.get = get;
154+
exports.del = del;

functions/datastore/package.json

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "nodejs-docs-samples-functions-datastore",
3+
"description": "Node.js samples found on https://cloud.google.com",
4+
"version": "0.0.1",
5+
"private": true,
6+
"license": "Apache Version 2.0",
7+
"author": "Google Inc.",
8+
"repository": {
9+
"type": "git",
10+
"url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
11+
},
12+
"dependencies": {
13+
"gcloud": "^0.35.0"
14+
}
15+
}

functions/gcs/README.md

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>
2+
3+
# Google Cloud Functions Cloud Storage sample
4+
5+
This recipe demonstrates how to load a file from Cloud Storage.
6+
7+
View the [source code][code].
8+
9+
[code]: index.js
10+
11+
## Deploy and Test
12+
13+
1. Follow the [Cloud Functions quickstart guide](https://cloud.google.com/functions/quickstart) to setup Cloud Functions for your project.
14+
15+
1. Clone this repository:
16+
17+
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
18+
cd nodejs-docs-samples/functions/gcs
19+
20+
1. Create a Cloud Storage Bucket to stage our deployment:
21+
22+
gsutil mb gs://<your-bucket-name>
23+
24+
1. Upload the sample file to the bucket:
25+
26+
gsutil cp sample.txt gs://<your-bucket-name>
27+
28+
1. Deploy the "wordCount" function with an HTTP trigger:
29+
30+
gcloud alpha functions deploy wordCount --bucket <your-bucket-name> --trigger-http --entry-point map
31+
32+
1. Call the "wordCount" function using the sample file:
33+
34+
gcloud alpha functions call wordCount --data '{"bucket":"<your-bucket-name>","file":"sample.txt"}'
35+
36+
You should see something like this in your console
37+
38+
The file sample.txt has 114 words

functions/gcs/index.js

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// Copyright 2016, Google, Inc.
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
'use strict';
15+
16+
var gcloud = require('gcloud');
17+
var readline = require('readline');
18+
19+
function getFileStream (bucketName, fileName) {
20+
if (!bucketName) {
21+
throw new Error('Bucket not provided. Make sure you have a ' +
22+
'"bucket" property in your request');
23+
}
24+
if (!fileName) {
25+
throw new Error('Filename not provided. Make sure you have a ' +
26+
'"file" property in your request');
27+
}
28+
29+
// Create a gcs client.
30+
var gcs = gcloud.storage();
31+
var bucket = gcs.bucket(bucketName);
32+
return bucket.file(fileName).createReadStream();
33+
}
34+
35+
/**
36+
* Reads file and responds with the number of words in the file.
37+
*
38+
* @example
39+
* gcloud alpha functions call wordCount --data '{"bucket":"<your-bucket-name>","file":"sample.txt"}'
40+
*
41+
* @param {Object} context Cloud Function context.
42+
* @param {Function} context.success Success callback.
43+
* @param {Function} context.failure Failure callback.
44+
* @param {Object} data Request data, in this case an object provided by the user.
45+
* @param {Object} data.bucket Name of a Cloud Storage bucket.
46+
* @param {Object} data.file Name of a file in the Cloud Storage bucket.
47+
*/
48+
function wordCount (context, data) {
49+
try {
50+
var count = 0;
51+
52+
// Use the linebyline module to read the stream line by line.
53+
var lineReader = readline.createInterface({
54+
input: getFileStream(data.bucket, data.file)
55+
});
56+
57+
lineReader.on('line', function (line) {
58+
count += line.trim().split(/\s+/).length;
59+
});
60+
61+
lineReader.on('close', function () {
62+
context.success('The file ' + data.file + ' has ' + count + ' words');
63+
});
64+
} catch (err) {
65+
context.failure(err.message);
66+
}
67+
}
68+
69+
exports.wordCount = wordCount;

functions/gcs/package.json

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "nodejs-docs-samples-functions-cloud-storage",
3+
"description": "Node.js samples found on https://cloud.google.com",
4+
"version": "0.0.1",
5+
"private": true,
6+
"license": "Apache Version 2.0",
7+
"author": "Google Inc.",
8+
"repository": {
9+
"type": "git",
10+
"url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
11+
},
12+
"dependencies": {
13+
"gcloud": "^0.35.0"
14+
}
15+
}

functions/gcs/sample.txt

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
Shall I compare thee to a summer's day?
2+
Thou art more lovely and more temperate:
3+
Rough winds do shake the darling buds of May,
4+
And summer's lease hath all too short a date:
5+
Sometime too hot the eye of heaven shines,
6+
And often is his gold complexion dimm'd;
7+
And every fair from fair sometime declines,
8+
By chance, or nature's changing course, untrimm'd;
9+
But thy eternal summer shall not fade
10+
Nor lose possession of that fair thou ow'st;
11+
Nor shall Death brag thou wander'st in his shade,
12+
When in eternal lines to time thou grow'st;
13+
So long as men can breathe or eyes can see,
14+
So long lives this, and this gives life to thee.

functions/log/index.js

-16
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,3 @@ exports.helloworld = function (context, data) {
1919
context.success();
2020
};
2121
// [END log]
22-
23-
exports.log = exports.helloworld;
24-
25-
// [START walkthrough_pubsub]
26-
exports.helloworld = function (context, data) {
27-
console.log('My GCF Function: ' + data.message);
28-
context.success();
29-
};
30-
// [END walkthrough_pubsub]
31-
32-
// [START walkthrough_http]
33-
exports.hellohttp = function (context, data) {
34-
// Use the success argument to send data back to the caller
35-
context.success('My GCF Function: ' + data.message);
36-
};
37-
// [END walkthrough_http]

0 commit comments

Comments
 (0)