From bdbf4039f8d3a075a812103b56fb596be10a5627 Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 18 Sep 2019 11:52:37 -0700 Subject: [PATCH 01/36] Automated lint fixes --- .eslintrc.yml | 2 +- cloud-sql/mysql/mysql/server.js | 2 +- cloud-sql/postgres/knex/server.js | 2 +- functions/billing/index.js | 2 +- functions/scheduleinstance/index.js | 4 ++-- functions/tokenservice/functions/index.js | 5 ++--- iot/http_example/cloudiot_http_example.js | 4 ++-- 7 files changed, 10 insertions(+), 11 deletions(-) diff --git a/.eslintrc.yml b/.eslintrc.yml index 15498767d0..06f3e9f4b7 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -27,6 +27,6 @@ rules: prefer-destructuring: warn prefer-template: warn func-style: - - 1 + - error - expression - allowArrowFunctions: true diff --git a/cloud-sql/mysql/mysql/server.js b/cloud-sql/mysql/mysql/server.js index 4681af584b..774a0f5976 100644 --- a/cloud-sql/mysql/mysql/server.js +++ b/cloud-sql/mysql/mysql/server.js @@ -156,7 +156,7 @@ app.post('/', async (req, res) => { res .status(200) - .send('Successfully voted for ' + team + ' at ' + timestamp) + .send(`Successfully voted for ${team} at ${timestamp}`) .end(); }); diff --git a/cloud-sql/postgres/knex/server.js b/cloud-sql/postgres/knex/server.js index c58d08e48c..e99361e110 100644 --- a/cloud-sql/postgres/knex/server.js +++ b/cloud-sql/postgres/knex/server.js @@ -212,7 +212,7 @@ app.post('/', async (req, res) => { try { await insertVote(knex, vote); } catch (err) { - logger.error('Error while attempting to submit vote:' + err); + logger.error(`Error while attempting to submit vote:${err}`); res .status(500) .send('Unable to cast vote; see logs for more details.') diff --git a/functions/billing/index.js b/functions/billing/index.js index 9be57c4ae3..4cdc28ecc8 100644 --- a/functions/billing/index.js +++ b/functions/billing/index.js @@ -187,7 +187,7 @@ const _stopInstances = async (projectId, zone, instanceNames) => { instance: instanceName, }) .then(res => { - console.log('Instance stopped successfully: ' + instanceName); + console.log(`Instance stopped successfully: ${instanceName}`); return res.data; }); }) diff --git a/functions/scheduleinstance/index.js b/functions/scheduleinstance/index.js index f30e567f00..03e8470b2e 100644 --- a/functions/scheduleinstance/index.js +++ b/functions/scheduleinstance/index.js @@ -51,7 +51,7 @@ exports.startInstancePubSub = (event, context, callback) => { }) .then(() => { // Operation complete. Instance successfully started. - const message = 'Successfully started instance ' + instance.name; + const message = `Successfully started instance ${instance.name}`; console.log(message); callback(null, message); }) @@ -101,7 +101,7 @@ exports.stopInstancePubSub = (event, context, callback) => { }) .then(() => { // Operation complete. Instance successfully stopped. - const message = 'Successfully stopped instance ' + instance.name; + const message = `Successfully stopped instance ${instance.name}`; console.log(message); callback(null, message); }) diff --git a/functions/tokenservice/functions/index.js b/functions/tokenservice/functions/index.js index cd9feff53f..549f105854 100644 --- a/functions/tokenservice/functions/index.js +++ b/functions/tokenservice/functions/index.js @@ -49,8 +49,7 @@ function generateAccessToken( method: 'POST', headers: { // Set Service Account Credentials - Authorization: - serviceAccountTokenType + ' ' + serviceAccountAccessToken, + Authorization: `${serviceAccountTokenType} ${serviceAccountAccessToken}`, }, }; @@ -120,7 +119,7 @@ function retrieveCredentials(context) { }); get_req.on('error', e => { //console.log('Error retrieving credentials', e.message); - return 'Error retrieving token' + e.message; + return `Error retrieving token${e.message}`; }); get_req.end(); }); diff --git a/iot/http_example/cloudiot_http_example.js b/iot/http_example/cloudiot_http_example.js index de2d4103f2..0dbba3d2ba 100644 --- a/iot/http_example/cloudiot_http_example.js +++ b/iot/http_example/cloudiot_http_example.js @@ -174,7 +174,7 @@ function publishAsync(authToken, messageCount, numMessages) { if (error) { console.error('Received error: ', error); } else if (response.body.error) { - console.error('Received error: ' + JSON.stringify(response.body.error)); + console.error(`Received error: ${JSON.stringify(response.body.error)}`); } else { console.log('Message sent.'); } @@ -205,7 +205,7 @@ function getConfig(authToken, version) { console.log(`Getting config from URL: ${urlBase}`); const options = { - url: urlBase + '/config?local_version=' + version, + url: `${urlBase}/config?local_version=${version}`, headers: { authorization: `Bearer ${authToken}`, 'content-type': 'application/json', From 78705d95030480a3e8a5bd1635fbbb98caa16ed4 Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 18 Sep 2019 11:52:52 -0700 Subject: [PATCH 02/36] Lint: switch WARNINGs to ERRORs --- .eslintrc.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.eslintrc.yml b/.eslintrc.yml index 06f3e9f4b7..d41bd8a48f 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -20,12 +20,12 @@ rules: prefer-const: error no-var: error prefer-arrow-callback: error - no-throw-literal: warn - require-await: warn - promise/prefer-await-to-then: warn - promise/no-nesting: warn - prefer-destructuring: warn - prefer-template: warn + no-throw-literal: error + require-await: error + promise/prefer-await-to-then: error + promise/no-nesting: error + prefer-destructuring: error + prefer-template: error func-style: - error - expression From 6ca6e7519ed9e34c2e9581a975846d5081ebae8a Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 18 Sep 2019 11:54:58 -0700 Subject: [PATCH 03/36] Fix lint: cloudsql --- cloud-sql/postgres/knex/server.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/cloud-sql/postgres/knex/server.js b/cloud-sql/postgres/knex/server.js index e99361e110..9ce632c1f6 100644 --- a/cloud-sql/postgres/knex/server.js +++ b/cloud-sql/postgres/knex/server.js @@ -47,9 +47,7 @@ const logger = winston.createLogger({ // [START cloud_sql_postgres_connection_pool] // Initialize Knex, a Node.js SQL query builder library with built-in connection pooling. -const knex = connect(); - -function connect() { +const connect = () => { // Configure which instance and what database user to connect with. // Remember - storing secrets in plaintext is potentially unsafe. Consider using // something like https://cloud.google.com/kms/ to help keep secrets secret. @@ -101,8 +99,10 @@ function connect() { // [END_EXCLUDE] return knex; - // [END cloud_sql_postgres_connection_pool] -} +}; + +const knex = connect(); +// [END cloud_sql_postgres_connection_pool] // [START cloud_sql_example_statement] /** @@ -112,13 +112,13 @@ function connect() { * @param {object} vote The vote record to insert. * @returns {Promise} */ -async function insertVote(knex, vote) { +const insertVote = async (knex, vote) => { try { return await knex('votes').insert(vote); } catch (err) { throw Error(err); } -} +}; // [END cloud_sql_example_statement] /** @@ -127,13 +127,13 @@ async function insertVote(knex, vote) { * @param {object} knex The Knex connection object. * @returns {Promise} */ -async function getVotes(knex) { +const getVotes = async knex => { return await knex .select('candidate', 'time_cast') .from('votes') .orderBy('time_cast', 'desc') .limit(5); -} +}; /** * Retrieve the total count of records for a given candidate @@ -143,11 +143,11 @@ async function getVotes(knex) { * @param {object} candidate The candidate for which to get the total vote count * @returns {Promise} */ -async function getVoteCount(knex, candidate) { +const getVoteCount = async (knex, candidate) => { return await knex('votes') .count('vote_id') .where('candidate', candidate); -} +}; app.get('/', (req, res) => { (async function() { From 0986398996c3143e2d32138964ff4e0c5cb5e41b Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 18 Sep 2019 11:57:44 -0700 Subject: [PATCH 04/36] Fix lint: datacatalog --- datacatalog/cloud-client/lookupEntry.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/datacatalog/cloud-client/lookupEntry.js b/datacatalog/cloud-client/lookupEntry.js index 52c59f2820..975bde1656 100644 --- a/datacatalog/cloud-client/lookupEntry.js +++ b/datacatalog/cloud-client/lookupEntry.js @@ -22,10 +22,10 @@ * For more information, see the README.md under /datacatalog and the * documentation at https://cloud.google.com/data-catalog/docs. */ -function main( +const main = async ( projectId = process.env.GCLOUD_PROJECT, datasetId = process.env.GCLOUD_DATASET_ID -) { +) => { // [START datacatalog_lookup_dataset] // ------------------------------- // Import required modules. @@ -33,7 +33,7 @@ function main( const {DataCatalogClient} = require('@google-cloud/datacatalog').v1beta1; const datacatalog = new DataCatalogClient(); - async function lookup() { + const lookup = async () => { // TODO(developer): Uncomment the following lines before running the sample. // const projectId = 'my-project' // const datasetId = 'my_dataset' @@ -41,13 +41,12 @@ function main( const request = {linkedResource: resourceName}; const [result] = await datacatalog.lookupEntry(request); return result; - } + }; - lookup().then(response => { - console.log(response); - }); + const response = await lookup(); + console.log(response); // [END datacatalog_lookup_dataset] -} +}; // node lookupEntry.js main(...process.argv.slice(2)); From a0ee63141d4416eda32e803335c4ca36a375a443 Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 18 Sep 2019 12:00:14 -0700 Subject: [PATCH 05/36] Fix lint: endpoints --- endpoints/getting-started-grpc/client.js | 4 ++-- endpoints/getting-started-grpc/server.js | 8 ++++---- endpoints/getting-started/app.js | 4 ++-- endpoints/getting-started/test/app.test.js | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/endpoints/getting-started-grpc/client.js b/endpoints/getting-started-grpc/client.js index a4f32ee591..50a1b28d2b 100644 --- a/endpoints/getting-started-grpc/client.js +++ b/endpoints/getting-started-grpc/client.js @@ -15,7 +15,7 @@ 'use strict'; -function makeGrpcRequest(JWT_AUTH_TOKEN, API_KEY, HOST, GREETEE) { +const makeGrpcRequest = (JWT_AUTH_TOKEN, API_KEY, HOST, GREETEE) => { // Uncomment these lines to set their values // const JWT_AUTH_TOKEN = 'YOUR_JWT_AUTH_TOKEN'; // const API_KEY = 'YOUR_API_KEY'; @@ -51,7 +51,7 @@ function makeGrpcRequest(JWT_AUTH_TOKEN, API_KEY, HOST, GREETEE) { console.log(response.message); } }); -} +}; // The command-line program const {argv} = require('yargs') diff --git a/endpoints/getting-started-grpc/server.js b/endpoints/getting-started-grpc/server.js index b4d4a53b55..f3fc4f4ef0 100644 --- a/endpoints/getting-started-grpc/server.js +++ b/endpoints/getting-started-grpc/server.js @@ -22,17 +22,17 @@ const grpc = require('grpc'); const helloProto = grpc.load(PROTO_PATH).helloworld; // Implement the SayHello RPC method. -function sayHello(call, callback) { +const sayHello = (call, callback) => { callback(null, {message: `Hello ${call.request.name}`}); -} +}; // Start an RPC server to handle Greeter service requests -function startServer(PORT) { +const startServer = PORT => { const server = new grpc.Server(); server.addProtoService(helloProto.Greeter.service, {sayHello: sayHello}); server.bind(`0.0.0.0:${PORT}`, grpc.ServerCredentials.createInsecure()); server.start(); -} +}; // The command-line program const {argv} = require('yargs') diff --git a/endpoints/getting-started/app.js b/endpoints/getting-started/app.js index ef7ae182d2..271c1c4f87 100644 --- a/endpoints/getting-started/app.js +++ b/endpoints/getting-started/app.js @@ -33,7 +33,7 @@ app.post('/echo', (req, res) => { .end(); }); -function authInfoHandler(req, res) { +const authInfoHandler = (req, res) => { let authUser = {id: 'anonymous'}; const encodedInfo = req.get('X-Endpoint-API-UserInfo'); if (encodedInfo) { @@ -43,7 +43,7 @@ function authInfoHandler(req, res) { .status(200) .json(authUser) .end(); -} +}; app.get('/auth/info/googlejwt', authInfoHandler); app.get('/auth/info/googleidtoken', authInfoHandler); diff --git a/endpoints/getting-started/test/app.test.js b/endpoints/getting-started/test/app.test.js index c9e1616542..fd22dbebb2 100644 --- a/endpoints/getting-started/test/app.test.js +++ b/endpoints/getting-started/test/app.test.js @@ -25,7 +25,7 @@ const tools = require('@google-cloud/nodejs-repo-tools'); const SAMPLE_PATH = path.join(__dirname, '../app.js'); -function getSample() { +const getSample = () => { const testApp = express(); sinon.stub(testApp, 'listen').callsArg(1); const expressMock = sinon.stub().returns(testApp); @@ -39,7 +39,7 @@ function getSample() { express: expressMock, }, }; -} +}; beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); From 0ffad4042db32508d720df579ce79e5a97af85c1 Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 18 Sep 2019 12:02:13 -0700 Subject: [PATCH 06/36] Fix lint: cloud run --- run/logging-manual/index.js | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/run/logging-manual/index.js b/run/logging-manual/index.js index a3a78f0aba..c1b1f8689c 100644 --- a/run/logging-manual/index.js +++ b/run/logging-manual/index.js @@ -12,15 +12,14 @@ const startServer = () => { }; if (!process.env.GOOGLE_CLOUD_PROJECT) { - metadata - .getProjectId() - .then(project => { - process.env.GOOGLE_CLOUD_PROJECT = project; - startServer(); - }) - .catch(error => { - console.error(`error: Identify project from metadata server: ${error}`); - }); + try { + const project = await metadata.getProjectId(); + + process.env.GOOGLE_CLOUD_PROJECT = project; + startServer(); + } catch (err) { + console.error(`error: Identify project from metadata server: ${error}`); + } } else { startServer(); } From 83f3d5f5098e81a7c65c1999e92937896d1bfbfc Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 10:53:58 -0700 Subject: [PATCH 07/36] Fix lint: storage transfer --- storage-transfer/system-test/transfer.test.js | 2 +- storage-transfer/test/transfer.test.js | 4 +- storage-transfer/transfer.js | 38 +++++++++---------- 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/storage-transfer/system-test/transfer.test.js b/storage-transfer/system-test/transfer.test.js index a4c425822e..f3bdf3f3a8 100644 --- a/storage-transfer/system-test/transfer.test.js +++ b/storage-transfer/system-test/transfer.test.js @@ -47,7 +47,7 @@ before(async () => { await bucket2.acl.add(bucketOptions); }); -after(async () => { +after(() => { tools.restoreConsole(); const bucketOne = storage.bucket(firstBucketName); const bucketTwo = storage.bucket(secondBucketName); diff --git a/storage-transfer/test/transfer.test.js b/storage-transfer/test/transfer.test.js index 85af3eb2bc..380f3e882a 100644 --- a/storage-transfer/test/transfer.test.js +++ b/storage-transfer/test/transfer.test.js @@ -25,7 +25,7 @@ const destBucketName = 'bar'; const jobName = 'transferJobs/123456789012345678'; const transferOperationName = 'transferOperations/123456789012345678'; -function getSample() { +const getSample = () => { const transferJobMock = { name: jobName, }; @@ -75,7 +75,7 @@ function getSample() { transferOperation: transferOperationMock, }, }; -} +}; beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); diff --git a/storage-transfer/transfer.js b/storage-transfer/transfer.js index 49cdba679f..ad1d0b3015 100644 --- a/storage-transfer/transfer.js +++ b/storage-transfer/transfer.js @@ -25,7 +25,7 @@ const storagetransfer = google.storagetransfer('v1'); // [END setup] // [START auth] -function auth(callback) { +const auth = callback => { google.auth.getApplicationDefault((err, authClient) => { if (err) { return callback(err); @@ -46,7 +46,7 @@ function auth(callback) { } callback(null, authClient); }); -} +}; // [END auth] // [START create_transfer_job] @@ -61,7 +61,7 @@ function auth(callback) { * @param {string} [options.description] Optional. Description for the new transfer job. * @param {function} callback The callback function. */ -function createTransferJob(options, callback) { +const createTransferJob = (options, callback) => { const startDate = moment(options.date, 'YYYY/MM/DD'); const transferTime = moment(options.time, 'HH:mm'); @@ -117,7 +117,7 @@ function createTransferJob(options, callback) { } ); }); -} +}; // [END create_transfer_job] // [START get_transfer_job] @@ -127,7 +127,7 @@ function createTransferJob(options, callback) { * @param {string} jobName The name of the transfer job to get. * @param {function} callback The callback function. */ -function getTransferJob(jobName, callback) { +const getTransferJob = (jobName, callback) => { auth((err, authClient) => { if (err) { return callback(err); @@ -150,7 +150,7 @@ function getTransferJob(jobName, callback) { } ); }); -} +}; // [END get_transfer_job] // [START update_transfer_job] @@ -163,7 +163,7 @@ function getTransferJob(jobName, callback) { * @param {string} options.value The new value for the field. * @param {function} callback The callback function. */ -function updateTransferJob(options, callback) { +const updateTransferJob = (options, callback) => { auth((err, authClient) => { if (err) { return callback(err); @@ -202,7 +202,7 @@ function updateTransferJob(options, callback) { } ); }); -} +}; // [END update_transfer_job] // [START list_transfer_jobs] @@ -211,7 +211,7 @@ function updateTransferJob(options, callback) { * * @param {function} callback The callback function. */ -function listTransferJobs(callback) { +const listTransferJobs = callback => { auth((err, authClient) => { if (err) { return callback(err); @@ -234,7 +234,7 @@ function listTransferJobs(callback) { } ); }); -} +}; // [END list_transfer_jobs] // [START list_transfer_operations] @@ -244,7 +244,7 @@ function listTransferJobs(callback) { * @param {string} [jobName] An optional job name by which to filter results. * @param {function} callback The callback function. */ -function listTransferOperations(jobName, callback) { +const listTransferOperations = (jobName, callback) => { auth((err, authClient) => { if (err) { return callback(err); @@ -276,7 +276,7 @@ function listTransferOperations(jobName, callback) { } ); }); -} +}; // [END list_transfer_operations] // [START get_transfer_operation] @@ -286,7 +286,7 @@ function listTransferOperations(jobName, callback) { * @param {string} transferOperationName The name of the transfer operation. * @param {function} callback The callback function. */ -function getTransferOperation(transferOperationName, callback) { +const getTransferOperation = (transferOperationName, callback) => { auth((err, authClient) => { if (err) { return callback(err); @@ -308,7 +308,7 @@ function getTransferOperation(transferOperationName, callback) { } ); }); -} +}; // [END get_transfer_operation] // [START pause_transfer_operation] @@ -318,7 +318,7 @@ function getTransferOperation(transferOperationName, callback) { * @param {string} transferOperationName The name of the transfer operation. * @param {function} callback The callback function. */ -function pauseTransferOperation(transferOperationName, callback) { +const pauseTransferOperation = (transferOperationName, callback) => { auth((err, authClient) => { if (err) { return callback(err); @@ -339,7 +339,7 @@ function pauseTransferOperation(transferOperationName, callback) { } ); }); -} +}; // [END pause_transfer_operation] // [START resume_transfer_operation] @@ -349,7 +349,7 @@ function pauseTransferOperation(transferOperationName, callback) { * @param {string} transferOperationName The name of the transfer operation. * @param {function} callback The callback function. */ -function resumeTransferOperation(transferOperationName, callback) { +const resumeTransferOperation = (transferOperationName, callback) => { auth((err, authClient) => { if (err) { return callback(err); @@ -370,7 +370,7 @@ function resumeTransferOperation(transferOperationName, callback) { } ); }); -} +}; // [END resume_transfer_operation] // [END all] @@ -386,7 +386,7 @@ const program = (module.exports = { getTransferOperation: getTransferOperation, pauseTransferOperation: pauseTransferOperation, resumeTransferOperation: resumeTransferOperation, - main: function(args) { + main: args => { // Run the command-line program cli.help().strict().parse(args).argv; // eslint-disable-line }, From 666435a5b6ecdf95070ae1fecea0b4e51187bade Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:11:40 -0700 Subject: [PATCH 08/36] Fix lint: healthcare --- healthcare/datasets/createDataset.js | 10 +++++----- healthcare/datasets/deidentifyDataset.js | 10 +++++----- healthcare/datasets/deleteDataset.js | 10 +++++----- healthcare/datasets/getDataset.js | 10 +++++----- healthcare/datasets/getDatasetIamPolicy.js | 10 +++++----- healthcare/datasets/listDatasets.js | 10 +++++----- healthcare/datasets/patchDataset.js | 10 +++++----- healthcare/datasets/setDatasetIamPolicy.js | 10 +++++----- healthcare/dicom/createDicomStore.js | 10 +++++----- healthcare/dicom/deleteDicomStore.js | 10 +++++----- healthcare/dicom/dicomWebDeleteStudy.js | 10 +++++----- healthcare/dicom/dicomWebRetrieveInstance.js | 10 +++++----- healthcare/dicom/dicomWebRetrieveRendered.js | 10 +++++----- healthcare/dicom/dicomWebRetrieveStudy.js | 10 +++++----- healthcare/dicom/dicomWebSearchForInstances.js | 10 +++++----- healthcare/dicom/exportDicomInstanceGcs.js | 10 +++++----- healthcare/dicom/getDicomStore.js | 10 +++++----- healthcare/dicom/getDicomStoreIamPolicy.js | 10 +++++----- healthcare/dicom/importDicomInstance.js | 10 +++++----- healthcare/dicom/listDicomStores.js | 10 +++++----- healthcare/dicom/patchDicomStore.js | 10 +++++----- healthcare/dicom/setDicomStoreIamPolicy.js | 10 +++++----- healthcare/fhir/createFhirStore.js | 10 +++++----- healthcare/fhir/deleteFhirResource.js | 10 +++++----- healthcare/fhir/deleteFhirResourcePurge.js | 10 +++++----- healthcare/fhir/deleteFhirStore.js | 10 +++++----- healthcare/fhir/exportFhirResources.js | 10 +++++----- healthcare/fhir/getFhirResource.js | 10 +++++----- healthcare/fhir/getFhirResourceHistory.js | 10 +++++----- healthcare/fhir/getFhirStore.js | 10 +++++----- healthcare/fhir/getFhirStoreCapabilities.js | 10 +++++----- healthcare/fhir/getFhirStoreIamPolicy.js | 10 +++++----- healthcare/fhir/getPatientEverything.js | 10 +++++----- healthcare/fhir/importFhirResources.js | 10 +++++----- healthcare/fhir/listFhirResourceHistory.js | 10 +++++----- healthcare/fhir/listFhirStores.js | 10 +++++----- healthcare/fhir/patchFhirStore.js | 10 +++++----- healthcare/fhir/searchFhirResourcesGet.js | 10 +++++----- healthcare/fhir/searchFhirResourcesPost.js | 10 +++++----- healthcare/fhir/setFhirStoreIamPolicy.js | 10 +++++----- healthcare/fhir/updateFhirResource.js | 10 +++++----- healthcare/hl7v2/createHl7v2Message.js | 10 +++++----- healthcare/hl7v2/createHl7v2Store.js | 10 +++++----- healthcare/hl7v2/deleteHl7v2Message.js | 10 +++++----- healthcare/hl7v2/deleteHl7v2Store.js | 10 +++++----- healthcare/hl7v2/getHl7v2Message.js | 10 +++++----- healthcare/hl7v2/getHl7v2Store.js | 10 +++++----- healthcare/hl7v2/getHl7v2StoreIamPolicy.js | 10 +++++----- healthcare/hl7v2/ingestHl7v2Message.js | 10 +++++----- healthcare/hl7v2/listHl7v2Messages.js | 10 +++++----- healthcare/hl7v2/listHl7v2Stores.js | 10 +++++----- healthcare/hl7v2/patchHl7v2Message.js | 10 +++++----- healthcare/hl7v2/patchHl7v2Store.js | 10 +++++----- healthcare/hl7v2/setHl7v2StoreIamPolicy.js | 10 +++++----- 54 files changed, 270 insertions(+), 270 deletions(-) diff --git a/healthcare/datasets/createDataset.js b/healthcare/datasets/createDataset.js index 9351e1028c..db21c11797 100644 --- a/healthcare/datasets/createDataset.js +++ b/healthcare/datasets/createDataset.js @@ -17,16 +17,16 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId -) { +) => { // [START healthcare_create_dataset] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function createDataset() { + const createDataset = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -41,11 +41,11 @@ function main( await healthcare.projects.locations.datasets.create(request); console.log(`Created dataset: ${datasetId}`); - } + }; createDataset(); // [END healthcare_create_dataset] -} +}; // node createDataset.js main(...process.argv.slice(2)); diff --git a/healthcare/datasets/deidentifyDataset.js b/healthcare/datasets/deidentifyDataset.js index 957954581b..255fb7887d 100644 --- a/healthcare/datasets/deidentifyDataset.js +++ b/healthcare/datasets/deidentifyDataset.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', sourceDatasetId, destinationDatasetId, keeplistTags -) { +) => { // [START healthcare_dicom_keeplist_deidentify_dataset] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function deidentifyDataset() { + const deidentifyDataset = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -60,11 +60,11 @@ function main( console.log( `De-identified data written from dataset ${sourceDatasetId} to dataset ${destinationDatasetId}` ); - } + }; deidentifyDataset(); // [END healthcare_dicom_keeplist_deidentify_dataset] -} +}; // node deidentifyDataset.js main(...process.argv.slice(2)); diff --git a/healthcare/datasets/deleteDataset.js b/healthcare/datasets/deleteDataset.js index 4106596dd4..122107ab56 100644 --- a/healthcare/datasets/deleteDataset.js +++ b/healthcare/datasets/deleteDataset.js @@ -17,16 +17,16 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId -) { +) => { // [START healthcare_delete_dataset] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function deleteDataset() { + const deleteDataset = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -41,11 +41,11 @@ function main( await healthcare.projects.locations.datasets.delete(request); console.log(`Deleted dataset: ${datasetId}`); - } + }; deleteDataset(); // [END healthcare_delete_dataset] -} +}; // node deleteDataset.js main(...process.argv.slice(2)); diff --git a/healthcare/datasets/getDataset.js b/healthcare/datasets/getDataset.js index 792f60f9b2..1de23d2e29 100644 --- a/healthcare/datasets/getDataset.js +++ b/healthcare/datasets/getDataset.js @@ -17,16 +17,16 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId -) { +) => { // [START healthcare_get_dataset] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getDataset() { + const getDataset = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -41,11 +41,11 @@ function main( const dataset = await healthcare.projects.locations.datasets.get(request); console.log(dataset.data); - } + }; getDataset(); // [END healthcare_get_dataset] -} +}; // node getDataset.js main(...process.argv.slice(2)); diff --git a/healthcare/datasets/getDatasetIamPolicy.js b/healthcare/datasets/getDatasetIamPolicy.js index 922a9ff75e..9fa8da75ab 100644 --- a/healthcare/datasets/getDatasetIamPolicy.js +++ b/healthcare/datasets/getDatasetIamPolicy.js @@ -17,16 +17,16 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId -) { +) => { // [START healthcare_dataset_get_iam_policy] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getDatasetIamPolicy() { + const getDatasetIamPolicy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -46,11 +46,11 @@ function main( 'Got dataset IAM policy:', JSON.stringify(dataset.data, null, 2) ); - } + }; getDatasetIamPolicy(); // [END healthcare_dataset_get_iam_policy] -} +}; // node getDatasetIamPolicy.js main(...process.argv.slice(2)); diff --git a/healthcare/datasets/listDatasets.js b/healthcare/datasets/listDatasets.js index 796cc572ba..8bc93a9de0 100644 --- a/healthcare/datasets/listDatasets.js +++ b/healthcare/datasets/listDatasets.js @@ -17,15 +17,15 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1' -) { +) => { // [START healthcare_list_datasets] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function listDatasets() { + const listDatasets = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -39,11 +39,11 @@ function main( const dataset = await healthcare.projects.locations.datasets.list(request); console.log(dataset.data); - } + }; listDatasets(); // [END healthcare_list_datasets] -} +}; // node listDatasets.js main(...process.argv.slice(2)); diff --git a/healthcare/datasets/patchDataset.js b/healthcare/datasets/patchDataset.js index 3477c7c2b3..be4c8dc280 100644 --- a/healthcare/datasets/patchDataset.js +++ b/healthcare/datasets/patchDataset.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, timeZone -) { +) => { // [START healthcare_patch_dataset] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function patchDataset() { + const patchDataset = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -47,11 +47,11 @@ function main( await healthcare.projects.locations.datasets.patch(request); console.log(`Dataset ${datasetId} patched with time zone ${timeZone}`); - } + }; patchDataset(); // [END healthcare_patch_dataset] -} +}; // node patchDataset.js main(...process.argv.slice(2)); diff --git a/healthcare/datasets/setDatasetIamPolicy.js b/healthcare/datasets/setDatasetIamPolicy.js index 8ea9e79b34..59ec2792ee 100644 --- a/healthcare/datasets/setDatasetIamPolicy.js +++ b/healthcare/datasets/setDatasetIamPolicy.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, member, role -) { +) => { // [START healthcare_dataset_set_iam_policy] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function setDatasetIamPolicy() { + const setDatasetIamPolicy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -62,11 +62,11 @@ function main( 'Set dataset IAM policy:', JSON.stringify(dataset.data, null, 2) ); - } + }; setDatasetIamPolicy(); // [END healthcare_dataset_set_iam_policy] -} +}; // node setDatasetIamPolicy.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/createDicomStore.js b/healthcare/dicom/createDicomStore.js index f2be09140f..42b11e446b 100644 --- a/healthcare/dicom/createDicomStore.js +++ b/healthcare/dicom/createDicomStore.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId -) { +) => { // [START healthcare_create_dicom_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function createDicomStore() { + const createDicomStore = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -43,11 +43,11 @@ function main( await healthcare.projects.locations.datasets.dicomStores.create(request); console.log(`Created DICOM store: ${dicomStoreId}`); - } + }; createDicomStore(); // [END healthcare_create_dicom_store] -} +}; // node createDicomStore.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/deleteDicomStore.js b/healthcare/dicom/deleteDicomStore.js index eefb283d94..c91544bb65 100644 --- a/healthcare/dicom/deleteDicomStore.js +++ b/healthcare/dicom/deleteDicomStore.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId -) { +) => { // [START healthcare_delete_dicom_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function deleteDicomStore() { + const deleteDicomStore = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -43,11 +43,11 @@ function main( await healthcare.projects.locations.datasets.dicomStores.delete(request); console.log(`Deleted DICOM store: ${dicomStoreId}`); - } + }; deleteDicomStore(); // [END healthcare_delete_dicom_store] -} +}; // node deleteDICOMStore.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/dicomWebDeleteStudy.js b/healthcare/dicom/dicomWebDeleteStudy.js index 4e69c82ba7..57595db09e 100644 --- a/healthcare/dicom/dicomWebDeleteStudy.js +++ b/healthcare/dicom/dicomWebDeleteStudy.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId, studyUid -) { +) => { // [START healthcare_dicomweb_delete_study] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function dicomWebDeleteStudy() { + const dicomWebDeleteStudy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -48,11 +48,11 @@ function main( request ); console.log('Deleted DICOM study'); - } + }; dicomWebDeleteStudy(); // [END healthcare_dicomweb_delete_study] -} +}; // node dicomWebDeleteStudy.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/dicomWebRetrieveInstance.js b/healthcare/dicom/dicomWebRetrieveInstance.js index 9c53e76a81..0c23e8d23a 100644 --- a/healthcare/dicom/dicomWebRetrieveInstance.js +++ b/healthcare/dicom/dicomWebRetrieveInstance.js @@ -17,7 +17,7 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, @@ -25,7 +25,7 @@ function main( studyUid, seriesUid, instanceUid -) { +) => { // [START healthcare_dicomweb_retrieve_instance] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); @@ -34,7 +34,7 @@ function main( const writeFile = util.promisify(fs.writeFile); const fileName = 'instance_file.dcm'; - async function dicomWebRetrieveInstance() { + const dicomWebRetrieveInstance = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -65,11 +65,11 @@ function main( console.log( `Retrieved DICOM instance and saved to ${fileName} in current directory` ); - } + }; dicomWebRetrieveInstance(); // [END healthcare_dicomweb_retrieve_instance] -} +}; // node dicomWebRetrieveInstance.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/dicomWebRetrieveRendered.js b/healthcare/dicom/dicomWebRetrieveRendered.js index fa6fa81ebb..f5896dc6fc 100644 --- a/healthcare/dicom/dicomWebRetrieveRendered.js +++ b/healthcare/dicom/dicomWebRetrieveRendered.js @@ -17,7 +17,7 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, @@ -25,7 +25,7 @@ function main( studyUid, seriesUid, instanceUid -) { +) => { // [START healthcare_dicomweb_retrieve_rendered] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); @@ -34,7 +34,7 @@ function main( const writeFile = util.promisify(fs.writeFile); const fileName = 'rendered_image.png'; - async function dicomWebRetrieveRendered() { + const dicomWebRetrieveRendered = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -65,11 +65,11 @@ function main( console.log( `Retrieved rendered image and saved to ${fileName} in current directory` ); - } + }; dicomWebRetrieveRendered(); // [END healthcare_dicomweb_retrieve_rendered] -} +}; // node dicomWebRetrieveRendered.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/dicomWebRetrieveStudy.js b/healthcare/dicom/dicomWebRetrieveStudy.js index 90070a8e48..0b33430b93 100644 --- a/healthcare/dicom/dicomWebRetrieveStudy.js +++ b/healthcare/dicom/dicomWebRetrieveStudy.js @@ -17,13 +17,13 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId, studyUid -) { +) => { // [START healthcare_dicomweb_retrieve_study] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); @@ -35,7 +35,7 @@ function main( // DICOM file. const fileName = 'study_file.multipart'; - async function dicomWebRetrieveStudy() { + const dicomWebRetrieveStudy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -67,11 +67,11 @@ function main( console.log( `Retrieved study and saved to ${fileName} in current directory` ); - } + }; dicomWebRetrieveStudy(); // [END healthcare_dicomweb_retrieve_study] -} +}; // node dicomWebRetrieveStudy.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/dicomWebSearchForInstances.js b/healthcare/dicom/dicomWebSearchForInstances.js index f8f641f4e7..7c10390600 100644 --- a/healthcare/dicom/dicomWebSearchForInstances.js +++ b/healthcare/dicom/dicomWebSearchForInstances.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId -) { +) => { // [START healthcare_dicomweb_search_instances] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function dicomWebSearchForInstances() { + const dicomWebSearchForInstances = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -50,11 +50,11 @@ function main( ); console.log(`Found ${instances.data.length} instances:`); console.log(JSON.stringify(instances.data)); - } + }; dicomWebSearchForInstances(); // [END healthcare_dicomweb_search_instances] -} +}; // node dicomWebSearchForInstances.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/exportDicomInstanceGcs.js b/healthcare/dicom/exportDicomInstanceGcs.js index 4ea81f6189..51a65b0291 100644 --- a/healthcare/dicom/exportDicomInstanceGcs.js +++ b/healthcare/dicom/exportDicomInstanceGcs.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId, gcsUri -) { +) => { // [START healthcare_export_dicom_instance_gcs] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function exportDicomInstanceGcs() { + const exportDicomInstanceGcs = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -55,11 +55,11 @@ function main( await healthcare.projects.locations.datasets.dicomStores.export(request); console.log(`Exported DICOM instances to ${gcsUri}`); - } + }; exportDicomInstanceGcs(); // [END healthcare_export_dicom_instance_gcs] -} +}; // node exportDicomInstanceGcs.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/getDicomStore.js b/healthcare/dicom/getDicomStore.js index 1c11472122..5d4353b2c9 100644 --- a/healthcare/dicom/getDicomStore.js +++ b/healthcare/dicom/getDicomStore.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId -) { +) => { // [START healthcare_get_dicom_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getDicomStore() { + const getDicomStore = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -45,11 +45,11 @@ function main( request ); console.log(dicomStore.data); - } + }; getDicomStore(); // [END healthcare_get_dicom_store] -} +}; // node getDicomStore.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/getDicomStoreIamPolicy.js b/healthcare/dicom/getDicomStoreIamPolicy.js index 625a6d1029..2e30724963 100644 --- a/healthcare/dicom/getDicomStoreIamPolicy.js +++ b/healthcare/dicom/getDicomStoreIamPolicy.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId -) { +) => { // [START healthcare_dicom_store_get_iam_policy] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getDicomStoreIamPolicy() { + const getDicomStoreIamPolicy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -48,11 +48,11 @@ function main( 'Got DICOM store IAM policy:', JSON.stringify(dicomStore.data, null, 2) ); - } + }; getDicomStoreIamPolicy(); // [END healthcare_dicom_store_get_iam_policy] -} +}; // node getDicomStoreIamPolicy.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/importDicomInstance.js b/healthcare/dicom/importDicomInstance.js index 385cf3edb0..5a6fc249d5 100644 --- a/healthcare/dicom/importDicomInstance.js +++ b/healthcare/dicom/importDicomInstance.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId, gcsUri -) { +) => { // [START healthcare_import_dicom_instance] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); const sleep = require('../sleep'); - async function importDicomInstance() { + const importDicomInstance = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -86,11 +86,11 @@ function main( data.error.details[0]['sampleErrors'][0]['error']['message'] ); } - } + }; importDicomInstance(); // [END healthcare_import_dicom_instance] -} +}; // node importDicomInstance.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/listDicomStores.js b/healthcare/dicom/listDicomStores.js index d9e9f1c80f..027d9da659 100644 --- a/healthcare/dicom/listDicomStores.js +++ b/healthcare/dicom/listDicomStores.js @@ -17,16 +17,16 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId -) { +) => { // [START healthcare_list_dicom_stores] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function listDicomStores() { + const listDicomStores = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -43,11 +43,11 @@ function main( request ); console.log(dicomStores.data); - } + }; listDicomStores(); // [END healthcare_list_dicom_stores] -} +}; // node listDicomStores.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/patchDicomStore.js b/healthcare/dicom/patchDicomStore.js index 7093211971..dd7ddcf40c 100644 --- a/healthcare/dicom/patchDicomStore.js +++ b/healthcare/dicom/patchDicomStore.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId, pubsubTopic -) { +) => { // [START healthcare_patch_dicom_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function patchDicomStore() { + const patchDicomStore = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -55,11 +55,11 @@ function main( console.log( `Patched DICOM store ${dicomStoreId} with Cloud Pub/Sub topic ${pubsubTopic}` ); - } + }; patchDicomStore(); // [END healthcare_patch_dicom_store] -} +}; // node patchDicomStore.js main(...process.argv.slice(2)); diff --git a/healthcare/dicom/setDicomStoreIamPolicy.js b/healthcare/dicom/setDicomStoreIamPolicy.js index 2d3680d975..421447cf31 100644 --- a/healthcare/dicom/setDicomStoreIamPolicy.js +++ b/healthcare/dicom/setDicomStoreIamPolicy.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, dicomStoreId, member, role -) { +) => { // [START healthcare_dicom_store_set_iam_policy] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function setDicomStoreIamPolicy() { + const setDicomStoreIamPolicy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -64,11 +64,11 @@ function main( 'Set DICOM store IAM policy:', JSON.stringify(dicomStore.data, null, 2) ); - } + }; setDicomStoreIamPolicy(); // [END healthcare_dicom_store_set_iam_policy] -} +}; // node setDicomStoreIamPolicy.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/createFhirStore.js b/healthcare/fhir/createFhirStore.js index c3c91a9e00..0a70a43d16 100644 --- a/healthcare/fhir/createFhirStore.js +++ b/healthcare/fhir/createFhirStore.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId -) { +) => { // [START healthcare_create_fhir_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function createFhirStore() { + const createFhirStore = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -43,11 +43,11 @@ function main( await healthcare.projects.locations.datasets.fhirStores.create(request); console.log(`Created FHIR store: ${fhirStoreId}`); - } + }; createFhirStore(); // [END healthcare_create_fhir_store] -} +}; // node createFhirStore.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/deleteFhirResource.js b/healthcare/fhir/deleteFhirResource.js index db322237f8..2de6d38ab1 100644 --- a/healthcare/fhir/deleteFhirResource.js +++ b/healthcare/fhir/deleteFhirResource.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, resourceType, resourceId -) { +) => { // [START healthcare_delete_resource] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function deleteFhirResource() { + const deleteFhirResource = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -49,11 +49,11 @@ function main( request ); console.log(`Deleted FHIR resource ${resourceType}`); - } + }; deleteFhirResource(); // [END healthcare_delete_resource] -} +}; // node deleteFhirResource.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/deleteFhirResourcePurge.js b/healthcare/fhir/deleteFhirResourcePurge.js index 88d594d03b..d24ad1c112 100644 --- a/healthcare/fhir/deleteFhirResourcePurge.js +++ b/healthcare/fhir/deleteFhirResourcePurge.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, resourceType, resourceId -) { +) => { // [START healthcare_delete_resource_purge] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function deleteFhirResourcePurge() { + const deleteFhirResourcePurge = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -49,11 +49,11 @@ function main( request ); console.log(`Deleted all historical versions of ${resourceType} resource`); - } + }; deleteFhirResourcePurge(); // [END healthcare_delete_resource_purge] -} +}; // node deleteFhirResourcePurge.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/deleteFhirStore.js b/healthcare/fhir/deleteFhirStore.js index 53c494ca22..6ca74d94e4 100644 --- a/healthcare/fhir/deleteFhirStore.js +++ b/healthcare/fhir/deleteFhirStore.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId -) { +) => { // [START healthcare_delete_fhir_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function deleteFhirStore() { + const deleteFhirStore = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -43,11 +43,11 @@ function main( await healthcare.projects.locations.datasets.fhirStores.delete(request); console.log(`Deleted FHIR store: ${fhirStoreId}`); - } + }; deleteFhirStore(); // [END healthcare_delete_fhir_store] -} +}; // node deleteFHIRStore.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/exportFhirResources.js b/healthcare/fhir/exportFhirResources.js index 80ef2450a4..7aeab52ad1 100644 --- a/healthcare/fhir/exportFhirResources.js +++ b/healthcare/fhir/exportFhirResources.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, gcsUri -) { +) => { // [START healthcare_export_fhir_resources_gcs] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); const sleep = require('../sleep'); - async function exportFhirResourcesGcs() { + const exportFhirResourcesGcs = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -70,11 +70,11 @@ function main( } else { console.log('Export failed'); } - } + }; exportFhirResourcesGcs(); // [END healthcare_export_fhir_resources_gcs] -} +}; // node exportFhirResources.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/getFhirResource.js b/healthcare/fhir/getFhirResource.js index 228e4aadc1..f158e59a38 100644 --- a/healthcare/fhir/getFhirResource.js +++ b/healthcare/fhir/getFhirResource.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, resourceType, resourceId -) { +) => { // [START healthcare_get_resource] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getFhirResource() { + const getFhirResource = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -49,11 +49,11 @@ function main( request ); console.log(`Got ${resourceType} resource:\n`, resource.data); - } + }; getFhirResource(); // [END healthcare_get_resource] -} +}; // node getFhirResource.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/getFhirResourceHistory.js b/healthcare/fhir/getFhirResourceHistory.js index 5dad77a976..9740911865 100644 --- a/healthcare/fhir/getFhirResourceHistory.js +++ b/healthcare/fhir/getFhirResourceHistory.js @@ -17,7 +17,7 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, @@ -25,12 +25,12 @@ function main( resourceType, resourceId, versionId -) { +) => { // [START healthcare_get_resource_history] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getFhirResourceHistory() { + const getFhirResourceHistory = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -51,11 +51,11 @@ function main( request ); console.log(JSON.stringify(resource.data, null, 2)); - } + }; getFhirResourceHistory(); // [END healthcare_get_resource_history] -} +}; // node getFhirResourceHistory.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/getFhirStore.js b/healthcare/fhir/getFhirStore.js index 027a33da7c..6ebd0c836e 100644 --- a/healthcare/fhir/getFhirStore.js +++ b/healthcare/fhir/getFhirStore.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId -) { +) => { // [START healthcare_get_fhir_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getFhirStore() { + const getFhirStore = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -45,11 +45,11 @@ function main( request ); console.log(fhirStore.data); - } + }; getFhirStore(); // [END healthcare_get_fhir_store] -} +}; // node getFHIRStore.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/getFhirStoreCapabilities.js b/healthcare/fhir/getFhirStoreCapabilities.js index c939f8abf9..070b374900 100644 --- a/healthcare/fhir/getFhirStoreCapabilities.js +++ b/healthcare/fhir/getFhirStoreCapabilities.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId -) { +) => { // [START healthcare_get_metadata] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getFhirStoreCapabilities() { + const getFhirStoreCapabilities = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -45,11 +45,11 @@ function main( request ); console.log(JSON.stringify(fhirStore.data, null, 2)); - } + }; getFhirStoreCapabilities(); // [END healthcare_get_metadata] -} +}; // node getFhirStoreCapabilities.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/getFhirStoreIamPolicy.js b/healthcare/fhir/getFhirStoreIamPolicy.js index a1360198f6..32f89e0d66 100644 --- a/healthcare/fhir/getFhirStoreIamPolicy.js +++ b/healthcare/fhir/getFhirStoreIamPolicy.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId -) { +) => { // [START healthcare_fhir_store_get_iam_policy] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getFhirStoreIamPolicy() { + const getFhirStoreIamPolicy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -48,11 +48,11 @@ function main( 'Got FHIR store IAM policy:', JSON.stringify(fhirStore.data, null, 2) ); - } + }; getFhirStoreIamPolicy(); // [END healthcare_fhir_store_get_iam_policy] -} +}; // node getFhirStoreIamPolicy.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/getPatientEverything.js b/healthcare/fhir/getPatientEverything.js index d71e86e690..4697ce708c 100644 --- a/healthcare/fhir/getPatientEverything.js +++ b/healthcare/fhir/getPatientEverything.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, patientId -) { +) => { // [START healthcare_get_patient_everything] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getPatientEverything() { + const getPatientEverything = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -50,11 +50,11 @@ function main( `Got all resources in patient ${patientId} compartment:\n`, JSON.stringify(patientEverything) ); - } + }; getPatientEverything(); // [END healthcare_get_patient_everything] -} +}; // node getPatientEverything.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/importFhirResources.js b/healthcare/fhir/importFhirResources.js index edab321c63..3e0fc6cfa2 100644 --- a/healthcare/fhir/importFhirResources.js +++ b/healthcare/fhir/importFhirResources.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, gcsUri -) { +) => { // [START healthcare_import_fhir_resources] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); const sleep = require('../sleep'); - async function importFhirResources() { + const importFhirResources = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -77,11 +77,11 @@ function main( operationStatus.data.error ); } - } + }; importFhirResources(); // [END healthcare_import_fhir_resources] -} +}; // node importFhirResources.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/listFhirResourceHistory.js b/healthcare/fhir/listFhirResourceHistory.js index 49d40ff03f..968e2847a0 100644 --- a/healthcare/fhir/listFhirResourceHistory.js +++ b/healthcare/fhir/listFhirResourceHistory.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, resourceType, resourceId -) { +) => { // [START healthcare_list_resource_history] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function listFhirResourceHistory() { + const listFhirResourceHistory = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -49,11 +49,11 @@ function main( request ); console.log(JSON.stringify(resource.data, null, 2)); - } + }; listFhirResourceHistory(); // [END healthcare_list_resource_history] -} +}; // node listFhirResourceHistory.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/listFhirStores.js b/healthcare/fhir/listFhirStores.js index c692c4eb8f..753e8fd854 100644 --- a/healthcare/fhir/listFhirStores.js +++ b/healthcare/fhir/listFhirStores.js @@ -17,16 +17,16 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId -) { +) => { // [START healthcare_list_fhir_stores] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function listFhirStores() { + const listFhirStores = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -43,11 +43,11 @@ function main( request ); console.log(fhirStores.data); - } + }; listFhirStores(); // [END healthcare_list_fhir_stores] -} +}; // node listFhirStores.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/patchFhirStore.js b/healthcare/fhir/patchFhirStore.js index 22e81bf087..8f6cde94c7 100644 --- a/healthcare/fhir/patchFhirStore.js +++ b/healthcare/fhir/patchFhirStore.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, pubsubTopic -) { +) => { // [START healthcare_patch_fhir_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function patchFhirStore() { + const patchFhirStore = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -55,11 +55,11 @@ function main( console.log( `Patched FHIR store ${fhirStoreId} with Cloud Pub/Sub topic ${pubsubTopic}` ); - } + }; patchFhirStore(); // [END healthcare_patch_fhir_store] -} +}; // node patchFhirStore.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/searchFhirResourcesGet.js b/healthcare/fhir/searchFhirResourcesGet.js index 38b9c7bc31..9fe3f13145 100644 --- a/healthcare/fhir/searchFhirResourcesGet.js +++ b/healthcare/fhir/searchFhirResourcesGet.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, resourceType -) { +) => { // [START healthcare_search_resources_get] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function searchFhirResourcesGet() { + const searchFhirResourcesGet = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -48,11 +48,11 @@ function main( const resources = response.data.entry; console.log(`Resources found: ${resources.length}`); console.log(JSON.stringify(resources, null, 2)); - } + }; searchFhirResourcesGet(); // [END healthcare_search_resources_get] -} +}; // node searchFhirResourcesGet.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/searchFhirResourcesPost.js b/healthcare/fhir/searchFhirResourcesPost.js index a60f08d159..eecb7b9b65 100644 --- a/healthcare/fhir/searchFhirResourcesPost.js +++ b/healthcare/fhir/searchFhirResourcesPost.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, resourceType -) { +) => { // [START healthcare_search_resources_post] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function searchFhirResourcesPost() { + const searchFhirResourcesPost = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -49,11 +49,11 @@ function main( const resources = response.data.entry; console.log(`Resources found: ${resources.length}`); console.log(JSON.stringify(resources, null, 2)); - } + }; searchFhirResourcesPost(); // [END healthcare_search_resources_post] -} +}; // node searchFhirResourcesPost.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/setFhirStoreIamPolicy.js b/healthcare/fhir/setFhirStoreIamPolicy.js index 62f233e6d6..558f6b1815 100644 --- a/healthcare/fhir/setFhirStoreIamPolicy.js +++ b/healthcare/fhir/setFhirStoreIamPolicy.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, member, role -) { +) => { // [START healthcare_fhir_store_set_iam_policy] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function setFhirStoreIamPolicy() { + const setFhirStoreIamPolicy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -63,11 +63,11 @@ function main( 'Set FHIR store IAM policy:', JSON.stringify(fhirStore.data, null, 2) ); - } + }; setFhirStoreIamPolicy(); // [END healthcare_fhir_store_set_iam_policy] -} +}; // node setFhirStoreIamPolicy.js main(...process.argv.slice(2)); diff --git a/healthcare/fhir/updateFhirResource.js b/healthcare/fhir/updateFhirResource.js index e95ead6467..e08c3a01f4 100644 --- a/healthcare/fhir/updateFhirResource.js +++ b/healthcare/fhir/updateFhirResource.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, fhirStoreId, resourceType, resourceId -) { +) => { // [START healthcare_update_resource] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function updateFhirResource() { + const updateFhirResource = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -53,11 +53,11 @@ function main( request ); console.log(`Updated ${resourceType} resource:\n`, resource.data); - } + }; updateFhirResource(); // [END healthcare_update_resource] -} +}; // node updateFhirResource.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/createHl7v2Message.js b/healthcare/hl7v2/createHl7v2Message.js index c9b53d19fa..7c522de20b 100644 --- a/healthcare/hl7v2/createHl7v2Message.js +++ b/healthcare/hl7v2/createHl7v2Message.js @@ -17,13 +17,13 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId, hl7v2MessageFile -) { +) => { // [START healthcare_create_hl7v2_message] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); @@ -31,7 +31,7 @@ function main( const util = require('util'); const readFile = util.promisify(fs.readFile); - async function createHl7v2Message() { + const createHl7v2Message = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -53,11 +53,11 @@ function main( ); const {data} = response; console.log(`Created HL7v2 message with data:\n`, data); - } + }; createHl7v2Message(); // [END healthcare_create_hl7v2_message] -} +}; // node createHl7v2Message.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/createHl7v2Store.js b/healthcare/hl7v2/createHl7v2Store.js index df49ec5bfd..ea9879486c 100644 --- a/healthcare/hl7v2/createHl7v2Store.js +++ b/healthcare/hl7v2/createHl7v2Store.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId -) { +) => { // [START healthcare_create_hl7v2_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function createHl7v2Store() { + const createHl7v2Store = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -43,11 +43,11 @@ function main( await healthcare.projects.locations.datasets.hl7V2Stores.create(request); console.log(`Created HL7v2 store: ${hl7v2StoreId}`); - } + }; createHl7v2Store(); // [END healthcare_create_hl7v2_store] -} +}; // node createHl7v2Store.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/deleteHl7v2Message.js b/healthcare/hl7v2/deleteHl7v2Message.js index 858f15e68e..5d7088d475 100644 --- a/healthcare/hl7v2/deleteHl7v2Message.js +++ b/healthcare/hl7v2/deleteHl7v2Message.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId, hl7v2MessageId -) { +) => { // [START healthcare_delete_hl7v2_message] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function deleteHl7v2Message() { + const deleteHl7v2Message = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -47,11 +47,11 @@ function main( request ); console.log('Deleted HL7v2 message'); - } + }; deleteHl7v2Message(); // [END healthcare_delete_hl7v2_message] -} +}; // node deleteHl7v2Message.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/deleteHl7v2Store.js b/healthcare/hl7v2/deleteHl7v2Store.js index 1083e00078..caa05a7f34 100644 --- a/healthcare/hl7v2/deleteHl7v2Store.js +++ b/healthcare/hl7v2/deleteHl7v2Store.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId -) { +) => { // [START healthcare_delete_hl7v2_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function deleteHl7v2Store() { + const deleteHl7v2Store = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -43,11 +43,11 @@ function main( await healthcare.projects.locations.datasets.hl7V2Stores.delete(request); console.log(`Deleted HL7v2 store: ${hl7v2StoreId}`); - } + }; deleteHl7v2Store(); // [END healthcare_delete_hl7v2_store] -} +}; // node deleteHL7v2Store.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/getHl7v2Message.js b/healthcare/hl7v2/getHl7v2Message.js index e153ccb8f2..8f41ba7e1b 100644 --- a/healthcare/hl7v2/getHl7v2Message.js +++ b/healthcare/hl7v2/getHl7v2Message.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId, hl7v2MessageId -) { +) => { // [START healthcare_get_hl7v2_message] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getHl7v2Message() { + const getHl7v2Message = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -48,11 +48,11 @@ function main( request ); console.log('Got HL7v2 message:\n', hl7v2Message.data); - } + }; getHl7v2Message(); // [END healthcare_get_hl7v2_message] -} +}; // node getHl7v2Message.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/getHl7v2Store.js b/healthcare/hl7v2/getHl7v2Store.js index 3f1b3cf1cc..df335f007c 100644 --- a/healthcare/hl7v2/getHl7v2Store.js +++ b/healthcare/hl7v2/getHl7v2Store.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId -) { +) => { // [START healthcare_get_hl7v2_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getHl7v2Store() { + const getHl7v2Store = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -45,11 +45,11 @@ function main( request ); console.log(hl7v2Store.data); - } + }; getHl7v2Store(); // [END healthcare_get_hl7v2_store] -} +}; // node getHl7v2Store.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/getHl7v2StoreIamPolicy.js b/healthcare/hl7v2/getHl7v2StoreIamPolicy.js index 1bb2b50a65..a08f875317 100644 --- a/healthcare/hl7v2/getHl7v2StoreIamPolicy.js +++ b/healthcare/hl7v2/getHl7v2StoreIamPolicy.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId -) { +) => { // [START healthcare_hl7v2_store_get_iam_policy] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function getHl7v2StoreIamPolicy() { + const getHl7v2StoreIamPolicy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -48,11 +48,11 @@ function main( 'Got HL7v2 store IAM policy:', JSON.stringify(hl7v2Store.data, null, 2) ); - } + }; getHl7v2StoreIamPolicy(); // [END healthcare_hl7v2_store_get_iam_policy] -} +}; // node getHl7v2StoreIamPolicy.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/ingestHl7v2Message.js b/healthcare/hl7v2/ingestHl7v2Message.js index 8f962845f6..4589dc76d0 100644 --- a/healthcare/hl7v2/ingestHl7v2Message.js +++ b/healthcare/hl7v2/ingestHl7v2Message.js @@ -17,13 +17,13 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId, hl7v2MessageFile -) { +) => { // [START healthcare_ingest_hl7v2_message] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); @@ -31,7 +31,7 @@ function main( const util = require('util'); const readFile = util.promisify(fs.readFile); - async function ingestHl7v2Message() { + const ingestHl7v2Message = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -55,11 +55,11 @@ function main( const buff = new Buffer.from(data, 'base64'); const hl7Ack = buff.toString('ascii'); console.log(`Ingested HL7v2 message with ACK:\n`, hl7Ack); - } + }; ingestHl7v2Message(); // [END healthcare_ingest_hl7v2_message] -} +}; // node ingestHl7v2Message.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/listHl7v2Messages.js b/healthcare/hl7v2/listHl7v2Messages.js index 467537d2ac..f440059c31 100644 --- a/healthcare/hl7v2/listHl7v2Messages.js +++ b/healthcare/hl7v2/listHl7v2Messages.js @@ -17,17 +17,17 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId -) { +) => { // [START healthcare_list_hl7v2_messages] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function listHl7v2Messages() { + const listHl7v2Messages = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -49,11 +49,11 @@ function main( for (const hl7v2Message of hl7v2Messages) { console.log(hl7v2Message); } - } + }; listHl7v2Messages(); // [END healthcare_list_hl7v2_messages] -} +}; // node listHl7v2Messages.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/listHl7v2Stores.js b/healthcare/hl7v2/listHl7v2Stores.js index 09efcc8ece..8171f61925 100644 --- a/healthcare/hl7v2/listHl7v2Stores.js +++ b/healthcare/hl7v2/listHl7v2Stores.js @@ -17,16 +17,16 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId -) { +) => { // [START healthcare_list_hl7v2_stores] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function listHl7v2Stores() { + const listHl7v2Stores = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -43,11 +43,11 @@ function main( request ); console.log(hl7v2Stores.data); - } + }; listHl7v2Stores(); // [END healthcare_list_hl7v2_stores] -} +}; // node listHl7v2Stores.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/patchHl7v2Message.js b/healthcare/hl7v2/patchHl7v2Message.js index 112a3e6df4..c17d366c89 100644 --- a/healthcare/hl7v2/patchHl7v2Message.js +++ b/healthcare/hl7v2/patchHl7v2Message.js @@ -17,7 +17,7 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, @@ -25,12 +25,12 @@ function main( hl7v2MessageId, labelKey, labelValue -) { +) => { // [START healthcare_patch_hl7v2_message] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function patchHl7v2Message() { + const patchHl7v2Message = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -59,11 +59,11 @@ function main( request ); console.log('Patched HL7v2 message'); - } + }; patchHl7v2Message(); // [END healthcare_patch_hl7v2_message] -} +}; // node patchHl7v2Message.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/patchHl7v2Store.js b/healthcare/hl7v2/patchHl7v2Store.js index c72eeffc76..8642df4592 100644 --- a/healthcare/hl7v2/patchHl7v2Store.js +++ b/healthcare/hl7v2/patchHl7v2Store.js @@ -17,18 +17,18 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId, pubsubTopic -) { +) => { // [START healthcare_patch_hl7v2_store] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function patchHl7v2Store() { + const patchHl7v2Store = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -55,11 +55,11 @@ function main( console.log( `Patched HL7v2 store ${hl7v2StoreId} with Cloud Pub/Sub topic ${pubsubTopic}` ); - } + }; patchHl7v2Store(); // [END healthcare_patch_hl7v2_store] -} +}; // node patchHl7v2Store.js main(...process.argv.slice(2)); diff --git a/healthcare/hl7v2/setHl7v2StoreIamPolicy.js b/healthcare/hl7v2/setHl7v2StoreIamPolicy.js index 6d3fc8cf8b..9edcdd2571 100644 --- a/healthcare/hl7v2/setHl7v2StoreIamPolicy.js +++ b/healthcare/hl7v2/setHl7v2StoreIamPolicy.js @@ -17,19 +17,19 @@ 'use strict'; -function main( +const main = ( projectId = process.env.GCLOUD_PROJECT, cloudRegion = 'us-central1', datasetId, hl7v2StoreId, member, role -) { +) => { // [START healthcare_hl7v2_store_set_iam_policy] const {google} = require('googleapis'); const healthcare = google.healthcare('v1beta1'); - async function setHl7v2StoreIamPolicy() { + const setHl7v2StoreIamPolicy = async () => { const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); @@ -63,11 +63,11 @@ function main( 'Set HL7v2 store IAM policy:', JSON.stringify(hl7v2Store.data, null, 2) ); - } + }; setHl7v2StoreIamPolicy(); // [END healthcare_hl7v2_store_set_iam_policy] -} +}; // node setHl7v2StoreIamPolicy.js main(...process.argv.slice(2)); From 65df9c2ec66f0efbb7c59b01285ecd0cf86f370c Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:14:07 -0700 Subject: [PATCH 09/36] Fix lint: functions/composer-storage-trigger --- functions/composer-storage-trigger/test/index.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/functions/composer-storage-trigger/test/index.test.js b/functions/composer-storage-trigger/test/index.test.js index 08a9a065c2..caea21f9d8 100644 --- a/functions/composer-storage-trigger/test/index.test.js +++ b/functions/composer-storage-trigger/test/index.test.js @@ -19,7 +19,7 @@ const proxyquire = require('proxyquire').noCallThru(); const sinon = require('sinon'); const assert = require('assert'); -function getSample(FetchStub) { +const getSample = FetchStub => { return { program: proxyquire('../', { 'node-fetch': FetchStub, @@ -28,7 +28,7 @@ function getSample(FetchStub) { fetch: FetchStub, }, }; -} +}; it('Handles error in JSON body', async () => { const event = { From 95662807d24721df8235e32fd67b20c385029063 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:14:19 -0700 Subject: [PATCH 10/36] Fix lint: functions/firebase --- functions/firebase/index.js | 2 +- functions/firebase/test/index.test.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/functions/firebase/index.js b/functions/firebase/index.js index 707d9a2e05..7464165693 100644 --- a/functions/firebase/index.js +++ b/functions/firebase/index.js @@ -114,7 +114,7 @@ exports.helloAnalytics = event => { const {resource} = event; console.log(`Function triggered by the following event: ${resource}`); - const analyticsEvent = event.data.eventDim[0]; + const [analyticsEvent] = event.data.eventDim; console.log(`Name: ${analyticsEvent.name}`); console.log(`Timestamp: ${new Date(analyticsEvent.timestampMicros / 1000)}`); diff --git a/functions/firebase/test/index.test.js b/functions/firebase/test/index.test.js index 1f7302cf81..fa3b84b524 100644 --- a/functions/firebase/test/index.test.js +++ b/functions/firebase/test/index.test.js @@ -20,7 +20,7 @@ const sinon = require('sinon'); const assert = require('assert'); const tools = require('@google-cloud/nodejs-repo-tools'); -function getSample() { +const getSample = () => { const firestoreMock = { doc: sinon.stub().returnsThis(), set: sinon.stub(), @@ -34,7 +34,7 @@ function getSample() { firestore: firestoreMock, }, }; -} +}; beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); From 4dbadcfac11145c12886caefe4923760c802d67c Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:14:32 -0700 Subject: [PATCH 11/36] Fix lint: functions/sendgrid --- functions/sendgrid/index.js | 245 +++++++++++++------------- functions/sendgrid/test/index.test.js | 10 +- 2 files changed, 124 insertions(+), 131 deletions(-) diff --git a/functions/sendgrid/index.js b/functions/sendgrid/index.js index a5ff238778..bfdddbf3b8 100644 --- a/functions/sendgrid/index.js +++ b/functions/sendgrid/index.js @@ -35,7 +35,7 @@ const bigquery = new BigQuery(); * @param {string} key Your SendGrid API key. * @returns {object} SendGrid client. */ -function getClient(key) { +const getClient = key => { if (!key) { const error = new Error( 'SendGrid API key not provided. Make sure you have a "sg_key" property in your request querystring' @@ -46,7 +46,7 @@ function getClient(key) { // Using SendGrid's Node.js Library https://github.com/sendgrid/sendgrid-nodejs return sendgrid(key); -} +}; // [END functions_sendgrid_get_client] // [START functions_get_payload] @@ -60,7 +60,7 @@ function getClient(key) { * @param {string} data.body Body of the email subject line. * @returns {object} Payload object. */ -function getPayload(requestBody) { +const getPayload = requestBody => { if (!requestBody.to) { const error = new Error( 'To email address not provided. Make sure you have a "to" property in your request' @@ -108,7 +108,7 @@ function getPayload(requestBody) { }, ], }; -} +}; // [END functions_get_payload] // [START functions_sendgrid_email] @@ -131,59 +131,58 @@ function getPayload(requestBody) { * @param {string} req.body.body Body of the email subject line. * @param {object} res Cloud Function response context. */ -exports.sendgridEmail = (req, res) => { - return Promise.resolve() - .then(() => { - if (req.method !== 'POST') { - const error = new Error('Only POST requests are accepted'); - error.code = 405; - throw error; - } +exports.sendgridEmail = async (req, res) => { + try { + if (req.method !== 'POST') { + const error = new Error('Only POST requests are accepted'); + error.code = 405; + throw error; + } - // Get a SendGrid client - const client = getClient(req.query.sg_key); - - // Build the SendGrid request to send email - const request = client.emptyRequest({ - method: 'POST', - path: '/v3/mail/send', - body: getPayload(req.body), - }); - - // Make the request to SendGrid's API - console.log(`Sending email to: ${req.body.to}`); - return client.API(request); - }) - .then(response => { - if (response.statusCode < 200 || response.statusCode >= 400) { - const error = Error(response.body); - error.code = response.statusCode; - throw error; - } + // Get a SendGrid client + const client = getClient(req.query.sg_key); - console.log(`Email sent to: ${req.body.to}`); - - // Forward the response back to the requester - res.status(response.statusCode); - if (response.headers['content-type']) { - res.set('content-type', response.headers['content-type']); - } - if (response.headers['content-length']) { - res.set('content-length', response.headers['content-length']); - } - if (response.body) { - res.send(response.body); - } else { - res.end(); - } - }) - .catch(err => { - console.error(err); - const code = - err.code || (err.response ? err.response.statusCode : 500) || 500; - res.status(code).send(err); - return Promise.reject(err); + // Build the SendGrid request to send email + const request = client.emptyRequest({ + method: 'POST', + path: '/v3/mail/send', + body: getPayload(req.body), }); + + // Make the request to SendGrid's API + console.log(`Sending email to: ${req.body.to}`); + const response = await client.API(request); + + if (response.statusCode < 200 || response.statusCode >= 400) { + const error = Error(response.body); + error.code = response.statusCode; + throw error; + } + + console.log(`Email sent to: ${req.body.to}`); + + // Forward the response back to the requester + res.status(response.statusCode); + if (response.headers['content-type']) { + res.set('content-type', response.headers['content-type']); + } + if (response.headers['content-length']) { + res.set('content-length', response.headers['content-length']); + } + if (response.body) { + res.send(response.body); + } else { + res.end(); + } + + return Promise.resolve(); + } catch (err) { + console.error(err); + const code = + err.code || (err.response ? err.response.statusCode : 500) || 500; + res.status(code).send(err); + return Promise.reject(err); + } }; // [END functions_sendgrid_email] @@ -193,7 +192,7 @@ exports.sendgridEmail = (req, res) => { * * @param {string} authorization The authorization header of the request, e.g. "Basic ZmdvOhJhcg==" */ -function verifyWebhook(authorization) { +const verifyWebhook = authorization => { const basicAuth = Buffer.from( authorization.replace('Basic ', ''), 'base64' @@ -204,7 +203,7 @@ function verifyWebhook(authorization) { error.code = 401; throw error; } -} +}; // [END functions_sendgrid_verify_webhook] // [START functions_sendgrid_fix_names] @@ -213,7 +212,7 @@ function verifyWebhook(authorization) { * * @param {*} obj Value to examine. */ -function fixNames(obj) { +const fixNames = obj => { if (Array.isArray(obj)) { obj.forEach(fixNames); } else if (obj && typeof obj === 'object') { @@ -227,7 +226,7 @@ function fixNames(obj) { } }); } -} +}; // [END functions_sendgrid_fix_names] // [START functions_sendgrid_webhook] @@ -239,46 +238,43 @@ function fixNames(obj) { * @param {object} req Cloud Function request context. * @param {object} res Cloud Function response context. */ -exports.sendgridWebhook = (req, res) => { - return Promise.resolve() - .then(() => { - if (req.method !== 'POST') { - const error = new Error('Only POST requests are accepted'); - error.code = 405; - throw error; - } +exports.sendgridWebhook = async (req, res) => { + try { + if (req.method !== 'POST') { + const error = new Error('Only POST requests are accepted'); + error.code = 405; + throw error; + } - verifyWebhook(req.get('authorization') || ''); + verifyWebhook(req.get('authorization') || ''); - const events = req.body || []; + const events = req.body || []; - // Make sure property names in the data meet BigQuery standards - fixNames(events); + // Make sure property names in the data meet BigQuery standards + fixNames(events); - // Generate newline-delimited JSON - // See https://cloud.google.com/bigquery/data-formats#json_format - const json = events.map(event => JSON.stringify(event)).join('\n'); + // Generate newline-delimited JSON + // See https://cloud.google.com/bigquery/data-formats#json_format + const json = events.map(event => JSON.stringify(event)).join('\n'); - // Upload a new file to Cloud Storage if we have events to save - if (json.length) { - const bucketName = config.EVENT_BUCKET; - const unixTimestamp = new Date().getTime() * 1000; - const filename = `${unixTimestamp}-${uuid.v4()}.json`; - const file = storage.bucket(bucketName).file(filename); + // Upload a new file to Cloud Storage if we have events to save + if (json.length) { + const bucketName = config.EVENT_BUCKET; + const unixTimestamp = new Date().getTime() * 1000; + const filename = `${unixTimestamp}-${uuid.v4()}.json`; + const file = storage.bucket(bucketName).file(filename); - console.log(`Saving events to ${filename} in bucket ${bucketName}`); + console.log(`Saving events to ${filename} in bucket ${bucketName}`); - return file.save(json).then(() => { - console.log(`JSON written to ${filename}`); - }); - } - }) - .then(() => res.status(200).end()) - .catch(err => { - console.error(err); - res.status(err.code || 500).send(err); - return Promise.reject(err); - }); + await file.save(json); + console.log(`JSON written to ${filename}`); + } + res.status(200).end(); + } catch (err) { + console.error(err); + res.status(err.code || 500).send(err); + return Promise.reject(err); + } }; // [END functions_sendgrid_webhook] @@ -287,13 +283,12 @@ exports.sendgridWebhook = (req, res) => { * Helper method to get a handle on a BigQuery table. Automatically creates the * dataset and table if necessary. */ -function getTable() { - const dataset = bigquery.dataset(config.DATASET); +const getTable = async () => { + let dataset = bigquery.dataset(config.DATASET); - return dataset - .get({autoCreate: true}) - .then(([dataset]) => dataset.table(config.TABLE).get({autoCreate: true})); -} + dataset = await dataset.get({autoCreate: true})[0]; + return dataset.table(config.TABLE).get({autoCreate: true}); +}; // [END functions_sendgrid_get_table] // [START functions_sendgrid_load] @@ -307,7 +302,7 @@ function getTable() { * @param {string} [event.data.timeDeleted] Time the file was deleted if this is a deletion event. * @see https://cloud.google.com/storage/docs/json_api/v1/objects#resource */ -exports.sendgridLoad = event => { +exports.sendgridLoad = async event => { const file = event.data; if (file.resourceState === 'not_exists') { @@ -315,34 +310,32 @@ exports.sendgridLoad = event => { return; } - return Promise.resolve() - .then(() => { - if (!file.bucket) { - throw new Error( - 'Bucket not provided. Make sure you have a "bucket" property in your request' - ); - } else if (!file.name) { - throw new Error( - 'Filename not provided. Make sure you have a "name" property in your request' - ); - } + try { + if (!file.bucket) { + throw new Error( + 'Bucket not provided. Make sure you have a "bucket" property in your request' + ); + } else if (!file.name) { + throw new Error( + 'Filename not provided. Make sure you have a "name" property in your request' + ); + } - return getTable(); - }) - .then(([table]) => { - const fileObj = storage.bucket(file.bucket).file(file.name); - console.log(`Starting job for ${file.name}`); - const metadata = { - autodetect: true, - sourceFormat: 'NEWLINE_DELIMITED_JSON', - }; - return table.import(fileObj, metadata); - }) - .then(([job]) => job.promise()) - .then(() => console.log(`Job complete for ${file.name}`)) - .catch(err => { - console.log(`Job failed for ${file.name}`); - return Promise.reject(err); - }); + const [table] = await getTable(); + + const fileObj = storage.bucket(file.bucket).file(file.name); + console.log(`Starting job for ${file.name}`); + const metadata = { + autodetect: true, + sourceFormat: 'NEWLINE_DELIMITED_JSON', + }; + const [job] = await table.import(fileObj, metadata); + + await job.promise(); + console.log(`Job complete for ${file.name}`); + } catch (err) { + console.log(`Job failed for ${file.name}`); + return Promise.reject(err); + } }; // [END functions_sendgrid_load] diff --git a/functions/sendgrid/test/index.test.js b/functions/sendgrid/test/index.test.js index a049e89e30..b7dcf28eac 100644 --- a/functions/sendgrid/test/index.test.js +++ b/functions/sendgrid/test/index.test.js @@ -53,7 +53,7 @@ const events = [ }, ]; -function getSample() { +const getSample = () => { const config = { EVENT_BUCKET: 'event-bucket', DATASET: 'datasets', @@ -112,9 +112,9 @@ function getSample() { job, }, }; -} +}; -function getMocks() { +const getMocks = () => { const req = { headers: {}, query: {}, @@ -144,7 +144,7 @@ function getMocks() { req: req, res: res, }; -} +}; beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); @@ -457,7 +457,7 @@ it('Saves files', async () => { sample.mocks.uuid.v4 = sinon.stub().returns('1357'); await sample.program.sendgridWebhook(mocks.req, mocks.res); - const filename = sample.mocks.bucket.file.firstCall.args[0]; + const [filename] = sample.mocks.bucket.file.firstCall.args; assert.strictEqual(mocks.res.status.callCount, 1); assert.deepStrictEqual(mocks.res.status.firstCall.args, [200]); assert.strictEqual(mocks.res.end.callCount, 1); From 7c48f3690a7a69a600a5afe2e7f35042664d2f79 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:14:43 -0700 Subject: [PATCH 12/36] Fix lint: functions/spanner --- functions/spanner/index.js | 32 +++++++++++++--------------- functions/spanner/test/index.test.js | 4 ++-- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/functions/spanner/index.js b/functions/spanner/index.js index c8439e7a95..ac157303e0 100644 --- a/functions/spanner/index.js +++ b/functions/spanner/index.js @@ -34,7 +34,7 @@ const databaseId = 'example-db'; * @param {Object} req Cloud Function request context. * @param {Object} res Cloud Function response context. */ -exports.get = (req, res) => { +exports.get = async (req, res) => { // Gets a reference to a Cloud Spanner instance and database const instance = spanner.instance(instanceId); const database = instance.database(databaseId); @@ -45,22 +45,20 @@ exports.get = (req, res) => { }; // Execute the query - return database - .run(query) - .then(results => { - const rows = results[0].map(row => row.toJSON()); - rows.forEach(row => { - res.write( - `SingerId: ${row.SingerId}, AlbumId: ${row.AlbumId}, AlbumTitle: ${row.AlbumTitle}\n` - ); - }); - res.status(200).end(); - }) - .catch(err => { - res - .status(500) - .send(`Error querying Spanner: ${err}`) - .end(); + try { + const results = await database.run(query); + const rows = results[0].map(row => row.toJSON()); + rows.forEach(row => { + res.write( + `SingerId: ${row.SingerId}, AlbumId: ${row.AlbumId}, AlbumTitle: ${row.AlbumTitle}\n` + ); }); + res.status(200).end(); + } catch (err) { + res + .status(500) + .send(`Error querying Spanner: ${err}`) + .end(); + } }; // [END spanner_functions_quickstart] diff --git a/functions/spanner/test/index.test.js b/functions/spanner/test/index.test.js index 859c4ae1b7..b8ea5df4ec 100644 --- a/functions/spanner/test/index.test.js +++ b/functions/spanner/test/index.test.js @@ -36,7 +36,7 @@ const query = { sql: 'SELECT * FROM Albums', }; -function getSample() { +const getSample = () => { const resultsMock = entities.map(row => { return {toJSON: sinon.stub().returns(row)}; }); @@ -69,7 +69,7 @@ function getSample() { }, }, }; -} +}; it('get: Gets albums', async () => { const sample = getSample(); From c39574e080b9c7b21cb6b1935d6174b2fdd3832d Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:42 -0700 Subject: [PATCH 13/36] Fix lint: functions/env_vars --- functions/env_vars/test/index.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/functions/env_vars/test/index.test.js b/functions/env_vars/test/index.test.js index 3727ee3f2e..5e95102f52 100644 --- a/functions/env_vars/test/index.test.js +++ b/functions/env_vars/test/index.test.js @@ -19,7 +19,7 @@ const sinon = require('sinon'); const assert = require('assert'); const functions = require('../'); -function getMocks() { +const getMocks = () => { const req = {}; const res = { send: sinon.stub().returnsThis(), @@ -29,7 +29,7 @@ function getMocks() { req: req, res: res, }; -} +}; it('should read env vars', () => { const mocks = getMocks(); From 8a8fd3e517d3f9f17b6bc67c4912aca801b11ea3 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:42 -0700 Subject: [PATCH 14/36] Fix lint: functions/http --- functions/http/index.js | 22 +++++++++++----------- functions/http/test/index.test.js | 8 ++++---- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/functions/http/index.js b/functions/http/index.js index 8b2e29a29b..b47309ed4c 100644 --- a/functions/http/index.js +++ b/functions/http/index.js @@ -31,7 +31,7 @@ exports.helloContent = (req, res) => { switch (req.get('content-type')) { // '{"name":"John"}' case 'application/json': - name = req.body.name; + name = req.body; break; // 'John', stored in a Buffer @@ -46,7 +46,7 @@ exports.helloContent = (req, res) => { // 'name=John' in the body of a POST request (not the URL) case 'application/x-www-form-urlencoded': - name = req.body.name; + name = req.body; break; } @@ -167,15 +167,15 @@ exports.uploadFile = (req, res) => { // Triggered once all uploaded files are processed by Busboy. // We still need to wait for the disk writes (saves) to complete. - busboy.on('finish', () => { - Promise.all(fileWrites).then(() => { - // TODO(developer): Process saved files here - for (const name in uploads) { - const file = uploads[name]; - fs.unlinkSync(file); - } - res.send(); - }); + busboy.on('finish', async () => { + await Promise.all(fileWrites); + + // TODO(developer): Process saved files here + for (const name in uploads) { + const file = uploads[name]; + fs.unlinkSync(file); + } + res.send(); }); busboy.end(req.rawBody); diff --git a/functions/http/test/index.test.js b/functions/http/test/index.test.js index f2bca4d991..e1cc240a81 100644 --- a/functions/http/test/index.test.js +++ b/functions/http/test/index.test.js @@ -21,7 +21,7 @@ const assert = require('assert'); const uuid = require('uuid'); const tools = require('@google-cloud/nodejs-repo-tools'); -function getSample() { +const getSample = () => { const requestPromise = sinon .stub() .returns(new Promise(resolve => resolve('test'))); @@ -34,9 +34,9 @@ function getSample() { requestPromise: requestPromise, }, }; -} +}; -function getMocks() { +const getMocks = () => { const req = { headers: {}, get: function(header) { @@ -65,7 +65,7 @@ function getMocks() { status: sinon.stub().returnsThis(), }, }; -} +}; beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); From cfc5a50bd021d2f2618b7bd1cbabc7cb8b6b3d94 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:42 -0700 Subject: [PATCH 15/36] Fix lint: functions/imagemagick --- functions/imagemagick/test/index.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/functions/imagemagick/test/index.test.js b/functions/imagemagick/test/index.test.js index f960245a65..3f67206515 100644 --- a/functions/imagemagick/test/index.test.js +++ b/functions/imagemagick/test/index.test.js @@ -41,7 +41,7 @@ const testFiles = { offensive: 'zombie.jpg', }; -describe('functions/imagemagick tests', async () => { +describe('functions/imagemagick tests', () => { let startFF, stopFF; before(async () => { From d1759ca4eaeb905a421f62910cfbc5bcc89e8c5d Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:43 -0700 Subject: [PATCH 16/36] Fix lint: functions/log --- functions/log/index.js | 18 +++++++++--------- functions/log/test/index.test.js | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/functions/log/index.js b/functions/log/index.js index 559ae99ea2..5c15394871 100644 --- a/functions/log/index.js +++ b/functions/log/index.js @@ -30,7 +30,7 @@ exports.helloWorld = (req, res) => { // https://github.com/googleapis/google-cloud-node/blob/master/docs/authentication.md const Logging = require('@google-cloud/logging'); -function getLogEntries() { +const getLogEntries = async () => { // Instantiates a client const logging = Logging(); @@ -41,12 +41,12 @@ function getLogEntries() { // Retrieve the latest Cloud Function log entries // See https://googlecloudplatform.github.io/gcloud-node/#/docs/logging - return logging.getEntries(options).then(([entries]) => { - console.log('Entries:'); - entries.forEach(entry => console.log(entry)); - return entries; - }); -} + const [entries] = await logging.getEntries(options); + + console.log('Entries:'); + entries.forEach(entry => console.log(entry)); + return entries; +}; // [END functions_log_retrieve] // [START functions_log_get_metrics] @@ -56,7 +56,7 @@ function getLogEntries() { // https://github.com/googleapis/google-cloud-node/blob/master/docs/authentication.md const Monitoring = require('@google-cloud/monitoring'); -function getMetrics(callback) { +const getMetrics = callback => { // Instantiates a client const monitoring = Monitoring.v3().metricServiceApi(); @@ -93,7 +93,7 @@ function getMetrics(callback) { .on('data', element => console.log(element)) .on('end', () => callback(error)); // [END functions_log_get_metrics] -} +}; // [START functions_log_stackdriver] exports.processLogEntry = data => { diff --git a/functions/log/test/index.test.js b/functions/log/test/index.test.js index 4ff06ec9e5..48f10b66d7 100644 --- a/functions/log/test/index.test.js +++ b/functions/log/test/index.test.js @@ -20,7 +20,7 @@ const sinon = require('sinon'); const assert = require('assert'); const tools = require('@google-cloud/nodejs-repo-tools'); -function getSample() { +const getSample = () => { const results = [[{}], {}]; const stream = { on: sinon.stub().returnsThis(), @@ -50,7 +50,7 @@ function getSample() { results: results, }, }; -} +}; beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); From d1bd17c2575a0f23fde43611a991464e0013b109 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:43 -0700 Subject: [PATCH 17/36] Fix lint: functions/memorystore/redis --- functions/memorystore/redis/test/index.test.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/functions/memorystore/redis/test/index.test.js b/functions/memorystore/redis/test/index.test.js index f152c9f27a..bcc3385434 100644 --- a/functions/memorystore/redis/test/index.test.js +++ b/functions/memorystore/redis/test/index.test.js @@ -18,7 +18,7 @@ const sinon = require('sinon'); const assert = require('assert'); -function getMocks() { +const getMocks = () => { return { req: {}, res: { @@ -28,7 +28,7 @@ function getMocks() { writeHead: sinon.stub().returnsThis(), }, }; -} +}; describe('visitCount', () => { it('should successfully increment the Redis counter', async () => { @@ -42,7 +42,7 @@ describe('visitCount', () => { assert(mocks.res.writeHead.calledWith(200)); assert(mocks.res.end.calledOnce); - const response = mocks.res.end.firstCall.args[0]; + const [response] = mocks.res.end.firstCall.args; assert(response.startsWith('Visit count:')); }); }); From 389bc8b439b196051010e4d725615277f9cc9aa8 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:43 -0700 Subject: [PATCH 18/36] Fix lint: functions/node8 --- functions/node8/index.js | 2 +- functions/node8/test/index.test.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/functions/node8/index.js b/functions/node8/index.js index 3a307144d8..36ad45bcd6 100644 --- a/functions/node8/index.js +++ b/functions/node8/index.js @@ -219,7 +219,7 @@ exports.helloAnalytics = (data, context) => { const {resource} = context; console.log(`Function triggered by the following event: ${resource}`); - const analyticsEvent = data.eventDim[0]; + const [analyticsEvent] = data.eventDim; console.log(`Name: ${analyticsEvent.name}`); console.log(`Timestamp: ${new Date(analyticsEvent.timestampMicros / 1000)}`); diff --git a/functions/node8/test/index.test.js b/functions/node8/test/index.test.js index c6c300d1ef..1925de3650 100644 --- a/functions/node8/test/index.test.js +++ b/functions/node8/test/index.test.js @@ -21,7 +21,7 @@ const assert = require('assert'); const utils = require('@google-cloud/nodejs-repo-tools'); const proxyquire = require('proxyquire').noCallThru(); -function getSample() { +const getSample = () => { const nodeFetch = sinon.stub().returns(Promise.resolve('test')); const firestoreMock = { @@ -39,7 +39,7 @@ function getSample() { nodeFetch: nodeFetch, }, }; -} +}; beforeEach(utils.stubConsole); afterEach(utils.restoreConsole); From f6ba8aec1a28b1b5ed86eed44923bd5b07e91cb2 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:43 -0700 Subject: [PATCH 19/36] Fix lint: functions/scheduleinstance --- functions/scheduleinstance/index.js | 80 ++++++++----------- functions/scheduleinstance/test/index.test.js | 8 +- 2 files changed, 38 insertions(+), 50 deletions(-) diff --git a/functions/scheduleinstance/index.js b/functions/scheduleinstance/index.js index 03e8470b2e..ed6ab3451b 100644 --- a/functions/scheduleinstance/index.js +++ b/functions/scheduleinstance/index.js @@ -31,37 +31,31 @@ const compute = new Compute(); * @param {!object} callback Cloud Function PubSub callback indicating * completion. */ -exports.startInstancePubSub = (event, context, callback) => { +exports.startInstancePubSub = async (event, context, callback) => { try { const payload = _validatePayload( JSON.parse(Buffer.from(event.data, 'base64').toString()) ); const options = {filter: `labels.${payload.label}`}; - compute.getVMs(options).then(vms => { - vms[0].forEach(instance => { + const [vms] = await compute.getVMs(options); + await Promise.all( + vms.map(async instance => { if (payload.zone === instance.zone.id) { - compute + const [operation] = await compute .zone(payload.zone) .vm(instance.name) - .start() - .then(data => { - // Operation pending. - const operation = data[0]; - return operation.promise(); - }) - .then(() => { - // Operation complete. Instance successfully started. - const message = `Successfully started instance ${instance.name}`; - console.log(message); - callback(null, message); - }) - .catch(err => { - console.log(err); - callback(err); - }); + .start(); + + // Operation pending + return operation.promise(); } - }); - }); + }) + ); + + // Operation complete. Instance successfully started. + const message = `Successfully started instance(s)`; + console.log(message); + callback(null, message); } catch (err) { console.log(err); callback(err); @@ -81,37 +75,31 @@ exports.startInstancePubSub = (event, context, callback) => { * @param {!object} event Cloud Function PubSub message event. * @param {!object} callback Cloud Function PubSub callback indicating completion. */ -exports.stopInstancePubSub = (event, context, callback) => { +exports.stopInstancePubSub = async (event, context, callback) => { try { const payload = _validatePayload( JSON.parse(Buffer.from(event.data, 'base64').toString()) ); const options = {filter: `labels.${payload.label}`}; - compute.getVMs(options).then(vms => { - vms[0].forEach(instance => { + const [vms] = await compute.getVMs(options); + await Promise.all( + vms.forEach(async instance => { if (payload.zone === instance.zone.id) { - compute + const [operation] = await compute .zone(payload.zone) .vm(instance.name) - .stop() - .then(data => { - // Operation pending. - const operation = data[0]; - return operation.promise(); - }) - .then(() => { - // Operation complete. Instance successfully stopped. - const message = `Successfully stopped instance ${instance.name}`; - console.log(message); - callback(null, message); - }) - .catch(err => { - console.log(err); - callback(err); - }); + .stop(); + + // Operation pending + return operation.promise(); } - }); - }); + }) + ); + + // Operation complete. Instance successfully stopped. + const message = `Successfully stopped instance(s)`; + console.log(message); + callback(null, message); } catch (err) { console.log(err); callback(err); @@ -125,13 +113,13 @@ exports.stopInstancePubSub = (event, context, callback) => { * @param {!object} payload the request payload to validate. * @return {!object} the payload object. */ -function _validatePayload(payload) { +const _validatePayload = payload => { if (!payload.zone) { throw new Error(`Attribute 'zone' missing from payload`); } else if (!payload.label) { throw new Error(`Attribute 'label' missing from payload`); } return payload; -} +}; // [END functions_start_instance_pubsub] // [END functions_stop_instance_pubsub] diff --git a/functions/scheduleinstance/test/index.test.js b/functions/scheduleinstance/test/index.test.js index ea22877ee7..4347bc373f 100644 --- a/functions/scheduleinstance/test/index.test.js +++ b/functions/scheduleinstance/test/index.test.js @@ -20,7 +20,7 @@ const sinon = require('sinon'); const assert = require('assert'); const tools = require('@google-cloud/nodejs-repo-tools'); -function getSample() { +const getSample = () => { const requestPromise = sinon .stub() .returns(new Promise(resolve => resolve('request sent'))); @@ -33,9 +33,9 @@ function getSample() { requestPromise: requestPromise, }, }; -} +}; -function getMocks() { +const getMocks = () => { const event = { data: {}, }; @@ -47,7 +47,7 @@ function getMocks() { context: {}, callback: callback, }; -} +}; beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); From 8dfec0ed5447e39b8b2019e6b17a9a5a0a0ba082 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:43 -0700 Subject: [PATCH 20/36] Fix lint: functions/slack --- functions/slack/index.js | 57 +++++++++++++++--------------- functions/slack/test/index.test.js | 8 ++--- 2 files changed, 32 insertions(+), 33 deletions(-) diff --git a/functions/slack/index.js b/functions/slack/index.js index fd88c3b73c..dbc8832911 100644 --- a/functions/slack/index.js +++ b/functions/slack/index.js @@ -31,7 +31,7 @@ const kgsearch = google.kgsearch('v1'); * @param {object} response The response from the Knowledge Graph API. * @returns {object} The formatted message. */ -function formatSlackMessage(query, response) { +const formatSlackMessage = (query, response) => { let entity; // Extract the first entity from the result list, if any @@ -81,7 +81,7 @@ function formatSlackMessage(query, response) { } return slackMessage; -} +}; // [END functions_slack_format] // [START functions_verify_webhook] @@ -91,13 +91,13 @@ function formatSlackMessage(query, response) { * @param {object} body The body of the request. * @param {string} body.token The Slack token to be verified. */ -function verifyWebhook(body) { +const verifyWebhook = body => { if (!body || body.token !== config.SLACK_TOKEN) { const error = new Error('Invalid credentials'); error.code = 401; throw error; } -} +}; // [END functions_verify_webhook] // [START functions_slack_request] @@ -106,7 +106,7 @@ function verifyWebhook(body) { * * @param {string} query The user's search query. */ -function makeSearchRequest(query) { +const makeSearchRequest = query => { return new Promise((resolve, reject) => { kgsearch.entities.search( { @@ -126,7 +126,7 @@ function makeSearchRequest(query) { } ); }); -} +}; // [END functions_slack_request] // [START functions_slack_search] @@ -145,29 +145,28 @@ function makeSearchRequest(query) { * @param {string} req.body.text The user's search query. * @param {object} res Cloud Function response object. */ -exports.kgSearch = (req, res) => { - return Promise.resolve() - .then(() => { - if (req.method !== 'POST') { - const error = new Error('Only POST requests are accepted'); - error.code = 405; - throw error; - } +exports.kgSearch = async (req, res) => { + try { + if (req.method !== 'POST') { + const error = new Error('Only POST requests are accepted'); + error.code = 405; + throw error; + } - // Verify that this request came from Slack - verifyWebhook(req.body); - - // Make the request to the Knowledge Graph Search API - return makeSearchRequest(req.body.text); - }) - .then(response => { - // Send the formatted message back to Slack - res.json(response); - }) - .catch(err => { - console.error(err); - res.status(err.code || 500).send(err); - return Promise.reject(err); - }); + // Verify that this request came from Slack + verifyWebhook(req.body); + + // Make the request to the Knowledge Graph Search API + const response = await makeSearchRequest(req.body.text); + + // Send the formatted message back to Slack + res.json(response); + + return Promise.resolve(); + } catch (err) { + console.error(err); + res.status(err.code || 500).send(err); + return Promise.reject(err); + } }; // [END functions_slack_search] diff --git a/functions/slack/test/index.test.js b/functions/slack/test/index.test.js index c36c383521..0ba657902d 100644 --- a/functions/slack/test/index.test.js +++ b/functions/slack/test/index.test.js @@ -25,7 +25,7 @@ const query = 'giraffe'; const SLACK_TOKEN = 'slack-token'; const KG_API_KEY = 'kg-api-key'; -function getSample() { +const getSample = () => { const config = { SLACK_TOKEN: SLACK_TOKEN, KG_API_KEY: KG_API_KEY, @@ -50,9 +50,9 @@ function getSample() { config: config, }, }; -} +}; -function getMocks() { +const getMocks = () => { const req = { headers: {}, query: {}, @@ -82,7 +82,7 @@ function getMocks() { req: req, res: res, }; -} +}; beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); From 5989c17d173717ba065ecd643cad9a6452828244 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:43 -0700 Subject: [PATCH 21/36] Fix lint: functions/sql --- functions/sql/test/index.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/functions/sql/test/index.test.js b/functions/sql/test/index.test.js index 2272bea464..7b9d54e136 100644 --- a/functions/sql/test/index.test.js +++ b/functions/sql/test/index.test.js @@ -52,7 +52,7 @@ it('should query MySQL', async () => { assert.strictEqual(resMock.status.called, false); assert.ok(resMock.send.calledOnce); - const response = resMock.send.firstCall.args[0]; + const [response] = resMock.send.firstCall.args; assert.ok(new RegExp(/\d{4}-\d{1,2}-\d{1,2}/).test(response.message)); }); @@ -79,6 +79,6 @@ it('should query Postgres', async () => { assert.strictEqual(resMock.status.called, false); assert.ok(resMock.send.calledOnce); - const response = resMock.send.firstCall.args[0]; + const [response] = resMock.send.firstCall.args; assert.ok(new RegExp(/\d{4}-\d{1,2}-\d{1,2}/).test(response.message)); }); From ccf9358cf891977979bca76bec362438ae7104da Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:43 -0700 Subject: [PATCH 22/36] Fix lint: functions/tips --- functions/tips/test/index.test.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/functions/tips/test/index.test.js b/functions/tips/test/index.test.js index 4fd5d1211c..9eddab0179 100644 --- a/functions/tips/test/index.test.js +++ b/functions/tips/test/index.test.js @@ -23,7 +23,7 @@ const sample = require(`../`); beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); -it('should demonstrate retry behavior for a promise', done => { +it('should demonstrate retry behavior for a promise', async done => { // Retry by throwing an error assert.throws(() => { sample.retryPromise({ @@ -34,13 +34,12 @@ it('should demonstrate retry behavior for a promise', done => { }, 'Retrying...'); // Terminate by returning a rejected promise - sample.retryPromise({data: {}}).then( - () => {}, - error => { - assert.strictEqual(error.message, 'Not retrying...'); - done(); - } - ); + try { + await sample.retryPromise({data: {}}); + } catch (err) { + assert.strictEqual(err.message, 'Not retrying...'); + done(); + } }); it('should demonstrate retry behavior for a callback', done => { From 4e2dc3e6251237d6d6e1e0a682988401755078ae Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:19:43 -0700 Subject: [PATCH 23/36] Fix lint: functions/tokenservice/functions --- functions/tokenservice/functions/index.js | 91 +++++++++++------------ 1 file changed, 44 insertions(+), 47 deletions(-) diff --git a/functions/tokenservice/functions/index.js b/functions/tokenservice/functions/index.js index 549f105854..56a3a1ae7d 100644 --- a/functions/tokenservice/functions/index.js +++ b/functions/tokenservice/functions/index.js @@ -26,18 +26,18 @@ admin.initializeApp(functions.config().firebase); const db = admin.firestore(); // [START save_token_to_firebase] -function saveOAuthToken(context, oauthToken) { +const saveOAuthToken = (context, oauthToken) => { const docRef = db.collection('ShortLivedAuthTokens').doc('OauthToken'); docRef.set(oauthToken); -} +}; // [END save_token_to_firebase] // [START generate_token] -function generateAccessToken( +const generateAccessToken = ( context, serviceAccountAccessToken, serviceAccountTokenType -) { +) => { // With the service account's credentials, we can make a request to generate // a new token for a 2nd service account that only has the permission to // act as a Dialogflow Client @@ -83,11 +83,11 @@ function generateAccessToken( post_req.write(JSON.stringify(body)); post_req.end(); }); -} +}; // [END generate_token] // [START retrieve_credentials] -function retrieveCredentials(context) { +const retrieveCredentials = context => { return new Promise(resolve => { // To create a new access token, we first have to retrieve the credentials // of the service account that will make the generateTokenRequest(). @@ -106,15 +106,14 @@ function retrieveCredentials(context) { body += chunk; }); - res.on('end', () => { + res.on('end', async () => { const response = JSON.parse(body); - return generateAccessToken( + const result = await generateAccessToken( context, response.access_token, response.token_type - ).then(result => { - return resolve(result); - }); + ); + return resolve(result); }); }); get_req.on('error', e => { @@ -123,22 +122,22 @@ function retrieveCredentials(context) { }); get_req.end(); }); -} +}; exports.retrieveCredentials = retrieveCredentials; // [END retrieve_credentials] // [START validate_token] // This method verifies the token expiry by validating against current time -function isValid(expiryTime) { +const isValid = expiryTime => { const currentDate = new Date(); const expirationDate = new Date(expiryTime); // If within 5 minutes of expiration, return false return currentDate <= expirationDate - 1000 * 60 * 5; -} +}; // [END validate_token] // [START function_get_token] -exports.getOAuthToken = functions.https.onCall((data, context) => { +exports.getOAuthToken = functions.https.onCall(async (data, context) => { // Checking that the user is authenticated. if (!context.auth) { // Throwing an HttpsError so that the client gets the error details. @@ -150,41 +149,39 @@ exports.getOAuthToken = functions.https.onCall((data, context) => { // Retrieve the token from the database const docRef = db.collection('ShortLivedAuthTokens').doc('OauthToken'); - return docRef - .get() - .then(doc => { - if (doc.exists && isValid(doc.data().expireTime)) { - //push notification - pushNotification( - data['deviceID'], - doc.data().accessToken, - doc.data().expireTime - ); - return doc.data(); - } else { - return retrieveCredentials(context).then(result => { - console.log('Print result from retrieveCredentials functions'); - console.log(result); - pushNotification( - data['deviceID'], - result['accessToken'], - result['expireTime'] - ); - return result; - }); - } - }) - .catch(err => { - console.log('Error retrieving token', err); - pushNotification(data['deviceID'], 'Error retrieving token', 'Error'); - // return 'Error retrieving token'; - return 'Error retrieving token'; - }); + const doc = await docRef.get(); + + try { + if (doc.exists && isValid(doc.data().expireTime)) { + //push notification + pushNotification( + data['deviceID'], + doc.data().accessToken, + doc.data().expireTime + ); + return doc.data(); + } else { + const result = await retrieveCredentials(context); + console.log('Print result from retrieveCredentials functions'); + console.log(result); + pushNotification( + data['deviceID'], + result['accessToken'], + result['expireTime'] + ); + return result; + } + } catch (err) { + console.log('Error retrieving token', err); + pushNotification(data['deviceID'], 'Error retrieving token', 'Error'); + // return 'Error retrieving token'; + return 'Error retrieving token'; + } }); // [END function_get_token] //[START pushNotification] -function pushNotification(deviceID, accessToken, expiryDate) { +const pushNotification = (deviceID, accessToken, expiryDate) => { //Passing the device id of the requested device which has requested for PN const tokens = [deviceID]; //Push notification payload with expiry date as title and access token as body @@ -199,5 +196,5 @@ function pushNotification(deviceID, accessToken, expiryDate) { }; //triggers push notification to the targeted devices. return admin.messaging().sendToDevice(tokens, payload); -} +}; //[END pushNotification] From dbaf523b616c041b270df8df059c5c3d23aaffb2 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:20:00 -0700 Subject: [PATCH 24/36] Fix lint: run/logging-manual --- run/logging-manual/index.js | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/run/logging-manual/index.js b/run/logging-manual/index.js index c1b1f8689c..7381789e3c 100644 --- a/run/logging-manual/index.js +++ b/run/logging-manual/index.js @@ -11,15 +11,19 @@ const startServer = () => { app.listen(PORT, () => console.log(`${SERVICE} listening on port ${PORT}`)); }; -if (!process.env.GOOGLE_CLOUD_PROJECT) { - try { - const project = await metadata.getProjectId(); +const main = async () => { + if (!process.env.GOOGLE_CLOUD_PROJECT) { + try { + const project = await metadata.getProjectId(); - process.env.GOOGLE_CLOUD_PROJECT = project; + process.env.GOOGLE_CLOUD_PROJECT = project; + startServer(); + } catch (err) { + console.error(`error: Identify project from metadata server: ${err}`); + } + } else { startServer(); - } catch (err) { - console.error(`error: Identify project from metadata server: ${error}`); } -} else { - startServer(); -} +}; + +main(); From 2196212fd3e678913c93f0414add9022929e7ce1 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 13:20:11 -0700 Subject: [PATCH 25/36] Fix lint: datacatalog --- datacatalog/cloud-client/lookupEntry.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/datacatalog/cloud-client/lookupEntry.js b/datacatalog/cloud-client/lookupEntry.js index 975bde1656..f37e36c07b 100644 --- a/datacatalog/cloud-client/lookupEntry.js +++ b/datacatalog/cloud-client/lookupEntry.js @@ -1,3 +1,5 @@ +/* eslint-disable no-warning-comments */ + /** * Copyright 2019 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); From c8eb48440e17cac1cd5e0847a9655d53b5c964d2 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 15:49:12 -0700 Subject: [PATCH 26/36] Address comments --- functions/http/index.js | 5 ++--- functions/sendgrid/index.js | 2 +- functions/spanner/index.js | 7 ++++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/functions/http/index.js b/functions/http/index.js index b47309ed4c..3baa11eb69 100644 --- a/functions/http/index.js +++ b/functions/http/index.js @@ -31,7 +31,7 @@ exports.helloContent = (req, res) => { switch (req.get('content-type')) { // '{"name":"John"}' case 'application/json': - name = req.body; + name = req.body.name; break; // 'John', stored in a Buffer @@ -171,8 +171,7 @@ exports.uploadFile = (req, res) => { await Promise.all(fileWrites); // TODO(developer): Process saved files here - for (const name in uploads) { - const file = uploads[name]; + for (const file of uploads) { fs.unlinkSync(file); } res.send(); diff --git a/functions/sendgrid/index.js b/functions/sendgrid/index.js index bfdddbf3b8..0007298d02 100644 --- a/functions/sendgrid/index.js +++ b/functions/sendgrid/index.js @@ -286,7 +286,7 @@ exports.sendgridWebhook = async (req, res) => { const getTable = async () => { let dataset = bigquery.dataset(config.DATASET); - dataset = await dataset.get({autoCreate: true})[0]; + [dataset] = await dataset.get({autoCreate: true}); return dataset.table(config.TABLE).get({autoCreate: true}); }; // [END functions_sendgrid_get_table] diff --git a/functions/spanner/index.js b/functions/spanner/index.js index ac157303e0..01c158df63 100644 --- a/functions/spanner/index.js +++ b/functions/spanner/index.js @@ -50,15 +50,16 @@ exports.get = async (req, res) => { const rows = results[0].map(row => row.toJSON()); rows.forEach(row => { res.write( - `SingerId: ${row.SingerId}, AlbumId: ${row.AlbumId}, AlbumTitle: ${row.AlbumTitle}\n` + `SingerId: ${row.SingerId},` + + `AlbumId: ${row.AlbumId},` + + `AlbumTitle: ${row.AlbumTitle}\n` ); }); res.status(200).end(); } catch (err) { res .status(500) - .send(`Error querying Spanner: ${err}`) - .end(); + .send(`Error querying Spanner: ${err}`); } }; // [END spanner_functions_quickstart] From 1e8f8b21d1b39859f44c9004cc82bb5a95cf62df Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 16:13:48 -0700 Subject: [PATCH 27/36] Address comments, take 2 --- functions/spanner/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/functions/spanner/index.js b/functions/spanner/index.js index 01c158df63..7dad972e00 100644 --- a/functions/spanner/index.js +++ b/functions/spanner/index.js @@ -50,8 +50,8 @@ exports.get = async (req, res) => { const rows = results[0].map(row => row.toJSON()); rows.forEach(row => { res.write( - `SingerId: ${row.SingerId},` + - `AlbumId: ${row.AlbumId},` + + `SingerId: ${row.SingerId}, ` + + `AlbumId: ${row.AlbumId}, ` + `AlbumTitle: ${row.AlbumTitle}\n` ); }); From aba93b1b055e511fb1d85eed80938dc8de16bd51 Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 17:41:09 -0700 Subject: [PATCH 28/36] Fix lint: iot --- iot/http_example/cloudiot_http_example.js | 12 ++--- .../cloudiot_mqtt_example_nodejs.js | 48 +++++++++---------- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/iot/http_example/cloudiot_http_example.js b/iot/http_example/cloudiot_http_example.js index 0dbba3d2ba..46296bd824 100644 --- a/iot/http_example/cloudiot_http_example.js +++ b/iot/http_example/cloudiot_http_example.js @@ -118,7 +118,7 @@ const url = `${urlBase}${pathSuffix}`; // Create a Cloud IoT Core JWT for the given project ID, signed with the given // private key. // [START iot_http_jwt] -function createJwt(projectId, privateKeyFile, algorithm) { +const createJwt = (projectId, privateKeyFile, algorithm) => { // Create a JWT to authenticate this device. The device will be disconnected // after the token expires, and will have to reconnect with a new token. The // audience field should always be set to the GCP project ID. @@ -129,14 +129,14 @@ function createJwt(projectId, privateKeyFile, algorithm) { }; const privateKey = fs.readFileSync(privateKeyFile); return jwt.sign(token, privateKey, {algorithm: algorithm}); -} +}; // [END iot_http_jwt] // Publish numMessages message asynchronously, starting from message // messageCount. Telemetry events are published at a rate of 1 per second and // states at a rate of 1 every 2 seconds. // [START iot_http_publish] -function publishAsync(authToken, messageCount, numMessages) { +const publishAsync = (authToken, messageCount, numMessages) => { const payload = `${argv.registryId}/${argv.deviceId}-payload-${messageCount}`; console.log('Publishing message:', payload); const binaryData = Buffer.from(payload).toString('base64'); @@ -197,11 +197,11 @@ function publishAsync(authToken, messageCount, numMessages) { }, delayMs); } }); -} +}; // [END iot_http_publish] // [START iot_http_getconfig] -function getConfig(authToken, version) { +const getConfig = (authToken, version) => { console.log(`Getting config from URL: ${urlBase}`); const options = { @@ -228,7 +228,7 @@ function getConfig(authToken, version) { console.log('Received config', JSON.stringify(body)); } }); -} +}; // [END iot_http_getconfig] // [START iot_run_http] diff --git a/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js b/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js index 76f40bfa20..c5daa3bd93 100644 --- a/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js +++ b/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js @@ -247,7 +247,7 @@ const {argv} = require(`yargs`) // Create a Cloud IoT Core JWT for the given project id, signed with the given // private key. // [START iot_mqtt_jwt] -function createJwt(projectId, privateKeyFile, algorithm) { +const createJwt = (projectId, privateKeyFile, algorithm) => { // Create a JWT to authenticate this device. The device will be disconnected // after the token expires, and will have to reconnect with a new token. The // audience field should always be set to the GCP project id. @@ -258,20 +258,20 @@ function createJwt(projectId, privateKeyFile, algorithm) { }; const privateKey = fs.readFileSync(privateKeyFile); return jwt.sign(token, privateKey, {algorithm: algorithm}); -} +}; // [END iot_mqtt_jwt] // Publish numMessages messages asynchronously, starting from message // messagesSent. // [START iot_mqtt_publish] -function publishAsync( +const publishAsync = ( mqttTopic, client, iatTime, messagesSent, numMessages, connectionArgs -) { +) => { // If we have published enough messages or backed off too many times, stop. if (messagesSent > numMessages || backoffTime >= MAXIMUM_BACKOFF_TIME) { if (backoffTime >= MAXIMUM_BACKOFF_TIME) { @@ -371,10 +371,10 @@ function publishAsync( ); }, schedulePublishDelayMs); }, publishDelayMs); -} +}; // [END iot_mqtt_publish] -function mqttDeviceDemo( +const mqttDeviceDemo = ( deviceId, registryId, projectId, @@ -385,7 +385,7 @@ function mqttDeviceDemo( mqttBridgePort, messageType, numMessages -) { +) => { // [START iot_mqtt_run] // const deviceId = `myDevice`; @@ -473,10 +473,10 @@ function mqttDeviceDemo( // Once all of the messages have been published, the connection to Google Cloud // IoT will be closed and the process will exit. See the publishAsync method. // [END iot_mqtt_run] -} +}; // Attaches a device to a gateway. -function attachDevice(deviceId, client, jwt) { +const attachDevice = (deviceId, client, jwt) => { // [START attach_device] // const deviceId = 'my-unauth-device'; const attachTopic = `/devices/${deviceId}/attach`; @@ -495,10 +495,10 @@ function attachDevice(deviceId, client, jwt) { } }); // [END attach_device] -} +}; // Detaches a device from a gateway. -function detachDevice(deviceId, client, jwt) { +const detachDevice = (deviceId, client, jwt) => { // [START detach_device] const detachTopic = `/devices/${deviceId}/detach`; console.log(`Detaching: ${detachTopic}`); @@ -516,10 +516,10 @@ function detachDevice(deviceId, client, jwt) { } }); // [END detach_device] -} +}; // Publish numMessages messages asynchronously through a gateway client connection -function publishAsyncGateway( +const publishAsyncGateway = ( client, iatTime, tokenExpMins, @@ -532,7 +532,7 @@ function publishAsyncGateway( projectId, privateKeyFile, algorithm -) { +) => { // If we have published enough messages or backed off too many times, stop. if (messagesSent > numMessages || backoffTime >= MAXIMUM_BACKOFF_TIME) { if (backoffTime >= MAXIMUM_BACKOFF_TIME) { @@ -601,10 +601,10 @@ function publishAsyncGateway( ); }, schedulePublishDelayMs); }, publishDelayMs); -} +}; // Sends data from a gateway on behalf of a device that is bound to that gateway. -function sendDataFromBoundDevice( +const sendDataFromBoundDevice = ( deviceId, gatewayId, registryId, @@ -616,7 +616,7 @@ function sendDataFromBoundDevice( mqttBridgePort, numMessages, tokenExpMins -) { +) => { // [START iot_send_data_from_bound_device] // const deviceId = `myDevice`; // const gatewayId = `mygateway`; @@ -692,10 +692,10 @@ function sendDataFromBoundDevice( // Note: logging packet send is very verbose }); // [END iot_send_data_from_bound_device] -} +}; // Listen for configuration messages on a gateway and bound device. -function listenForConfigMessages( +const listenForConfigMessages = ( deviceId, gatewayId, registryId, @@ -706,7 +706,7 @@ function listenForConfigMessages( mqttBridgeHostname, mqttBridgePort, clientDuration -) { +) => { // [START iot_listen_for_config_messages] // const deviceId = `myDevice`; // const gatewayId = `mygateway`; @@ -778,10 +778,10 @@ function listenForConfigMessages( // Note: logging packet send is very verbose }); // [END iot_listen_for_config_messages] -} +}; // Listen for error messages on a gateway. -function listenForErrorMessages( +const listenForErrorMessages = ( deviceId, gatewayId, registryId, @@ -792,7 +792,7 @@ function listenForErrorMessages( mqttBridgeHostname, mqttBridgePort, clientDuration -) { +) => { // [START iot_listen_for_error_messages] // const deviceId = `myDevice`; // const gatewayId = `mygateway`; @@ -858,4 +858,4 @@ function listenForErrorMessages( // Note: logging packet send is very verbose }); // [END iot_listen_for_error_messages] -} +}; From e4384c0db5b5b6750c097315e4bf3010cc7922bc Mon Sep 17 00:00:00 2001 From: ace-n Date: Fri, 20 Sep 2019 17:41:34 -0700 Subject: [PATCH 29/36] Auto-lint GCF changes --- functions/spanner/index.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/functions/spanner/index.js b/functions/spanner/index.js index 7dad972e00..de17887725 100644 --- a/functions/spanner/index.js +++ b/functions/spanner/index.js @@ -51,15 +51,13 @@ exports.get = async (req, res) => { rows.forEach(row => { res.write( `SingerId: ${row.SingerId}, ` + - `AlbumId: ${row.AlbumId}, ` + - `AlbumTitle: ${row.AlbumTitle}\n` + `AlbumId: ${row.AlbumId}, ` + + `AlbumTitle: ${row.AlbumTitle}\n` ); }); res.status(200).end(); } catch (err) { - res - .status(500) - .send(`Error querying Spanner: ${err}`); + res.status(500).send(`Error querying Spanner: ${err}`); } }; // [END spanner_functions_quickstart] From 92623bea2a1ad2317cd4390ca8a7d657e13703b6 Mon Sep 17 00:00:00 2001 From: ace-n Date: Mon, 23 Sep 2019 10:43:55 -0700 Subject: [PATCH 30/36] Fix tests --- functions/http/index.js | 4 +- functions/tips/test/index.test.js | 4 +- iot/http_example/cloudiot_http_example.js | 34 +- .../cloudiot_mqtt_example_nodejs.js | 413 +++++++++--------- 4 files changed, 228 insertions(+), 227 deletions(-) diff --git a/functions/http/index.js b/functions/http/index.js index 3baa11eb69..eeb4fbf0eb 100644 --- a/functions/http/index.js +++ b/functions/http/index.js @@ -31,7 +31,7 @@ exports.helloContent = (req, res) => { switch (req.get('content-type')) { // '{"name":"John"}' case 'application/json': - name = req.body.name; + ({name} = req.body); break; // 'John', stored in a Buffer @@ -46,7 +46,7 @@ exports.helloContent = (req, res) => { // 'name=John' in the body of a POST request (not the URL) case 'application/x-www-form-urlencoded': - name = req.body; + ({name} = req.body); break; } diff --git a/functions/tips/test/index.test.js b/functions/tips/test/index.test.js index 9eddab0179..26ecc6e3f8 100644 --- a/functions/tips/test/index.test.js +++ b/functions/tips/test/index.test.js @@ -23,7 +23,7 @@ const sample = require(`../`); beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); -it('should demonstrate retry behavior for a promise', async done => { +it('should demonstrate retry behavior for a promise', async () => { // Retry by throwing an error assert.throws(() => { sample.retryPromise({ @@ -38,7 +38,7 @@ it('should demonstrate retry behavior for a promise', async done => { await sample.retryPromise({data: {}}); } catch (err) { assert.strictEqual(err.message, 'Not retrying...'); - done(); + return Promise.resolve(); } }); diff --git a/iot/http_example/cloudiot_http_example.js b/iot/http_example/cloudiot_http_example.js index 46296bd824..c28322174e 100644 --- a/iot/http_example/cloudiot_http_example.js +++ b/iot/http_example/cloudiot_http_example.js @@ -20,6 +20,23 @@ const jwt = require('jsonwebtoken'); const request = require('retry-request', {request: require('request')}); // [END iot_http_includes] +// Create a Cloud IoT Core JWT for the given project ID, signed with the given +// private key. +// [START iot_http_jwt] +const createJwt = (projectId, privateKeyFile, algorithm) => { + // Create a JWT to authenticate this device. The device will be disconnected + // after the token expires, and will have to reconnect with a new token. The + // audience field should always be set to the GCP project ID. + const token = { + iat: parseInt(Date.now() / 1000), + exp: parseInt(Date.now() / 1000) + 20 * 60, // 20 minutes + aud: projectId, + }; + const privateKey = fs.readFileSync(privateKeyFile); + return jwt.sign(token, privateKey, {algorithm: algorithm}); +}; +// [END iot_http_jwt] + console.log('Google Cloud IoT Core HTTP example.'); const {argv} = require(`yargs`) .options({ @@ -115,23 +132,6 @@ const urlBase = `https://${argv.httpBridgeAddress}/v1/${devicePath}`; const url = `${urlBase}${pathSuffix}`; // [END iot_http_variables] -// Create a Cloud IoT Core JWT for the given project ID, signed with the given -// private key. -// [START iot_http_jwt] -const createJwt = (projectId, privateKeyFile, algorithm) => { - // Create a JWT to authenticate this device. The device will be disconnected - // after the token expires, and will have to reconnect with a new token. The - // audience field should always be set to the GCP project ID. - const token = { - iat: parseInt(Date.now() / 1000), - exp: parseInt(Date.now() / 1000) + 20 * 60, // 20 minutes - aud: projectId, - }; - const privateKey = fs.readFileSync(privateKeyFile); - return jwt.sign(token, privateKey, {algorithm: algorithm}); -}; -// [END iot_http_jwt] - // Publish numMessages message asynchronously, starting from message // messageCount. Telemetry events are published at a rate of 1 per second and // states at a rate of 1 every 2 seconds. diff --git a/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js b/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js index c5daa3bd93..44729da8ad 100644 --- a/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js +++ b/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js @@ -37,212 +37,6 @@ let backoffTime = 1; let publishChainInProgress = false; console.log('Google Cloud IoT Core MQTT example.'); -const {argv} = require(`yargs`) - .options({ - projectId: { - default: process.env.GCLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, - description: - 'The Project ID to use. Defaults to the value of the GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.', - requiresArg: true, - type: 'string', - }, - cloudRegion: { - default: 'us-central1', - description: 'GCP cloud region.', - requiresArg: true, - type: 'string', - }, - registryId: { - description: 'Cloud IoT registry ID.', - requiresArg: true, - demandOption: true, - type: 'string', - }, - deviceId: { - description: 'Cloud IoT device ID.', - requiresArg: true, - demandOption: true, - type: 'string', - }, - privateKeyFile: { - description: 'Path to private key file.', - requiresArg: true, - demandOption: true, - type: 'string', - }, - algorithm: { - description: 'Encryption algorithm to generate the JWT.', - requiresArg: true, - demandOption: true, - choices: ['RS256', 'ES256'], - type: 'string', - }, - tokenExpMins: { - default: 20, - description: 'Minutes to JWT token expiration.', - requiresArg: true, - type: 'number', - }, - mqttBridgeHostname: { - default: 'mqtt.googleapis.com', - description: 'MQTT bridge hostname.', - requiresArg: true, - type: 'string', - }, - mqttBridgePort: { - default: 8883, - description: 'MQTT bridge port.', - requiresArg: true, - type: 'number', - }, - }) - .command( - `mqttDeviceDemo`, - `Connects a device, sends data, and receives data`, - { - messageType: { - default: 'events', - description: 'Message type to publish.', - requiresArg: true, - choices: ['events', 'state'], - type: 'string', - }, - numMessages: { - default: 10, - description: 'Number of messages to publish.', - demandOption: true, - type: 'number', - }, - }, - opts => { - mqttDeviceDemo( - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.algorithm, - opts.privateKeyFile, - opts.mqttBridgeHostname, - opts.mqttBridgePort, - opts.messageType, - opts.numMessages - ); - } - ) - .command( - `sendDataFromBoundDevice`, - `Sends data from a gateway on behalf of a bound device.`, - { - gatewayId: { - description: 'Cloud IoT gateway ID.', - requiresArg: true, - demandOption: true, - type: 'string', - }, - numMessages: { - default: 10, - description: 'Number of messages to publish.', - demandOption: true, - type: 'number', - }, - }, - opts => { - sendDataFromBoundDevice( - opts.deviceId, - opts.gatewayId, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.algorithm, - opts.privateKeyFile, - opts.mqttBridgeHostname, - opts.mqttBridgePort, - opts.numMessages, - opts.tokenExpMins - ); - } - ) - .command( - `listenForConfigMessages`, - `Listens for configuration changes on a gateway and bound device.`, - { - gatewayId: { - description: 'Cloud IoT gateway ID.', - requiresArg: true, - demandOption: true, - type: 'string', - }, - clientDuration: { - default: 60000, - description: 'Duration in milliseconds for MQTT client to run.', - requiresArg: true, - type: 'number', - }, - }, - opts => { - listenForConfigMessages( - opts.deviceId, - opts.gatewayId, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.algorithm, - opts.privateKeyFile, - opts.mqttBridgeHostname, - opts.mqttBridgePort, - opts.clientDuration - ); - } - ) - .command( - `listenForErrorMessages`, - `Listens for error messages on a gateway.`, - { - gatewayId: { - description: 'Cloud IoT gateway ID.', - requiresArg: true, - demandOption: true, - type: 'string', - }, - clientDuration: { - default: 60000, - description: 'Duration in milliseconds for MQTT client to run.', - requiresArg: true, - type: 'number', - }, - }, - opts => { - listenForErrorMessages( - opts.deviceId, - opts.gatewayId, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.algorithm, - opts.privateKeyFile, - opts.mqttBridgeHostname, - opts.mqttBridgePort, - opts.clientDuration - ); - } - ) - .example( - `node $0 mqttDeviceDemo --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --numMessages=10 \\\n` - ) - .example( - `node $0 sendDataFromBoundDevice --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --gatewayId=my-node-gateway \\\n` - ) - .example( - `node $0 listenForConfigMessages --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --gatewayId=my-node-gateway \\\n\t--clientDuration=300000 \\\n` - ) - .example( - `node $0 listenForErrorMessages --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --gatewayId=my-node-gateway \\\n\t--clientDuration=300000 \\\n` - ) - .wrap(120) - .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/iot-core/docs`) - .help() - .strict(); // Create a Cloud IoT Core JWT for the given project id, signed with the given // private key. @@ -859,3 +653,210 @@ const listenForErrorMessages = ( }); // [END iot_listen_for_error_messages] }; + +const {argv} = require(`yargs`) + .options({ + projectId: { + default: process.env.GCLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, + description: + 'The Project ID to use. Defaults to the value of the GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.', + requiresArg: true, + type: 'string', + }, + cloudRegion: { + default: 'us-central1', + description: 'GCP cloud region.', + requiresArg: true, + type: 'string', + }, + registryId: { + description: 'Cloud IoT registry ID.', + requiresArg: true, + demandOption: true, + type: 'string', + }, + deviceId: { + description: 'Cloud IoT device ID.', + requiresArg: true, + demandOption: true, + type: 'string', + }, + privateKeyFile: { + description: 'Path to private key file.', + requiresArg: true, + demandOption: true, + type: 'string', + }, + algorithm: { + description: 'Encryption algorithm to generate the JWT.', + requiresArg: true, + demandOption: true, + choices: ['RS256', 'ES256'], + type: 'string', + }, + tokenExpMins: { + default: 20, + description: 'Minutes to JWT token expiration.', + requiresArg: true, + type: 'number', + }, + mqttBridgeHostname: { + default: 'mqtt.googleapis.com', + description: 'MQTT bridge hostname.', + requiresArg: true, + type: 'string', + }, + mqttBridgePort: { + default: 8883, + description: 'MQTT bridge port.', + requiresArg: true, + type: 'number', + }, + }) + .command( + `mqttDeviceDemo`, + `Connects a device, sends data, and receives data`, + { + messageType: { + default: 'events', + description: 'Message type to publish.', + requiresArg: true, + choices: ['events', 'state'], + type: 'string', + }, + numMessages: { + default: 10, + description: 'Number of messages to publish.', + demandOption: true, + type: 'number', + }, + }, + opts => { + mqttDeviceDemo( + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.algorithm, + opts.privateKeyFile, + opts.mqttBridgeHostname, + opts.mqttBridgePort, + opts.messageType, + opts.numMessages + ); + } + ) + .command( + `sendDataFromBoundDevice`, + `Sends data from a gateway on behalf of a bound device.`, + { + gatewayId: { + description: 'Cloud IoT gateway ID.', + requiresArg: true, + demandOption: true, + type: 'string', + }, + numMessages: { + default: 10, + description: 'Number of messages to publish.', + demandOption: true, + type: 'number', + }, + }, + opts => { + sendDataFromBoundDevice( + opts.deviceId, + opts.gatewayId, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.algorithm, + opts.privateKeyFile, + opts.mqttBridgeHostname, + opts.mqttBridgePort, + opts.numMessages, + opts.tokenExpMins + ); + } + ) + .command( + `listenForConfigMessages`, + `Listens for configuration changes on a gateway and bound device.`, + { + gatewayId: { + description: 'Cloud IoT gateway ID.', + requiresArg: true, + demandOption: true, + type: 'string', + }, + clientDuration: { + default: 60000, + description: 'Duration in milliseconds for MQTT client to run.', + requiresArg: true, + type: 'number', + }, + }, + opts => { + listenForConfigMessages( + opts.deviceId, + opts.gatewayId, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.algorithm, + opts.privateKeyFile, + opts.mqttBridgeHostname, + opts.mqttBridgePort, + opts.clientDuration + ); + } + ) + .command( + `listenForErrorMessages`, + `Listens for error messages on a gateway.`, + { + gatewayId: { + description: 'Cloud IoT gateway ID.', + requiresArg: true, + demandOption: true, + type: 'string', + }, + clientDuration: { + default: 60000, + description: 'Duration in milliseconds for MQTT client to run.', + requiresArg: true, + type: 'number', + }, + }, + opts => { + listenForErrorMessages( + opts.deviceId, + opts.gatewayId, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.algorithm, + opts.privateKeyFile, + opts.mqttBridgeHostname, + opts.mqttBridgePort, + opts.clientDuration + ); + } + ) + .example( + `node $0 mqttDeviceDemo --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --numMessages=10 \\\n` + ) + .example( + `node $0 sendDataFromBoundDevice --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --gatewayId=my-node-gateway \\\n` + ) + .example( + `node $0 listenForConfigMessages --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --gatewayId=my-node-gateway \\\n\t--clientDuration=300000 \\\n` + ) + .example( + `node $0 listenForErrorMessages --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --gatewayId=my-node-gateway \\\n\t--clientDuration=300000 \\\n` + ) + .wrap(120) + .recommendCommands() + .epilogue(`For more information, see https://cloud.google.com/iot-core/docs`) + .help() + .strict(); From eedc373fcc570948f04051c41642781cd73ff09f Mon Sep 17 00:00:00 2001 From: ace-n Date: Mon, 23 Sep 2019 11:27:32 -0700 Subject: [PATCH 31/36] Cloud Run: humor ESLint's race condition warning --- run/logging-manual/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/run/logging-manual/index.js b/run/logging-manual/index.js index 7381789e3c..760a905467 100644 --- a/run/logging-manual/index.js +++ b/run/logging-manual/index.js @@ -12,11 +12,11 @@ const startServer = () => { }; const main = async () => { - if (!process.env.GOOGLE_CLOUD_PROJECT) { + if (!process.env['GOOGLE_CLOUD_PROJECT']) { try { const project = await metadata.getProjectId(); - process.env.GOOGLE_CLOUD_PROJECT = project; + process.env['GOOGLE_CLOUD_PROJECT'] = project; startServer(); } catch (err) { console.error(`error: Identify project from metadata server: ${err}`); From 201206c2479330ab58a508ab1ea60c1837650859 Mon Sep 17 00:00:00 2001 From: ace-n Date: Mon, 23 Sep 2019 14:00:51 -0700 Subject: [PATCH 32/36] functions/pubsub tests: increase timeouts to reduce flakiness --- functions/helloworld/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/functions/helloworld/package.json b/functions/helloworld/package.json index 6e6d157c32..0666158c61 100644 --- a/functions/helloworld/package.json +++ b/functions/helloworld/package.json @@ -13,7 +13,7 @@ }, "scripts": { "unit-test": "mocha test/index.test.js test/*unit*test.js test/*integration*test.js --timeout=2000 --exit", - "system-test": "mocha test/*system*test.js --timeout=60000 --exit", + "system-test": "mocha test/*system*test.js --timeout=240000 --exit", "test": "npm run unit-test && npm run system-test" }, "dependencies": { From b7474a0ab69cad6d05463f12bd46ef4bde754c29 Mon Sep 17 00:00:00 2001 From: ace-n Date: Mon, 23 Sep 2019 14:04:35 -0700 Subject: [PATCH 33/36] ESLint race condition rule: revert old fix + make rule optional --- .eslintrc.yml | 1 + run/logging-manual/index.js | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.eslintrc.yml b/.eslintrc.yml index d41bd8a48f..9ea8d6e19b 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -10,6 +10,7 @@ plugins: - prettier - promise rules: + require-atomic-updates: warn prettier/prettier: error block-scoped-var: error eqeqeq: error diff --git a/run/logging-manual/index.js b/run/logging-manual/index.js index 760a905467..7381789e3c 100644 --- a/run/logging-manual/index.js +++ b/run/logging-manual/index.js @@ -12,11 +12,11 @@ const startServer = () => { }; const main = async () => { - if (!process.env['GOOGLE_CLOUD_PROJECT']) { + if (!process.env.GOOGLE_CLOUD_PROJECT) { try { const project = await metadata.getProjectId(); - process.env['GOOGLE_CLOUD_PROJECT'] = project; + process.env.GOOGLE_CLOUD_PROJECT = project; startServer(); } catch (err) { console.error(`error: Identify project from metadata server: ${err}`); From d8c3008728f63ca1c8dd0cd1a016d7e3cb4fab68 Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 25 Sep 2019 12:03:53 -0700 Subject: [PATCH 34/36] Fix bug in functions/scheduleinstance promise handling --- functions/scheduleinstance/index.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/functions/scheduleinstance/index.js b/functions/scheduleinstance/index.js index ed6ab3451b..8680304ff5 100644 --- a/functions/scheduleinstance/index.js +++ b/functions/scheduleinstance/index.js @@ -83,7 +83,7 @@ exports.stopInstancePubSub = async (event, context, callback) => { const options = {filter: `labels.${payload.label}`}; const [vms] = await compute.getVMs(options); await Promise.all( - vms.forEach(async instance => { + vms.map(async instance => { if (payload.zone === instance.zone.id) { const [operation] = await compute .zone(payload.zone) @@ -92,6 +92,8 @@ exports.stopInstancePubSub = async (event, context, callback) => { // Operation pending return operation.promise(); + } else { + return Promise.resolve(); } }) ); From 6b0ef1b38e27f2f669b5a66a9153d3f93df45e32 Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 25 Sep 2019 12:34:38 -0700 Subject: [PATCH 35/36] Increase helloworld system test timeout --- functions/helloworld/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/functions/helloworld/package.json b/functions/helloworld/package.json index 0666158c61..ca3e8170bb 100644 --- a/functions/helloworld/package.json +++ b/functions/helloworld/package.json @@ -13,7 +13,7 @@ }, "scripts": { "unit-test": "mocha test/index.test.js test/*unit*test.js test/*integration*test.js --timeout=2000 --exit", - "system-test": "mocha test/*system*test.js --timeout=240000 --exit", + "system-test": "mocha test/*system*test.js --timeout=600000 --exit", "test": "npm run unit-test && npm run system-test" }, "dependencies": { From 6120423679c6c7f7897234c5974ab33ea42cc11e Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 25 Sep 2019 14:54:13 -0700 Subject: [PATCH 36/36] functions/helloworld: disable flaky system tests --- functions/helloworld/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/functions/helloworld/package.json b/functions/helloworld/package.json index e7322c16ca..296c3d868c 100644 --- a/functions/helloworld/package.json +++ b/functions/helloworld/package.json @@ -14,7 +14,7 @@ "scripts": { "unit-test": "mocha test/index.test.js test/*unit*test.js test/*integration*test.js --timeout=2000 --exit", "system-test": "mocha test/*system*test.js --timeout=600000 --exit", - "test": "npm run unit-test && npm run system-test" + "test": "npm run unit-test" }, "dependencies": { "@google-cloud/debug-agent": "^4.0.0",