Skip to content

Commit 70d9b39

Browse files
author
Ace Nassri
authored
Move GCF samples from docs into Github (#604)
* Add inline samples * Add getSignedUrl sample * Update tips region tags * Add retry samples * Fix comments * Add cached client library instance sample * Move existing + add new conceptual samples * Add conceptual samples, round 3 * Address comments * Address comments, round 2 * Add unit test for concepts samples * Clarify comments * Fix lint * Make comments consistent * Fix failing + add new tests * Don't run debug tests * Increment Node version
1 parent 0f57d22 commit 70d9b39

File tree

13 files changed

+749
-3
lines changed

13 files changed

+749
-3
lines changed

circle.yml

+9-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
machine:
2020
node:
21-
version: 6.12.3
21+
version: 6.14.1
2222

2323
# Use for broader build-related configuration
2424
general:
@@ -35,21 +35,25 @@ dependencies:
3535
- yarn install
3636
- yarn run lint
3737
- samples test install -l=functions/background
38+
- samples test install -l=functions/concepts
39+
- samples test install -l=functions/datastore
3840
- samples test install -l=functions/errorreporting
3941
- samples test install -l=functions/gcs
40-
- samples test install -l=functions/datastore
4142
- samples test install -l=functions/helloworld
43+
- samples test install -l=functions/http
4244
- samples test install -l=functions/imagemagick
4345
- samples test install -l=functions/log
4446
- samples test install -l=functions/ocr/app
4547
- samples test install -l=functions/pubsub
4648
- samples test install -l=functions/sendgrid
4749
- samples test install -l=functions/slack
4850
- samples test install -l=functions/spanner
51+
- samples test install -l=functions/tips
4952
- samples test install -l=functions/uuid
5053
cache_directories:
5154
- ~/.cache/yarn
5255
- functions/background/node_modules
56+
- functions/concepts/node_modules
5357
- functions/datastore/node_modules
5458
- functions/errorreporting/node_modules
5559
- functions/gcs/node_modules
@@ -62,6 +66,7 @@ dependencies:
6266
- functions/sendgrid/node_modules
6367
- functions/slack/node_modules
6468
- functions/spanner/node_modules
69+
- functions/tips/node_modules
6570
- functions/uuid/node_modules
6671

6772
# Run your tests
@@ -70,6 +75,7 @@ test:
7075
- functions-emulator config set projectId $GCLOUD_PROJECT && functions-emulator start && cd functions/datastore && npm run system-test && functions-emulator stop
7176
- functions-emulator config set projectId $GCLOUD_PROJECT && functions-emulator start && cd functions/helloworld && npm run test && functions-emulator stop
7277
- samples test run --cmd nyc -- --cache ava --verbose -T 30s 'functions/background/test/**/*.test.js'
78+
- samples test run --cmd nyc -- --cache ava --verbose -T 30s 'functions/concepts/test/**/*.test.js'
7379
- samples test run --cmd nyc -- --cache ava --verbose -T 30s 'functions/gcs/test/**/*.test.js'
7480
- samples test run --cmd nyc -- --cache ava --verbose -T 30s 'functions/http/test/**/*.test.js'
7581
- samples test run --cmd nyc -- --cache ava --verbose -T 30s 'functions/imagemagick/test/**/*.test.js'
@@ -79,6 +85,7 @@ test:
7985
- samples test run --cmd nyc -- --cache ava --verbose -T 30s 'functions/slack/test/**/*.test.js'
8086
- samples test run --cmd nyc -- --cache ava --verbose -T 30s 'functions/spanner/test/**/*.test.js'
8187
- samples test run --cmd nyc -- --cache ava --verbose -T 30s 'functions/uuid/test/**/*.test.js'
88+
- samples test run --cmd nyc -- --cache ava --verbose -T 30s 'functions/tips/test/**/*.test.js'
8289
post:
8390
- nyc report --reporter=lcov > coverage.lcov && codecov || true
8491
deployment:

functions/concepts/index.js

+175
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
/**
2+
* Copyright 2018, Google, Inc.
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
'use strict';
17+
18+
/**
19+
* HTTP Cloud Function that demonstrates
20+
* how to catch errors of different types.
21+
*
22+
* @param {Object} req Cloud Function request context.
23+
* @param {Object} req.body Cloud Function request context body.
24+
* @param {String} req.body.topic The Cloud Pub/Sub topic to publish to.
25+
* @param {Object} res Cloud Function response context.
26+
*/
27+
exports.errorTypes = (req, res) => {
28+
// [START functions_concepts_error_object]
29+
try {
30+
// Throw an Error object (to simulate a GCP API failure)
31+
throw new Error('Error object!');
32+
} catch (err) {
33+
// err is already an Error object
34+
console.error(err);
35+
}
36+
// [END functions_concepts_error_object]
37+
38+
const someCondition = !!req.body.throwAsString;
39+
40+
/* eslint-disable no-throw-literal */
41+
// [START functions_concepts_error_unknown]
42+
try {
43+
// Throw an unknown error type
44+
if (someCondition) {
45+
throw 'Error string!';
46+
} else {
47+
throw new Error('Error object!');
48+
}
49+
} catch (err) {
50+
// Determine the error type
51+
if (err instanceof Error) {
52+
console.error(err);
53+
} else {
54+
console.error(new Error(err));
55+
}
56+
}
57+
// [END functions_concepts_error_unknown]
58+
/* eslint-enable no-throw-literal */
59+
60+
res.end();
61+
};
62+
63+
// [START functions_concepts_stateless]
64+
// Global variable, but only shared within function instance.
65+
let count = 0;
66+
67+
/**
68+
* HTTP Cloud Function that counts how many times
69+
* it is executed within a specific instance.
70+
*
71+
* @param {Object} req Cloud Function request context.
72+
* @param {Object} res Cloud Function response context.
73+
*/
74+
exports.executionCount = (req, res) => {
75+
count++;
76+
77+
// Note: the total function invocation count across
78+
// all instances may not be equal to this value!
79+
res.send(`Instance execution count: ${count}`);
80+
};
81+
// [END functions_concepts_stateless]
82+
83+
// [START functions_concepts_after_response]
84+
/**
85+
* HTTP Cloud Function that may not completely
86+
* execute due to early HTTP response
87+
*
88+
* @param {Object} req Cloud Function request context.
89+
* @param {Object} res Cloud Function response context.
90+
*/
91+
exports.afterResponse = (req, res) => {
92+
res.end();
93+
94+
// This statement may not execute
95+
console.log('Function complete!');
96+
};
97+
// [END functions_concepts_after_response]
98+
99+
// [START functions_concepts_after_timeout]
100+
/**
101+
* HTTP Cloud Function that may not completely
102+
* execute due to function execution timeout
103+
*
104+
* @param {Object} req Cloud Function request context.
105+
* @param {Object} res Cloud Function response context.
106+
*/
107+
exports.afterTimeout = (req, res) => {
108+
setTimeout(() => {
109+
// May not execute if function's timeout is <2 minutes
110+
console.log('Function running...');
111+
res.end();
112+
}, 120000); // 2 minute delay
113+
};
114+
// [END functions_concepts_after_timeout]
115+
116+
// [START functions_concepts_filesystem]
117+
const fs = require('fs');
118+
119+
/**
120+
* HTTP Cloud Function that lists files in the function directory
121+
*
122+
* @param {Object} req Cloud Function request context.
123+
* @param {Object} res Cloud Function response context.
124+
*/
125+
exports.listFiles = (req, res) => {
126+
fs.readdir(__dirname, (err, files) => {
127+
if (err) {
128+
console.error(err);
129+
res.sendStatus(500);
130+
} else {
131+
console.log('Files', files);
132+
res.sendStatus(200);
133+
}
134+
});
135+
};
136+
// [END functions_concepts_filesystem]
137+
138+
// [START functions_concepts_modules]
139+
const path = require('path');
140+
const loadedModule = require(path.join(__dirname, 'loadable.js'));
141+
142+
/**
143+
* HTTP Cloud Function that runs a function loaded from another Node.js file
144+
*
145+
* @param {Object} req Cloud Function request context.
146+
* @param {Object} res Cloud Function response context.
147+
*/
148+
exports.runLoadedModule = (req, res) => {
149+
console.log(`Loaded function from file ${loadedModule.getFileName()}`);
150+
res.end();
151+
};
152+
// [END functions_concepts_modules]
153+
154+
// [START functions_concepts_requests]
155+
const request = require('request');
156+
157+
/**
158+
* HTTP Cloud Function that makes an HTTP request
159+
*
160+
* @param {Object} req Cloud Function request context.
161+
* @param {Object} res Cloud Function response context.
162+
*/
163+
exports.makeRequest = (req, res) => {
164+
// The URL to send the request to
165+
const url = 'https://example.com';
166+
167+
request(url, (err, response) => {
168+
if (!err && response.statusCode === 200) {
169+
res.sendStatus(200);
170+
} else {
171+
res.sendStatus(500);
172+
}
173+
});
174+
};
175+
// [END functions_concepts_requests]

functions/concepts/loadable.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Copyright 2018, Google, Inc.
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
'use strict';
17+
18+
// [START functions_sample_module]
19+
exports.getFileName = () => {
20+
return __filename;
21+
};
22+
// [END functions_sample_module]

functions/concepts/package.json

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"name": "nodejs-docs-samples-functions-concepts",
3+
"version": "0.0.1",
4+
"private": true,
5+
"license": "Apache-2.0",
6+
"author": "Google Inc.",
7+
"repository": {
8+
"type": "git",
9+
"url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
10+
},
11+
"engines": {
12+
"node": ">=4.3.2"
13+
},
14+
"scripts": {
15+
"lint": "repo-tools lint"
16+
},
17+
"dependencies": {
18+
"request": "^2.85.0"
19+
},
20+
"devDependencies": {
21+
"@google-cloud/nodejs-repo-tools": "^2.2.5",
22+
"ava": "^0.25.0",
23+
"sinon": "^4.5.0",
24+
"supertest": "^3.0.0"
25+
}
26+
}

functions/concepts/test/index.test.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Copyright 2018, Google, Inc.
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
'use strict';
17+
18+
const sinon = require(`sinon`);
19+
const test = require(`ava`);
20+
const tools = require(`@google-cloud/nodejs-repo-tools`);
21+
22+
const sample = require(`../`);
23+
24+
test.beforeEach(tools.stubConsole);
25+
test.afterEach.always(tools.restoreConsole);
26+
27+
test(`should demonstrate error type behavior`, (t) => {
28+
const objError = new Error('Error object!');
29+
const strError = new Error('Error string!');
30+
31+
const req = { body:
32+
{ throwAsString: true }
33+
};
34+
const res = { end: sinon.stub() };
35+
36+
// Test throwing both objects and strings
37+
sample.errorTypes(req, res);
38+
t.deepEqual(console.error.getCall(0).args, [objError]);
39+
t.deepEqual(console.error.getCall(1).args, [strError]);
40+
41+
// Test throwing objects only
42+
req.body.throwAsString = false;
43+
sample.errorTypes(req, res);
44+
t.deepEqual(console.error.getCall(2).args, [objError]);
45+
t.deepEqual(console.error.getCall(3).args, [objError]);
46+
});

functions/helloworld/.gcloudignore

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# This file specifies files that are *not* uploaded to Google Cloud Platform
2+
# using gcloud. It follows the same syntax as .gitignore, with the addition of
3+
# "#!include" directives (which insert the entries of the given .gitignore-style
4+
# file at that point).
5+
#
6+
# For more information, run:
7+
# $ gcloud topic gcloudignore
8+
#
9+
.gcloudignore
10+
# If you would like to upload your .git directory, .gitignore file or files
11+
# from your .gitignore file, remove the corresponding line
12+
# below:
13+
.git
14+
.gitignore
15+
16+
node_modules

functions/helloworld/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Copyright 2016, Google, Inc.
2+
* Copyright 2018, Google, Inc.
33
* Licensed under the Apache License, Version 2.0 (the "License");
44
* you may not use this file except in compliance with the License.
55
* You may obtain a copy of the License at

0 commit comments

Comments
 (0)