diff --git a/.eslintignore b/.eslintignore index 9340ad9b86..b5b7fb12e5 100644 --- a/.eslintignore +++ b/.eslintignore @@ -4,3 +4,4 @@ test/fixtures build/ docs/ protos/ +run/idp-sql/ diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index 7ce9ab6060..0000000000 --- a/.eslintrc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "parserOptions": { - "ecmaVersion": 2018, - "sourceType": "module" - }, - - "env": { - "es6": true - } -} diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000000..f8a6c809a2 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,13 @@ +{ + "extends": "./node_modules/gts/", + "env": { + "mocha": true + }, + "rules": { + "node/no-missing-require": ["off"], + "node/no-unpublished-require": ["off"], + "no-unused-vars": ["off"], + "node/no-deprecated-api": ["off"], + "no-process-exit": ["off"] + } +} \ No newline at end of file diff --git a/.estlintrc.json b/.estlintrc.json deleted file mode 100644 index e7bb5620b6..0000000000 --- a/.estlintrc.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "./node_modules/gts" - } - \ No newline at end of file diff --git a/appengine/analytics/app.js b/appengine/analytics/app.js index 1db961bf39..792c1aa3d8 100644 --- a/appengine/analytics/app.js +++ b/appengine/analytics/app.js @@ -46,7 +46,9 @@ const trackEvent = (category, action, label, value) => { ev: value, }; - return fetch('http://www.google-analytics.com/debug/collect', { params: data }); + return axios.get('http://www.google-analytics.com/debug/collect', { + params: data, + }); }; app.get('/', async (req, res, next) => { diff --git a/appengine/analytics/package.json b/appengine/analytics/package.json index 2b04244fe3..ca30d1085e 100644 --- a/appengine/analytics/package.json +++ b/appengine/analytics/package.json @@ -23,6 +23,6 @@ }, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/building-an-app/build/package.json b/appengine/building-an-app/build/package.json index 9b2cd26fea..7ae5b84d51 100644 --- a/appengine/building-an-app/build/package.json +++ b/appengine/building-an-app/build/package.json @@ -23,7 +23,7 @@ }, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "proxyquire": "^2.1.3" } } diff --git a/appengine/building-an-app/update/package.json b/appengine/building-an-app/update/package.json index f88576bf4a..d3ecb62767 100644 --- a/appengine/building-an-app/update/package.json +++ b/appengine/building-an-app/update/package.json @@ -25,7 +25,7 @@ "devDependencies": { "mocha": "^8.0.0", "sinon": "^9.0.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "proxyquire": "^2.1.3" } } diff --git a/appengine/building-an-app/update/server.js b/appengine/building-an-app/update/server.js index d4ecd3afd6..2b4cd69e38 100755 --- a/appengine/building-an-app/update/server.js +++ b/appengine/building-an-app/update/server.js @@ -17,7 +17,7 @@ // [START app] const express = require('express'); const bodyParser = require('body-parser'); -const path = require(`path`); +const path = require('path'); const app = express(); diff --git a/appengine/building-an-app/update/test/server.test.js b/appengine/building-an-app/update/test/server.test.js index 61723a381d..6fc6ad3c33 100755 --- a/appengine/building-an-app/update/test/server.test.js +++ b/appengine/building-an-app/update/test/server.test.js @@ -24,8 +24,8 @@ const cwd = path.join(__dirname, '../'); const requestObj = supertest(proxyquire(path.join(cwd, 'server'), {process})); const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; const restoreConsole = function () { @@ -40,7 +40,7 @@ it('should send greetings', async () => { await requestObj .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual(response.text, 'Hello from App Engine!'); }); }); @@ -50,9 +50,11 @@ describe('add_display_form', () => { await requestObj .get('/submit') .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual( - response.text.includes('textarea name="message" placeholder="Message"'), + response.text.includes( + 'textarea name="message" placeholder="Message"' + ), true ); }); @@ -67,7 +69,7 @@ describe('add_post_handler enable_parser', () => { message: 'sample-message', }) .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual(response.text, 'Thanks for your message!'); }); }); diff --git a/appengine/cloudsql/createTables.js b/appengine/cloudsql/createTables.js index 09667558c5..226b0dc0c7 100644 --- a/appengine/cloudsql/createTables.js +++ b/appengine/cloudsql/createTables.js @@ -34,15 +34,15 @@ prompt.get(FIELDS, async (err, config) => { // Create the "visits" table try { - await knex.schema.createTable('visits', (table) => { + await knex.schema.createTable('visits', table => { table.increments(); table.timestamp('timestamp'); table.string('userIp'); }); - console.log(`Successfully created 'visits' table.`); + console.log("Successfully created 'visits' table."); } catch (err) { - console.error(`Failed to create 'visits' table:`, err); + console.error("Failed to create 'visits' table:", err); } finally { if (knex) { knex.destroy(); diff --git a/appengine/cloudsql/package.json b/appengine/cloudsql/package.json index b6af999b00..f42831f43c 100644 --- a/appengine/cloudsql/package.json +++ b/appengine/cloudsql/package.json @@ -31,7 +31,7 @@ "mocha": "^8.0.0", "proxyquire": "^2.1.0", "sinon": "^9.0.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "wait-port": "^0.2.7" } } diff --git a/appengine/cloudsql/server.js b/appengine/cloudsql/server.js index f0174ca3a1..0b5b026a9b 100644 --- a/appengine/cloudsql/server.js +++ b/appengine/cloudsql/server.js @@ -69,7 +69,7 @@ const insertVisit = (knex, visit) => { * @param {object} knex The Knex connection object. * @returns {Promise} */ -const getVisits = async (knex) => { +const getVisits = async knex => { const results = await knex .select('timestamp', 'userIp') .from('visits') @@ -77,7 +77,7 @@ const getVisits = async (knex) => { .limit(10); return results.map( - (visit) => `Time: ${visit.timestamp}, AddrHash: ${visit.userIp}` + visit => `Time: ${visit.timestamp}, AddrHash: ${visit.userIp}` ); }; diff --git a/appengine/cloudsql/test/createTables.test.js b/appengine/cloudsql/test/createTables.test.js index b79ac4bd28..99a77af443 100644 --- a/appengine/cloudsql/test/createTables.test.js +++ b/appengine/cloudsql/test/createTables.test.js @@ -58,8 +58,8 @@ const getSample = () => { const stubConsole = function () { /* eslint-disable no-console */ - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; const restoreConsole = function () { @@ -73,7 +73,7 @@ afterEach(restoreConsole); describe('gae_flex_mysql_create_tables', () => { it('should create a table', async () => { const sample = getSample(); - const expectedResult = `Successfully created 'visits' table.`; + const expectedResult = "Successfully created 'visits' table."; proxyquire(SAMPLE_PATH, { knex: sample.mocks.Knex, @@ -87,7 +87,7 @@ describe('gae_flex_mysql_create_tables', () => { exampleConfig ); - await new Promise((r) => setTimeout(r, 10)); + await new Promise(r => setTimeout(r, 10)); assert.ok(sample.mocks.Knex.calledOnce); assert.deepStrictEqual(sample.mocks.Knex.firstCall.args, [ { @@ -116,7 +116,7 @@ describe('gae_flex_mysql_create_tables', () => { prompt: sample.mocks.prompt, }); - await new Promise((r) => setTimeout(r, 10)); + await new Promise(r => setTimeout(r, 10)); assert.ok(console.error.calledOnce); assert.ok(console.error.calledWith(error)); assert.ok(sample.mocks.Knex.notCalled); @@ -133,10 +133,10 @@ describe('gae_flex_mysql_create_tables', () => { knex: sample.mocks.Knex, prompt: sample.mocks.prompt, }); - await new Promise((r) => setTimeout(r, 10)); + await new Promise(r => setTimeout(r, 10)); assert.ok(console.error.calledOnce); assert.ok( - console.error.calledWith(`Failed to create 'visits' table:`, error) + console.error.calledWith("Failed to create 'visits' table:", error) ); assert.ok(sample.mocks.knex.destroy.calledOnce); }); diff --git a/appengine/cloudsql/test/server.test.js b/appengine/cloudsql/test/server.test.js index b93c7c86ec..a1e0205284 100644 --- a/appengine/cloudsql/test/server.test.js +++ b/appengine/cloudsql/test/server.test.js @@ -99,7 +99,7 @@ describe('gae_flex_mysql_app', () => { await request(sample.app) .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual(response.text, expectedResult); }); }); @@ -113,7 +113,7 @@ describe('gae_flex_mysql_app', () => { await request(sample.app) .get('/') .expect(500) - .expect((response) => { + .expect(response => { assert.ok(response.text.includes(expectedResult)); }); }); @@ -127,7 +127,7 @@ describe('gae_flex_mysql_app', () => { await request(sample.app) .get('/') .expect(500) - .expect((response) => { + .expect(response => { assert.ok(response.text.includes(expectedResult)); }); }); diff --git a/appengine/cloudsql_postgresql/createTables.js b/appengine/cloudsql_postgresql/createTables.js index fc5030e604..c6badb7b16 100644 --- a/appengine/cloudsql_postgresql/createTables.js +++ b/appengine/cloudsql_postgresql/createTables.js @@ -34,16 +34,16 @@ prompt.get(FIELDS, async (err, config) => { // Create the "visits" table try { - await knex.schema.createTable('visits', (table) => { + await knex.schema.createTable('visits', table => { table.increments(); table.timestamp('timestamp'); table.string('userIp'); }); - console.log(`Successfully created 'visits' table.`); + console.log("Successfully created 'visits' table."); return knex.destroy(); } catch (err) { - console.error(`Failed to create 'visits' table:`, err); + console.error("Failed to create 'visits' table:", err); if (knex) { knex.destroy(); } diff --git a/appengine/cloudsql_postgresql/package.json b/appengine/cloudsql_postgresql/package.json index 0bc7eb8fcf..4321f252c1 100644 --- a/appengine/cloudsql_postgresql/package.json +++ b/appengine/cloudsql_postgresql/package.json @@ -32,6 +32,6 @@ "mocha": "^8.0.0", "proxyquire": "^2.1.0", "sinon": "^9.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/cloudsql_postgresql/server.js b/appengine/cloudsql_postgresql/server.js index ba06e57c4a..a79bcb7d3f 100644 --- a/appengine/cloudsql_postgresql/server.js +++ b/appengine/cloudsql_postgresql/server.js @@ -70,7 +70,7 @@ const insertVisit = (knex, visit) => { * @returns {Promise} */ -const getVisits = async (knex) => { +const getVisits = async knex => { const results = await knex .select('timestamp', 'userIp') .from('visits') @@ -78,7 +78,7 @@ const getVisits = async (knex) => { .limit(10); return results.map( - (visit) => `Time: ${visit.timestamp}, AddrHash: ${visit.userIp}` + visit => `Time: ${visit.timestamp}, AddrHash: ${visit.userIp}` ); }; diff --git a/appengine/cloudsql_postgresql/test/createTables.test.js b/appengine/cloudsql_postgresql/test/createTables.test.js index 545e95647a..94c0b7fc66 100644 --- a/appengine/cloudsql_postgresql/test/createTables.test.js +++ b/appengine/cloudsql_postgresql/test/createTables.test.js @@ -57,8 +57,8 @@ const getSample = () => { }; const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; const restoreConsole = function () { @@ -72,7 +72,7 @@ afterEach(restoreConsole); describe('gae_flex_postgres_create_tables', () => { it('should create a table', async () => { const sample = getSample(); - const expectedResult = `Successfully created 'visits' table.`; + const expectedResult = "Successfully created 'visits' table."; proxyquire(SAMPLE_PATH, { knex: sample.mocks.Knex, @@ -86,7 +86,7 @@ describe('gae_flex_postgres_create_tables', () => { exampleConfig ); - await new Promise((r) => setTimeout(r, 10)); + await new Promise(r => setTimeout(r, 10)); assert.ok(sample.mocks.Knex.calledOnce); assert.deepStrictEqual(sample.mocks.Knex.firstCall.args, [ { @@ -115,7 +115,7 @@ describe('gae_flex_postgres_create_tables', () => { prompt: sample.mocks.prompt, }); - await new Promise((r) => setTimeout(r, 10)); + await new Promise(r => setTimeout(r, 10)); assert.ok(console.error.calledOnce); assert.ok(console.error.calledWith(error)); assert.ok(sample.mocks.Knex.notCalled); @@ -133,10 +133,10 @@ describe('gae_flex_postgres_create_tables', () => { prompt: sample.mocks.prompt, }); - await new Promise((r) => setTimeout(r, 10)); + await new Promise(r => setTimeout(r, 10)); assert.ok(console.error.calledOnce); assert.ok( - console.error.calledWith(`Failed to create 'visits' table:`, error) + console.error.calledWith("Failed to create 'visits' table:", error) ); assert.ok(sample.mocks.knex.destroy.calledOnce); }); diff --git a/appengine/cloudsql_postgresql/test/server.test.js b/appengine/cloudsql_postgresql/test/server.test.js index 9b104dab6c..b34c8541d9 100644 --- a/appengine/cloudsql_postgresql/test/server.test.js +++ b/appengine/cloudsql_postgresql/test/server.test.js @@ -97,7 +97,7 @@ describe('gae_flex_postgres_app', () => { await request(sample.app) .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual(response.text, expectedResult); }); }); @@ -111,7 +111,7 @@ describe('gae_flex_postgres_app', () => { await request(sample.app) .get('/') .expect(500) - .expect((response) => { + .expect(response => { assert.strictEqual(response.text.includes(expectedResult), true); }); }); @@ -125,7 +125,7 @@ describe('gae_flex_postgres_app', () => { await request(sample.app) .get('/') .expect(500) - .expect((response) => { + .expect(response => { assert.strictEqual(response.text.includes(expectedResult), true); }); }); diff --git a/appengine/datastore/app.js b/appengine/datastore/app.js index 6634a182db..a8ea6bb4ad 100644 --- a/appengine/datastore/app.js +++ b/appengine/datastore/app.js @@ -36,7 +36,7 @@ const datastore = new Datastore(); * * @param {object} visit The visit record to insert. */ -const insertVisit = (visit) => { +const insertVisit = visit => { return datastore.save({ key: datastore.key('visit'), data: visit, @@ -71,7 +71,7 @@ app.get('/', async (req, res, next) => { await insertVisit(visit); const [entities] = await getVisits(); const visits = entities.map( - (entity) => `Time: ${entity.timestamp}, AddrHash: ${entity.userIp}` + entity => `Time: ${entity.timestamp}, AddrHash: ${entity.userIp}` ); res .status(200) diff --git a/appengine/datastore/package.json b/appengine/datastore/package.json index 26cc376644..0c7e52a493 100644 --- a/appengine/datastore/package.json +++ b/appengine/datastore/package.json @@ -23,6 +23,6 @@ }, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/datastore/test/app.test.js b/appengine/datastore/test/app.test.js index b0cbac2997..989b574020 100644 --- a/appengine/datastore/test/app.test.js +++ b/appengine/datastore/test/app.test.js @@ -3,7 +3,7 @@ const path = require('path'); const app = require(path.join(__dirname, '../', 'app.js')); describe('gae_flex_datastore_app', () => { - it('should be listening', async () => { - await supertest(app).get('/').expect(200); - }); + it('should be listening', async () => { + await supertest(app).get('/').expect(200); + }); }); diff --git a/appengine/endpoints/package.json b/appengine/endpoints/package.json index 58eb5dda8b..96e399b762 100644 --- a/appengine/endpoints/package.json +++ b/appengine/endpoints/package.json @@ -28,6 +28,6 @@ "mocha": "^8.0.0", "proxyquire": "^2.1.0", "sinon": "^9.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/endpoints/test/app.test.js b/appengine/endpoints/test/app.test.js index f8097c3747..59fe874d5e 100644 --- a/appengine/endpoints/test/app.test.js +++ b/appengine/endpoints/test/app.test.js @@ -39,7 +39,7 @@ const getSample = () => { }; const stubConsole = function () { - sinon.stub(console, `error`); + sinon.stub(console, 'error'); }; const restoreConsole = function () { @@ -49,35 +49,35 @@ const restoreConsole = function () { beforeEach(stubConsole); afterEach(restoreConsole); -it(`sets up the sample`, (done) => { +it('sets up the sample', done => { const sample = getSample(); assert.ok(sample.mocks.express.calledOnce); done(); }); -it(`should echo a message`, async () => { +it('should echo a message', async () => { const sample = getSample(); await request(sample.app) .post('/echo') .send({message: 'foo'}) .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual(response.body.message, 'foo'); }); }); -it(`should try to parse encoded info`, async () => { +it('should try to parse encoded info', async () => { const sample = getSample(); await request(sample.app) .get('/auth/info/googlejwt') .expect(200) - .expect((response) => { + .expect(response => { assert.deepStrictEqual(response.body, {id: 'anonymous'}); }); }); -it(`should successfully parse encoded info`, async () => { +it('should successfully parse encoded info', async () => { const sample = getSample(); await request(sample.app) .get('/auth/info/googlejwt') @@ -86,7 +86,7 @@ it(`should successfully parse encoded info`, async () => { Buffer.from(JSON.stringify({id: 'foo'})).toString('base64') ) .expect(200) - .expect((response) => { + .expect(response => { assert.deepStrictEqual(response.body, {id: 'foo'}); }); }); diff --git a/appengine/hello-world/flexible/package.json b/appengine/hello-world/flexible/package.json index 8198e11043..91a7dee504 100644 --- a/appengine/hello-world/flexible/package.json +++ b/appengine/hello-world/flexible/package.json @@ -21,6 +21,6 @@ }, "devDependencies": { "mocha": "^8.1.3", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/hello-world/flexible/test/app.test.js b/appengine/hello-world/flexible/test/app.test.js index 8f5d29d786..1616347e70 100644 --- a/appengine/hello-world/flexible/test/app.test.js +++ b/appengine/hello-world/flexible/test/app.test.js @@ -4,11 +4,11 @@ const request = require('supertest'); describe('gae_flex_quickstart', () => { describe('GET /', () => { - it('should get 200', (done) => { + it('should get 200', done => { request(app).get('/').expect(200, done); }); - it('should get Hello World', (done) => { + it('should get Hello World', done => { request(app).get('/').expect('Hello, world!', done); }); }); diff --git a/appengine/hello-world/standard/package.json b/appengine/hello-world/standard/package.json index fd7a0801a8..9e22ac628a 100644 --- a/appengine/hello-world/standard/package.json +++ b/appengine/hello-world/standard/package.json @@ -21,6 +21,6 @@ }, "devDependencies": { "mocha": "^8.1.3", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/hello-world/standard/test/app.test.js b/appengine/hello-world/standard/test/app.test.js index 5d58e14412..b2ea17f345 100644 --- a/appengine/hello-world/standard/test/app.test.js +++ b/appengine/hello-world/standard/test/app.test.js @@ -4,11 +4,11 @@ const request = require('supertest'); describe('gae_node_request_example', () => { describe('GET /', () => { - it('should get 200', (done) => { + it('should get 200', done => { request(app).get('/').expect(200, done); }); - it('should get Hello World', (done) => { + it('should get Hello World', done => { request(app).get('/').expect('Hello, world!', done); }); }); diff --git a/appengine/mailjet/package.json b/appengine/mailjet/package.json index 2eaef6c101..8fc67ba58c 100644 --- a/appengine/mailjet/package.json +++ b/appengine/mailjet/package.json @@ -25,6 +25,6 @@ }, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/mailjet/test/app.test.js b/appengine/mailjet/test/app.test.js index 2b7d03595b..83f56f2ac0 100644 --- a/appengine/mailjet/test/app.test.js +++ b/appengine/mailjet/test/app.test.js @@ -4,7 +4,7 @@ const request = require('supertest'); describe('gae_flex_mailjet_send_message gae_flex_mailjet_config', () => { describe('GET /', () => { - it('should get 200', (done) => { + it('should get 200', done => { request(app).get('/').expect(200, done); }); }); diff --git a/appengine/metadata/flexible/package.json b/appengine/metadata/flexible/package.json index c9bbcfd348..9f866a4e9f 100644 --- a/appengine/metadata/flexible/package.json +++ b/appengine/metadata/flexible/package.json @@ -22,6 +22,6 @@ }, "devDependencies": { "mocha": "^8.1.3", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/metadata/standard/package.json b/appengine/metadata/standard/package.json index 1e072ada7e..c781fa011e 100644 --- a/appengine/metadata/standard/package.json +++ b/appengine/metadata/standard/package.json @@ -22,6 +22,6 @@ }, "devDependencies": { "mocha": "^8.1.3", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/pubsub/package.json b/appengine/pubsub/package.json index 0414fe5084..f263259c5b 100644 --- a/appengine/pubsub/package.json +++ b/appengine/pubsub/package.json @@ -27,7 +27,7 @@ "mocha": "^8.1.3", "sinon": "^9.0.3", "uuid": "^8.3.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "proxyquire": "^2.1.3" } } diff --git a/appengine/pubsub/test/app.test.js b/appengine/pubsub/test/app.test.js index 1dbd56624d..81630fa05b 100644 --- a/appengine/pubsub/test/app.test.js +++ b/appengine/pubsub/test/app.test.js @@ -72,7 +72,7 @@ describe('gae_flex_pubsub_index', () => { .type('form') .send({payload: payload}) .expect(200) - .expect((response) => { + .expect(response => { assert(new RegExp(/Message \d* sent/).test(response.text)); }); }); @@ -81,7 +81,7 @@ describe('gae_flex_pubsub_index', () => { await requestObj .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert( new RegExp(/Messages received by this instance/).test(response.text) ); @@ -132,7 +132,7 @@ describe('gae_flex_pubsub_auth_push', () => { await requestObj .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert(response.text.includes(payload)); }); }); diff --git a/appengine/sendgrid/package.json b/appengine/sendgrid/package.json index 16163cce2f..1d60e3ae4d 100644 --- a/appengine/sendgrid/package.json +++ b/appengine/sendgrid/package.json @@ -20,7 +20,7 @@ }, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "proxyquire": "^2.1.3" } } diff --git a/appengine/sendgrid/test/app.test.js b/appengine/sendgrid/test/app.test.js index 71206688da..afbc3f54ac 100644 --- a/appengine/sendgrid/test/app.test.js +++ b/appengine/sendgrid/test/app.test.js @@ -11,7 +11,7 @@ describe('gae_flex_sendgrid', () => { await request .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert(response.text.includes('Hello World!')); }); }); @@ -22,7 +22,7 @@ describe('gae_flex_sendgrid', () => { .type('form') .send({email: 'testuser@google.com'}) .expect(200) - .expect((response) => { + .expect(response => { assert(response.text.includes('Email sent!')); }); }); diff --git a/appengine/static-files/package.json b/appengine/static-files/package.json index 1b74758017..e7caf47cca 100644 --- a/appengine/static-files/package.json +++ b/appengine/static-files/package.json @@ -18,6 +18,6 @@ }, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/storage/flexible/app.js b/appengine/storage/flexible/app.js index d3710b2407..34aa709613 100644 --- a/appengine/storage/flexible/app.js +++ b/appengine/storage/flexible/app.js @@ -64,7 +64,7 @@ app.post('/upload', multer.single('file'), (req, res, next) => { const blob = bucket.file(req.file.originalname); const blobStream = blob.createWriteStream(); - blobStream.on('error', (err) => { + blobStream.on('error', err => { next(err); }); diff --git a/appengine/storage/flexible/package.json b/appengine/storage/flexible/package.json index 6cebac2d91..ebdb160092 100644 --- a/appengine/storage/flexible/package.json +++ b/appengine/storage/flexible/package.json @@ -17,7 +17,7 @@ }, "devDependencies": { "mocha": "^8.1.3", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "proxyquire": "^2.1.3" } } diff --git a/appengine/storage/flexible/system-test/app.test.js b/appengine/storage/flexible/system-test/app.test.js index 4aea1b2f52..ab308e60aa 100644 --- a/appengine/storage/flexible/system-test/app.test.js +++ b/appengine/storage/flexible/system-test/app.test.js @@ -29,11 +29,11 @@ const requestObj = supertest(proxyquire(path.join(cwd, 'app'), {process})); before(async () => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); await bucket.create(bucket).then(() => { return bucket.acl.add({ @@ -54,7 +54,7 @@ describe('gae_flex_storage_app', () => { await requestObj .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual( new RegExp(//).test(response.text), true @@ -67,7 +67,7 @@ describe('gae_flex_storage_app', () => { .post('/upload') .attach('file', path.join(__dirname, 'resources/test.txt')) .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual( response.text, `https://storage.googleapis.com/${bucketName}/test.txt` diff --git a/appengine/storage/standard/app.js b/appengine/storage/standard/app.js index c53c860288..113f3f3948 100644 --- a/appengine/storage/standard/app.js +++ b/appengine/storage/standard/app.js @@ -66,7 +66,7 @@ app.post('/upload', multer.single('file'), (req, res, next) => { resumable: false, }); - blobStream.on('error', (err) => { + blobStream.on('error', err => { next(err); }); diff --git a/appengine/storage/standard/package.json b/appengine/storage/standard/package.json index 95bebb186b..6dcfd38c81 100644 --- a/appengine/storage/standard/package.json +++ b/appengine/storage/standard/package.json @@ -17,7 +17,7 @@ }, "devDependencies": { "mocha": "^8.1.3", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "proxyquire": "^2.1.3" } } diff --git a/appengine/storage/standard/system-test/app.test.js b/appengine/storage/standard/system-test/app.test.js index 2eb80ae4ca..68a9743fd8 100644 --- a/appengine/storage/standard/system-test/app.test.js +++ b/appengine/storage/standard/system-test/app.test.js @@ -29,7 +29,7 @@ const requestObj = supertest(proxyquire(path.join(cwd, 'app'), {process})); before(async () => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); await bucket.create(bucket).then(() => { return bucket.acl.add({ @@ -50,7 +50,7 @@ describe('gae_storage_app', () => { await requestObj .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual( new RegExp(//).test(response.text), true @@ -63,7 +63,7 @@ describe('gae_storage_app', () => { .post('/upload') .attach('file', path.join(__dirname, 'resources/test.txt')) .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual( response.text, `https://storage.googleapis.com/${bucketName}/test.txt` diff --git a/appengine/twilio/package.json b/appengine/twilio/package.json index 0957295109..a80d06d376 100644 --- a/appengine/twilio/package.json +++ b/appengine/twilio/package.json @@ -21,6 +21,6 @@ "mocha": "^8.0.0", "proxyquire": "^2.1.0", "sinon": "^9.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/appengine/twilio/test/app.test.js b/appengine/twilio/test/app.test.js index ac45e6d080..dcb89b5cc2 100644 --- a/appengine/twilio/test/app.test.js +++ b/appengine/twilio/test/app.test.js @@ -60,7 +60,7 @@ describe('gae_flex_twilio_send_sms', () => { .get('/sms/send') .query({to: 1234}) .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual(response.text, 'Message sent.'); }); }); diff --git a/appengine/typescript/index.ts b/appengine/typescript/index.ts index 9ed9ae3ee8..8f1cdca37b 100644 --- a/appengine/typescript/index.ts +++ b/appengine/typescript/index.ts @@ -17,8 +17,8 @@ import express = require('express'); const PORT = Number(process.env.PORT) || 8080; const app = express(); -app.get("/", (req, res) => { - res.send("🎉 Hello TypeScript! 🎉"); +app.get('/', (req, res) => { + res.send('🎉 Hello TypeScript! 🎉'); }); const server = app.listen(PORT, () => { diff --git a/appengine/websockets/app.js b/appengine/websockets/app.js index 24ef2861f9..9da63a7bb6 100644 --- a/appengine/websockets/app.js +++ b/appengine/websockets/app.js @@ -25,8 +25,8 @@ app.get('/', (req, res) => { res.render('index.pug'); }); -io.on('connection', (socket) => { - socket.on('chat message', (msg) => { +io.on('connection', socket => { + socket.on('chat message', msg => { io.emit('chat message', msg); }); }); @@ -40,4 +40,4 @@ if (module === require.main) { } // [END appengine_websockets_app] -module.exports = server +module.exports = server; diff --git a/appengine/websockets/package.json b/appengine/websockets/package.json index b6e03778ab..805f9c6f4a 100644 --- a/appengine/websockets/package.json +++ b/appengine/websockets/package.json @@ -20,7 +20,7 @@ "express": "^4.15.4", "pug": "^3.0.0", "socket.io": "^2.2.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" }, "devDependencies": { "eslint": "^7.0.0", diff --git a/appengine/websockets/test/index.test.js b/appengine/websockets/test/index.test.js index bf86c1063d..464bb23572 100644 --- a/appengine/websockets/test/index.test.js +++ b/appengine/websockets/test/index.test.js @@ -27,10 +27,8 @@ before(async () => { app.listen(PORT, () => {}); browser = await puppeteer.launch({ - args: [ - '--no-sandbox', - '--disable-setuid-sandbox', - ]}); + args: ['--no-sandbox', '--disable-setuid-sandbox'], + }); browserPage = await browser.newPage(); }); @@ -48,7 +46,7 @@ describe('appengine_websockets_app', () => { document.querySelector('button').click(); }); - await new Promise((resolve) => setTimeout(resolve, 100)); + await new Promise(resolve => setTimeout(resolve, 100)); const itemText = await browserPage.evaluate( () => document.querySelector('li').textContent diff --git a/auth/auth.js b/auth/auth.js index 459fde288c..bf57432d9d 100644 --- a/auth/auth.js +++ b/auth/auth.js @@ -36,7 +36,7 @@ const authCloudImplicit = async () => { const [buckets] = results; console.log('Buckets:'); - buckets.forEach((bucket) => { + buckets.forEach(bucket => { console.log(bucket.name); }); } catch (err) { @@ -65,7 +65,7 @@ const authCloudExplicit = async ({projectId, keyFilename}) => { const [buckets] = await storage.getBuckets(); console.log('Buckets:'); - buckets.forEach((bucket) => { + buckets.forEach(bucket => { console.log(bucket.name); }); } catch (err) { @@ -76,17 +76,17 @@ const authCloudExplicit = async ({projectId, keyFilename}) => { // [END auth_cloud_explicit] }; -const cli = require(`yargs`) +const cli = require('yargs') .demand(1) .command( - `auth-cloud-implicit`, - `Loads credentials implicitly.`, + 'auth-cloud-implicit', + 'Loads credentials implicitly.', {}, authCloudImplicit ) .command( - `auth-cloud-explicit`, - `Loads credentials explicitly.`, + 'auth-cloud-explicit', + 'Loads credentials explicitly.', { projectId: { alias: 'p', @@ -99,12 +99,12 @@ const cli = require(`yargs`) }, authCloudExplicit ) - .example(`node $0 implicit`, `Loads credentials implicitly.`) - .example(`node $0 explicit`, `Loads credentials explicitly.`) + .example('node $0 implicit', 'Loads credentials implicitly.') + .example('node $0 explicit', 'Loads credentials explicitly.') .wrap(120) .recommendCommands() .epilogue( - `For more information, see https://cloud.google.com/docs/authentication` + 'For more information, see https://cloud.google.com/docs/authentication' ) .help() .strict(); diff --git a/auth/system-test/auth.test.js b/auth/system-test/auth.test.js index 4d38acd669..dee72e4532 100644 --- a/auth/system-test/auth.test.js +++ b/auth/system-test/auth.test.js @@ -26,11 +26,11 @@ const {BUCKET_NAME} = process.env; before(() => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); }); diff --git a/cloud-sql/mysql/mysql/package.json b/cloud-sql/mysql/mysql/package.json index ea2e0fb04b..d4726c75d4 100644 --- a/cloud-sql/mysql/mysql/package.json +++ b/cloud-sql/mysql/mysql/package.json @@ -27,7 +27,7 @@ "devDependencies": { "mocha": "^8.0.0", "proxyquire": "^2.1.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "sinon": "^9.0.0" } } diff --git a/cloud-sql/mysql/mysql/server.js b/cloud-sql/mysql/mysql/server.js index 7e6c3e8305..bf85ca5357 100644 --- a/cloud-sql/mysql/mysql/server.js +++ b/cloud-sql/mysql/mysql/server.js @@ -42,9 +42,9 @@ const logger = winston.createLogger({ }); // [START cloud_sql_mysql_mysql_create_tcp] -const createTcpPool = async (config) => { +const createTcpPool = async config => { // Extract host and port from socket address - const dbSocketAddr = process.env.DB_HOST.split(":") + const dbSocketAddr = process.env.DB_HOST.split(':'); // Establish a connection to the database return await mysql.createPool({ @@ -54,14 +54,14 @@ const createTcpPool = async (config) => { host: dbSocketAddr[0], // e.g. '127.0.0.1' port: dbSocketAddr[1], // e.g. '3306' // ... Specify additional properties here. - ...config + ...config, }); -} +}; // [END cloud_sql_mysql_mysql_create_tcp] // [START cloud_sql_mysql_mysql_create_socket] -const createUnixSocketPool = async (config) => { - const dbSocketPath = process.env.DB_SOCKET_PATH || "/cloudsql" +const createUnixSocketPool = async config => { + const dbSocketPath = process.env.DB_SOCKET_PATH || '/cloudsql'; // Establish a connection to the database return await mysql.createPool({ @@ -71,9 +71,9 @@ const createUnixSocketPool = async (config) => { // If connecting via unix domain socket, specify the path socketPath: `${dbSocketPath}/${process.env.CLOUD_SQL_CONNECTION_NAME}`, // Specify additional properties here. - ...config + ...config, }); -} +}; // [END cloud_sql_mysql_mysql_create_socket] const createPool = async () => { @@ -104,34 +104,33 @@ const createPool = async () => { // The mysql module automatically uses exponential delays between failed // connection attempts. // [END cloud_sql_mysql_mysql_backoff] - } + }; if (process.env.DB_HOST) { return await createTcpPool(config); } else { return await createUnixSocketPool(config); } - }; -const ensureSchema = async (pool) => { +const ensureSchema = async pool => { // Wait for tables to be created (if they don't already exist). await pool.query( `CREATE TABLE IF NOT EXISTS votes ( vote_id SERIAL NOT NULL, time_cast timestamp NOT NULL, candidate CHAR(6) NOT NULL, PRIMARY KEY (vote_id) );` ); - console.log(`Ensured that table 'votes' exists`); + console.log("Ensured that table 'votes' exists"); }; let pool; const poolPromise = createPool() - .then(async (pool) => { + .then(async pool => { await ensureSchema(pool); return pool; }) - .catch((err) => { + .catch(err => { logger.error(err); - process.exit(1) + process.exit(1); }); app.use(async (req, res, next) => { @@ -141,8 +140,7 @@ app.use(async (req, res, next) => { try { pool = await poolPromise; next(); - } - catch (err) { + } catch (err) { logger.error(err); return next(err); } @@ -172,8 +170,7 @@ app.get('/', async (req, res) => { tabCount: tabsVotes.count, spaceCount: spacesVotes.count, }); - } - catch(err) { + } catch (err) { logger.error(err); res .status(500) @@ -182,7 +179,6 @@ app.get('/', async (req, res) => { ) .end(); } - }); // Handle incoming vote requests and inserting them into the database. diff --git a/cloud-sql/mysql/mysql/test/server.test.js b/cloud-sql/mysql/mysql/test/server.test.js index 485bc5acc6..6edfd74957 100644 --- a/cloud-sql/mysql/mysql/test/server.test.js +++ b/cloud-sql/mysql/mysql/test/server.test.js @@ -30,7 +30,7 @@ it('should display the default page', async () => { await request(server) .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert.ok(response.text.includes('Tabs VS Spaces')); }); }); @@ -41,8 +41,7 @@ it('should handle insert error', async () => { await request(server) .post('/') .expect(400) - .expect((response) => { + .expect(response => { assert.ok(response.text.includes(expectedResult)); }); }); - diff --git a/cloud-sql/postgres/knex/createTable.js b/cloud-sql/postgres/knex/createTable.js index 5ede208e37..3af01777c1 100644 --- a/cloud-sql/postgres/knex/createTable.js +++ b/cloud-sql/postgres/knex/createTable.js @@ -16,32 +16,32 @@ const Knex = require('knex'); -const createTable = async (config) => { - const socketPath = process.env.DB_SOCKET_PATH || "/cloudsql"; - +const createTable = async config => { + const socketPath = process.env.DB_SOCKET_PATH || '/cloudsql'; + // Connect to the database - if (config.dbHost){ - const dbSocketAddr = config.dbHost.split(":"); + if (config.dbHost) { + const dbSocketAddr = config.dbHost.split(':'); config.host = dbSocketAddr[0]; config.port = dbSocketAddr[1]; } else { config.host = `${socketPath}/${config.connectionName}`; } - + const knex = Knex({client: 'pg', connection: config}); // Create the "votes" table try { - await knex.schema.createTable('votes', (table) => { + await knex.schema.createTable('votes', table => { table.bigIncrements('vote_id').notNull(); table.timestamp('time_cast').notNull(); table.specificType('candidate', 'CHAR(6) NOT NULL'); }); - console.log(`Successfully created 'votes' table.`); + console.log("Successfully created 'votes' table."); return knex.destroy(); } catch (err) { - console.error(`Failed to create 'votes' table:`, err); + console.error("Failed to create 'votes' table:", err); if (knex) { knex.destroy(); } diff --git a/cloud-sql/postgres/knex/package.json b/cloud-sql/postgres/knex/package.json index 567023ed70..cbee5415a9 100644 --- a/cloud-sql/postgres/knex/package.json +++ b/cloud-sql/postgres/knex/package.json @@ -28,6 +28,6 @@ }, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/cloud-sql/postgres/knex/server.js b/cloud-sql/postgres/knex/server.js index 1d57c38cf8..be4f099cf0 100644 --- a/cloud-sql/postgres/knex/server.js +++ b/cloud-sql/postgres/knex/server.js @@ -45,9 +45,9 @@ const logger = winston.createLogger({ }); // [START cloud_sql_postgres_knex_create_tcp] -const connectWithTcp = (config) => { +const connectWithTcp = config => { // Extract host and port from socket address - const dbSocketAddr = process.env.DB_HOST.split(":") // e.g. '127.0.0.1:5432' + const dbSocketAddr = process.env.DB_HOST.split(':'); // e.g. '127.0.0.1:5432' // Establish a connection to the database return Knex({ @@ -60,14 +60,14 @@ const connectWithTcp = (config) => { port: dbSocketAddr[1], // e.g. '5432' }, // ... Specify additional properties here. - ...config + ...config, }); -} +}; // [END cloud_sql_postgres_knex_create_tcp] // [START cloud_sql_postgres_knex_create_socket] -const connectWithUnixSockets = (config) => { - const dbSocketPath = process.env.DB_SOCKET_PATH || "/cloudsql" +const connectWithUnixSockets = config => { + const dbSocketPath = process.env.DB_SOCKET_PATH || '/cloudsql'; // Establish a connection to the database return Knex({ @@ -79,9 +79,9 @@ const connectWithUnixSockets = (config) => { host: `${dbSocketPath}/${process.env.CLOUD_SQL_CONNECTION_NAME}`, }, // ... Specify additional properties here. - ...config + ...config, }); -} +}; // [END cloud_sql_postgres_knex_create_socket] // Initialize Knex, a Node.js SQL query builder library with built-in connection pooling. @@ -89,7 +89,7 @@ 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. - let config = {pool: {}}; + const config = {pool: {}}; // [START cloud_sql_postgres_knex_limit] // 'max' limits the total number of concurrent connections this pool will keep. Ideal @@ -101,16 +101,16 @@ const connect = () => { // [END cloud_sql_postgres_knex_limit] // [START cloud_sql_postgres_knex_timeout] - // 'acquireTimeoutMillis' is the number of milliseconds before a timeout occurs when acquiring a - // connection from the pool. This is slightly different from connectionTimeout, because acquiring + // 'acquireTimeoutMillis' is the number of milliseconds before a timeout occurs when acquiring a + // connection from the pool. This is slightly different from connectionTimeout, because acquiring // a pool connection does not always involve making a new connection, and may include multiple retries. // when making a connection config.pool.acquireTimeoutMillis = 60000; // 60 seconds // 'createTimeoutMillis` is the maximum number of milliseconds to wait trying to establish an - // initial connection before retrying. + // initial connection before retrying. // After acquireTimeoutMillis has passed, a timeout exception will be thrown. config.createTimeoutMillis = 30000; // 30 seconds - // 'idleTimeoutMillis' is the number of milliseconds a connection must sit idle in the pool + // 'idleTimeoutMillis' is the number of milliseconds a connection must sit idle in the pool // and not be checked out before it is automatically closed. config.idleTimeoutMillis = 600000; // 10 minutes // [END cloud_sql_postgres_knex_timeout] @@ -155,7 +155,7 @@ const insertVote = async (knex, vote) => { * @param {object} knex The Knex connection object. * @returns {Promise} */ -const getVotes = async (knex) => { +const getVotes = async knex => { return await knex .select('candidate', 'time_cast') .from('votes') @@ -211,14 +211,12 @@ app.get('/', async (req, res) => { voteDiff: voteDiff, leaderMessage: leaderMessage, }); - } - catch(err) { + } catch (err) { res .status(500) .send('Unable to load page; see logs for more details.') .end(); } - }); app.post('/', async (req, res) => { diff --git a/cloud-sql/postgres/knex/test/createTable.test.js b/cloud-sql/postgres/knex/test/createTable.test.js index 06b3d5e551..d3f4c67663 100644 --- a/cloud-sql/postgres/knex/test/createTable.test.js +++ b/cloud-sql/postgres/knex/test/createTable.test.js @@ -22,7 +22,7 @@ const {exec} = require('child_process'); const cwd = path.join(__dirname, '..'); const {DB_USER, DB_PASS, DB_NAME, CONNECTION_NAME, DB_HOST} = process.env; -const SOCKET_PATH = process.env.DB_SOCKET_PATH || "/cloudsql" +const SOCKET_PATH = process.env.DB_SOCKET_PATH || '/cloudsql'; before(async () => { const connection = { @@ -32,7 +32,7 @@ before(async () => { }; if (DB_HOST) { - const dbSocketAddr = process.env.DB_HOST.split(":"); + const dbSocketAddr = process.env.DB_HOST.split(':'); connection.host = dbSocketAddr[0]; connection.port = dbSocketAddr[1]; } else { @@ -50,18 +50,18 @@ before(async () => { } }); -it('should create a table', (done) => { +it('should create a table', done => { exec( `node createTable.js ${DB_USER} ${DB_PASS} ${DB_NAME} ${CONNECTION_NAME} ${DB_HOST}`, {cwd}, (err, stdout) => { - assert.ok(stdout.includes(`Successfully created 'votes' table.`)); + assert.ok(stdout.includes("Successfully created 'votes' table.")); done(); } ); }); -it('should handle existing tables', (done) => { +it('should handle existing tables', done => { exec( `node createTable.js ${DB_USER} ${DB_PASS} ${DB_NAME} ${CONNECTION_NAME} ${DB_HOST}`, {cwd}, diff --git a/cloud-sql/postgres/knex/test/server.test.js b/cloud-sql/postgres/knex/test/server.test.js index 8b16e62977..0b3b726ae5 100644 --- a/cloud-sql/postgres/knex/test/server.test.js +++ b/cloud-sql/postgres/knex/test/server.test.js @@ -30,7 +30,7 @@ it('should display the default page', async () => { await request(server) .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert.ok(response.text.includes('Tabs VS Spaces')); }); }); @@ -41,7 +41,7 @@ it('should handle insert error', async () => { await request(server) .post('/') .expect(400) - .expect((response) => { + .expect(response => { assert.ok(response.text.includes(expectedResult)); }); }); diff --git a/cloud-sql/sqlserver/mssql/package.json b/cloud-sql/sqlserver/mssql/package.json index 4a16329025..607016d80c 100644 --- a/cloud-sql/sqlserver/mssql/package.json +++ b/cloud-sql/sqlserver/mssql/package.json @@ -26,6 +26,6 @@ }, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/cloud-sql/sqlserver/mssql/server.js b/cloud-sql/sqlserver/mssql/server.js index 3924d7d464..1635ddbf5a 100644 --- a/cloud-sql/sqlserver/mssql/server.js +++ b/cloud-sql/sqlserver/mssql/server.js @@ -15,7 +15,7 @@ 'use strict'; const express = require('express'); -const mssql = require('mssql') +const mssql = require('mssql'); const bodyParser = require('body-parser'); const app = express(); @@ -41,10 +41,9 @@ const logger = winston.createLogger({ transports: [new winston.transports.Console(), loggingWinston], }); -// [START cloud_sql_server_mssql_create] // [START cloud_sql_sqlserver_mssql_create] const createPool = async () => { - let config = {pool: {}}; + const config = {pool: {}}; config.user = process.env.DB_USER; // e.g. 'my-db-user' config.password = process.env.DB_PASS; // e.g. 'my-db-password' config.database = process.env.DB_NAME; // e.g. 'my-database' @@ -54,50 +53,42 @@ const createPool = async () => { // [START_EXCLUDE] - // [START cloud_sql_server_mssql_timeout] // [START cloud_sql_sqlserver_mssql_timeout] // 'connectionTimeout` is the maximum number of milliseconds to wait trying to establish an // initial connection. After the specified amount of time, an exception will be thrown. config.connectionTimeout = 30000; - // 'acquireTimeoutMillis' is the number of milliseconds before a timeout occurs when acquiring a + // 'acquireTimeoutMillis' is the number of milliseconds before a timeout occurs when acquiring a // connection from the pool. config.pool.acquireTimeoutMillis = 30000; - // 'idleTimeoutMillis' is the number of milliseconds a connection must sit idle in the pool + // 'idleTimeoutMillis' is the number of milliseconds a connection must sit idle in the pool // and not be checked out before it is automatically closed - config.pool.idleTimeoutMillis = 600000, - // [END cloud_sql_sqlserver_mssql_timeout] - // [END cloud_sql_server_mssql_timeout] - - // [START cloud_sql_server_mssql_limit] - // [START cloud_sql_sqlserver_mssql_limit] - // 'max' limits the total number of concurrent connections this pool will keep. Ideal - // values for this setting are highly variable on app design, infrastructure, and database. - config.pool.max = 5; + (config.pool.idleTimeoutMillis = 600000), + // [END cloud_sql_sqlserver_mssql_timeout] + + // [START cloud_sql_sqlserver_mssql_limit] + // 'max' limits the total number of concurrent connections this pool will keep. Ideal + // values for this setting are highly variable on app design, infrastructure, and database. + (config.pool.max = 5); // 'min' is the minimum number of idle connections maintained in the pool. // Additional connections will be established to meet this value unless the pool is full. config.pool.min = 1; // [END cloud_sql_sqlserver_mssql_limit] - // [END cloud_sql_server_mssql_limit] - // [START cloud_sql_server_mssql_backoff] // [START cloud_sql_sqlserver_mssql_backoff] // The node-mssql module uses a built-in retry strategy which does not implement backoff. // 'createRetryIntervalMillis' is the number of milliseconds to wait in between retries. config.pool.createRetryIntervalMillis = 200; // [END cloud_sql_sqlserver_mssql_backoff] - // [END cloud_sql_server_mssql_backoff] // [END_EXCLUDE] return await mssql.connect(config); }; // [END cloud_sql_sqlserver_mssql_create] -// [END cloud_sql_server_mssql_create] -const ensureSchema = async (pool) => { +const ensureSchema = async pool => { // Wait for tables to be created (if they don't already exist). - await pool.request() - .query( - `IF NOT EXISTS ( + await pool.request().query( + `IF NOT EXISTS ( SELECT * FROM sysobjects WHERE name='votes' and xtype='U') CREATE TABLE votes ( vote_id INT NOT NULL IDENTITY, @@ -105,16 +96,16 @@ const ensureSchema = async (pool) => { candidate VARCHAR(6) NOT NULL, PRIMARY KEY (vote_id));` ); - console.log(`Ensured that table 'votes' exists`); + console.log("Ensured that table 'votes' exists"); }; let pool; const poolPromise = createPool() - .then(async (pool) => { + .then(async pool => { await ensureSchema(pool); return pool; }) - .catch((err) => { + .catch(err => { logger.error(err); process.exit(1); }); @@ -126,8 +117,7 @@ app.use(async (req, res, next) => { try { pool = await poolPromise; next(); - } - catch (err) { + } catch (err) { logger.error(err); return next(err); } @@ -135,27 +125,31 @@ app.use(async (req, res, next) => { // Serve the index page, showing vote tallies. app.get('/', async (req, res, next) => { - try { - // Get the 5 most recent votes. - const recentVotesQuery = pool.request().query( - 'SELECT TOP(5) candidate, time_cast FROM votes ORDER BY time_cast DESC' - ); - - // Get votes - const stmt = 'SELECT COUNT(vote_id) as count FROM votes WHERE candidate=@candidate'; - - const tabsQuery = pool.request() - .input('candidate', mssql.VarChar(6), 'TABS') - .query(stmt); + // Get the 5 most recent votes. + const recentVotesQuery = pool + .request() + .query( + 'SELECT TOP(5) candidate, time_cast FROM votes ORDER BY time_cast DESC' + ); + + // Get votes + const stmt = + 'SELECT COUNT(vote_id) as count FROM votes WHERE candidate=@candidate'; + + const tabsQuery = pool + .request() + .input('candidate', mssql.VarChar(6), 'TABS') + .query(stmt); + + const spacesQuery = pool + .request() + .input('candidate', mssql.VarChar(6), 'SPACES') + .query(stmt); + + // Run queries concurrently, and wait for them to complete + // This is faster than await-ing each query object as it is created - const spacesQuery = pool.request() - .input('candidate', mssql.VarChar(6), 'SPACES') - .query(stmt); - - // Run queries concurrently, and wait for them to complete - // This is faster than await-ing each query object as it is created - const recentVotes = await recentVotesQuery; const tabsVotes = await tabsQuery; const spacesVotes = await spacesQuery; @@ -165,8 +159,7 @@ app.get('/', async (req, res, next) => { tabCount: tabsVotes.recordset[0].count, spaceCount: spacesVotes.recordset[0].count, }); - } - catch (err) { + } catch (err) { logger.error(err); res .status(500) @@ -186,21 +179,21 @@ app.post('/', async (req, res, next) => { return res.status(400).send('Invalid team specified.').end(); } - // [START cloud_sql_server_mssql_connection] - // [START cloud_sql_sqlserver_mssql_connection] + // [START cloud_sql_sqlserver_mssql_connection] try { - const stmt = 'INSERT INTO votes (time_cast, candidate) VALUES (@timestamp, @team)'; + const stmt = + 'INSERT INTO votes (time_cast, candidate) VALUES (@timestamp, @team)'; // Using a prepared statement protects against SQL injection attacks. - // When prepare is called, a single connection is acquired from the connection pool + // When prepare is called, a single connection is acquired from the connection pool // and all subsequent executions are executed exclusively on this connection. const ps = new mssql.PreparedStatement(pool); - ps.input('timestamp', mssql.DateTime) - ps.input('team', mssql.VarChar(6)) - await ps.prepare(stmt) + ps.input('timestamp', mssql.DateTime); + ps.input('team', mssql.VarChar(6)); + await ps.prepare(stmt); await ps.execute({ timestamp: timestamp, - team: team - }) + team: team, + }); await ps.unprepare(); } catch (err) { // If something goes wrong, handle the error in this section. This might @@ -217,7 +210,6 @@ app.post('/', async (req, res, next) => { // [END_EXCLUDE] } // [END cloud_sql_sqlserver_mssql_connection] - // [END cloud_sql_server_mssql_connection] res.status(200).send(`Successfully voted for ${team} at ${timestamp}`).end(); }); @@ -228,8 +220,8 @@ const server = app.listen(PORT, () => { console.log('Press Ctrl+C to quit.'); }); -var environment = process.env.NODE_ENV || 'development'; -if (environment === `development`) { +const environment = process.env.NODE_ENV || 'development'; +if (environment === 'development') { process.on('unhandledRejection', err => { console.error(err); process.exit(1); diff --git a/cloud-sql/sqlserver/mssql/test/server.test.js b/cloud-sql/sqlserver/mssql/test/server.test.js index ee1bb2e9e5..c461c02fcb 100644 --- a/cloud-sql/sqlserver/mssql/test/server.test.js +++ b/cloud-sql/sqlserver/mssql/test/server.test.js @@ -30,7 +30,7 @@ it('should display the default page', async () => { await request(server) .get('/') .expect(200) - .expect((response) => { + .expect(response => { assert.ok(response.text.includes('Tabs VS Spaces')); }); }); @@ -41,7 +41,7 @@ it('should handle insert error', async () => { await request(server) .post('/') .expect(400) - .expect((response) => { + .expect(response => { assert.ok(response.text.includes(expectedResult)); }); }); diff --git a/cloud-tasks/function/test/index.test.js b/cloud-tasks/function/test/index.test.js index e2b32f6be0..438e4802fc 100644 --- a/cloud-tasks/function/test/index.test.js +++ b/cloud-tasks/function/test/index.test.js @@ -23,7 +23,7 @@ const key = process.env.SENDGRID_API_KEY; const getSample = function () { const requestPromise = sinon .stub() - .returns(new Promise((resolve) => resolve('test'))); + .returns(new Promise(resolve => resolve('test'))); return { program: proxyquire('../', { diff --git a/composer/composer_transform_csv_to_json.js b/composer/composer_transform_csv_to_json.js index 2544eeca5a..db5be1d43e 100644 --- a/composer/composer_transform_csv_to_json.js +++ b/composer/composer_transform_csv_to_json.js @@ -40,8 +40,8 @@ module.exports = function main( var jsonString = JSON.stringify(weatherInCity); return jsonString; } - -// [END composer_transform_csv_to_json] - + + // [END composer_transform_csv_to_json] + return transformCSVtoJSON(line); }; diff --git a/composer/functions/composer-storage-trigger/index.js b/composer/functions/composer-storage-trigger/index.js index 52c9ee0916..ade0ffccc2 100644 --- a/composer/functions/composer-storage-trigger/index.js +++ b/composer/functions/composer-storage-trigger/index.js @@ -31,7 +31,7 @@ const FormData = require('form-data'); * @param {!Object} data The Cloud Functions event data. * @returns {Promise} */ -exports.triggerDag = async (data) => { +exports.triggerDag = async data => { // Fill in your Composer environment information here. // The project that holds your function diff --git a/composer/functions/composer-storage-trigger/test/index.test.js b/composer/functions/composer-storage-trigger/test/index.test.js index 9533fa040f..d75fe0b153 100644 --- a/composer/functions/composer-storage-trigger/test/index.test.js +++ b/composer/functions/composer-storage-trigger/test/index.test.js @@ -18,7 +18,7 @@ const proxyquire = require('proxyquire').noCallThru(); const sinon = require('sinon'); const assert = require('assert'); -const getSample = (FetchStub) => { +const getSample = FetchStub => { return { program: proxyquire('../', { 'node-fetch': FetchStub, diff --git a/containerengine/hello-world/package.json b/containerengine/hello-world/package.json index e2e96725d4..b83979dcca 100644 --- a/containerengine/hello-world/package.json +++ b/containerengine/hello-world/package.json @@ -20,6 +20,6 @@ "dependencies": {}, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/datacatalog/cloud-client/createEntryGroup.js b/datacatalog/cloud-client/createEntryGroup.js index 68eb946765..4653353909 100644 --- a/datacatalog/cloud-client/createEntryGroup.js +++ b/datacatalog/cloud-client/createEntryGroup.js @@ -23,7 +23,10 @@ * For more information, see the README.md under /datacatalog and the * documentation at https://cloud.google.com/data-catalog/docs. */ -const main = async (projectId = process.env.GOOGLE_CLOUD_PROJECT, entryGroupId) => { +const main = async ( + projectId = process.env.GOOGLE_CLOUD_PROJECT, + entryGroupId +) => { // [START datacatalog_create_entry_group_tag] // ------------------------------- // Import required modules. diff --git a/datacatalog/cloud-client/system-test/createEntryGroup.test.js b/datacatalog/cloud-client/system-test/createEntryGroup.test.js index 4a8f625c5b..bdaec42d5e 100644 --- a/datacatalog/cloud-client/system-test/createEntryGroup.test.js +++ b/datacatalog/cloud-client/system-test/createEntryGroup.test.js @@ -31,16 +31,16 @@ const datacatalog = new DataCatalogClient(); before(() => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); }); describe('createEntryGroup', () => { - it('should create a entry group', (done) => { + it('should create a entry group', done => { const expectedName = `projects/${projectId}/locations/${location}/entryGroups/${entryGroupId}`; exec( `node createEntryGroup.js ${projectId} ${entryGroupId}`, diff --git a/datacatalog/cloud-client/system-test/createFilesetEntry.test.js b/datacatalog/cloud-client/system-test/createFilesetEntry.test.js index 657bb085a3..b664d94f9b 100644 --- a/datacatalog/cloud-client/system-test/createFilesetEntry.test.js +++ b/datacatalog/cloud-client/system-test/createFilesetEntry.test.js @@ -32,21 +32,21 @@ const datacatalog = new DataCatalogClient(); before(() => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); }); describe('createFilesetEntry', () => { - before((done) => { + before(done => { // Must create entryGroup before creating entry exec(`node createEntryGroup.js ${projectId} ${entryGroupId}`, {cwd}, done); }); - it('should create a fileset entry', (done) => { + it('should create a fileset entry', done => { const expectedLinkedResource = `//datacatalog.googleapis.com/projects/${projectId}/locations/${location}/entryGroups/${entryGroupId}/entries/${entryId}`; exec( `node createFilesetEntry.js ${projectId} ${entryGroupId} ${entryId}`, diff --git a/datacatalog/cloud-client/system-test/lookupEntry.test.js b/datacatalog/cloud-client/system-test/lookupEntry.test.js index 644b47cb1e..cb4a9b4b1f 100644 --- a/datacatalog/cloud-client/system-test/lookupEntry.test.js +++ b/datacatalog/cloud-client/system-test/lookupEntry.test.js @@ -22,16 +22,16 @@ const {exec} = require('child_process'); before(() => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); }); describe('lookupEntry lookup', () => { - it('should lookup a dataset entry', (done) => { + it('should lookup a dataset entry', done => { const projectId = 'bigquery-public-data'; const datasetId = 'new_york_taxi_trips'; const expectedLinkedResource = `//bigquery.googleapis.com/projects/${projectId}/datasets/${datasetId}`; diff --git a/datacatalog/quickstart/system-test/createFilesetEntry.test.js b/datacatalog/quickstart/system-test/createFilesetEntry.test.js index a1b5907291..7d46e11990 100644 --- a/datacatalog/quickstart/system-test/createFilesetEntry.test.js +++ b/datacatalog/quickstart/system-test/createFilesetEntry.test.js @@ -41,7 +41,7 @@ before(() => { }); describe('createFilesetEntry', () => { - it('should create a fileset entry', (done) => { + it('should create a fileset entry', done => { const expectedLinkedResource = `//datacatalog.googleapis.com/projects/${projectId}/locations/${location}/entryGroups/${entryGroupId}/entries/${entryId}`; exec( `node createFilesetEntry.js ${projectId} ${entryGroupId} ${entryId}`, diff --git a/datacatalog/quickstart/system-test/deleteFilesetEntry.test.js b/datacatalog/quickstart/system-test/deleteFilesetEntry.test.js index 8179df7ebe..a83a602379 100644 --- a/datacatalog/quickstart/system-test/deleteFilesetEntry.test.js +++ b/datacatalog/quickstart/system-test/deleteFilesetEntry.test.js @@ -41,7 +41,7 @@ before(() => { }); describe('deleteFilesetEntry', () => { - before((done) => { + before(done => { // Must create an entry to be deleted. exec( `node createFilesetEntry.js ${projectId} ${entryGroupId} ${entryId}`, @@ -50,7 +50,7 @@ describe('deleteFilesetEntry', () => { ); }); - it('should delete a fileset entry', (done) => { + it('should delete a fileset entry', done => { exec( `node deleteFilesetEntry.js ${projectId} ${entryGroupId} ${entryId}`, {cwd}, diff --git a/datastore/functions/index.js b/datastore/functions/index.js index 91f45a70c5..35f30da559 100644 --- a/datastore/functions/index.js +++ b/datastore/functions/index.js @@ -19,7 +19,7 @@ const {Datastore} = require('@google-cloud/datastore'); // Instantiates a client const datastore = new Datastore(); -const makeErrorObj = (prop) => { +const makeErrorObj = prop => { return new Error( `${prop} not provided. Make sure you have a "${prop.toLowerCase()}" property in your request` ); @@ -33,7 +33,7 @@ const makeErrorObj = (prop) => { * @param {string} requestData.kind Datastore kind. * @returns {object} Datastore key object. */ -const getKeyFromRequestData = (requestData) => { +const getKeyFromRequestData = requestData => { if (!requestData.key) { return Promise.reject(makeErrorObj('Key')); } diff --git a/datastore/functions/test/index.test.js b/datastore/functions/test/index.test.js index 0e893ac3b4..81feafe39f 100644 --- a/datastore/functions/test/index.test.js +++ b/datastore/functions/test/index.test.js @@ -34,10 +34,10 @@ const VALUE = { description: 'Buy milk', }; -const errorMsg = (msg) => +const errorMsg = msg => `${msg} not provided. Make sure you have a "${msg.toLowerCase()}" property in your request`; -const handleLinuxFailures = async (proc) => { +const handleLinuxFailures = async proc => { try { return await proc; } catch (err) { @@ -50,10 +50,10 @@ const handleLinuxFailures = async (proc) => { }; // Wait for the HTTP server to start listening -const waitForReady = async (baseUrl) => { +const waitForReady = async baseUrl => { let ready = false; while (!ready) { - await new Promise((r) => setTimeout(r, 500)); + await new Promise(r => setTimeout(r, 500)); ready = await isReachable(baseUrl); } }; @@ -125,7 +125,7 @@ describe('functions/datastore', () => { }); it('set: Saves an entity', async () => { - const response = await fetch(`${BASE_URL}/set`,{ + const response = await fetch(`${BASE_URL}/set`, { method: 'POST', body: JSON.stringify({ kind: KIND, @@ -275,8 +275,8 @@ describe('functions/datastore', () => { assert.ok(res.send.calledWith(errorMsg('Kind'))); }); - it(`del: Doesn't fail when entity does not exist`, async () => { - const response = await fetch(`${BASE_URL}/del`,{ + it("del: Doesn't fail when entity does not exist", async () => { + const response = await fetch(`${BASE_URL}/del`, { method: 'POST', body: JSON.stringify({ kind: KIND, @@ -290,7 +290,7 @@ describe('functions/datastore', () => { }); it('del: Deletes an entity', async () => { - const response = await fetch( `${BASE_URL}/del`,{ + const response = await fetch(`${BASE_URL}/del`, { method: 'POST', body: JSON.stringify({ kind: KIND, diff --git a/endpoints/getting-started-grpc/client.js b/endpoints/getting-started-grpc/client.js index 0240e140cf..92b6c9cc57 100644 --- a/endpoints/getting-started-grpc/client.js +++ b/endpoints/getting-started-grpc/client.js @@ -83,7 +83,7 @@ const {argv} = require('yargs') default: 'world', global: true, }) - .check((argv) => { + .check(argv => { const valid = !!(argv.jwtAuthToken || argv.apiKey); if (!valid) { console.error('One of API_KEY or JWT_AUTH_TOKEN must be set.'); @@ -94,7 +94,7 @@ const {argv} = require('yargs') .help() .strict() .epilogue( - `For more information, see https://cloud.google.com/endpoints/docs` + 'For more information, see https://cloud.google.com/endpoints/docs' ); makeGrpcRequest(argv.jwtAuthToken, argv.apiKey, argv.host, argv.greetee); diff --git a/endpoints/getting-started-grpc/server.js b/endpoints/getting-started-grpc/server.js index 0ccf64d202..40806a8018 100644 --- a/endpoints/getting-started-grpc/server.js +++ b/endpoints/getting-started-grpc/server.js @@ -26,7 +26,7 @@ const sayHello = (call, callback) => { }; // Start an RPC server to handle Greeter service requests -const 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()); @@ -44,7 +44,7 @@ const {argv} = require('yargs') }) .wrap(120) .epilogue( - `For more information, see https://cloud.google.com/endpoints/docs` + 'For more information, see https://cloud.google.com/endpoints/docs' ); startServer(argv.port); diff --git a/endpoints/getting-started-grpc/system-test/endpoints.test.js b/endpoints/getting-started-grpc/system-test/endpoints.test.js index 5303ddc5ad..59226047cf 100644 --- a/endpoints/getting-started-grpc/system-test/endpoints.test.js +++ b/endpoints/getting-started-grpc/system-test/endpoints.test.js @@ -31,4 +31,4 @@ describe('server listening', () => { expect(isOpen).to.be.true; process.kill(child.pid, 'SIGTERM'); }); -}); \ No newline at end of file +}); diff --git a/endpoints/getting-started/package.json b/endpoints/getting-started/package.json index 8ea24ab353..2baf0616e9 100644 --- a/endpoints/getting-started/package.json +++ b/endpoints/getting-started/package.json @@ -24,6 +24,6 @@ "mocha": "^8.0.0", "proxyquire": "^2.1.0", "sinon": "^9.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/endpoints/getting-started/test/app.test.js b/endpoints/getting-started/test/app.test.js index cf39ca80d2..dd97b849a5 100644 --- a/endpoints/getting-started/test/app.test.js +++ b/endpoints/getting-started/test/app.test.js @@ -40,7 +40,7 @@ const getSample = () => { }; const stubConsole = function () { - sinon.stub(console, `error`); + sinon.stub(console, 'error'); }; //Restore console @@ -56,7 +56,7 @@ it('should echo a message', async () => { .post('/echo') .send({message: 'foo'}) .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual(response.body.message, 'foo'); }); }); @@ -65,7 +65,7 @@ it('should try to parse encoded info', async () => { await request(getSample().app) .get('/auth/info/googlejwt') .expect(200) - .expect((response) => { + .expect(response => { assert.deepStrictEqual(response.body, {id: 'anonymous'}); }); }); @@ -78,7 +78,7 @@ it('should successfully parse encoded info', async () => { Buffer.from(JSON.stringify({id: 'foo'})).toString('base64') ) .expect(200) - .expect((response) => { + .expect(response => { assert.deepStrictEqual(response.body, {id: 'foo'}); }); }); diff --git a/eventarc/audit-storage/app.js b/eventarc/audit-storage/app.js index d824472971..e854015fd9 100644 --- a/eventarc/audit-storage/app.js +++ b/eventarc/audit-storage/app.js @@ -19,11 +19,15 @@ const app = express(); app.use(express.json()); app.post('/', (req, res) => { if (!req.header('ce-subject')) { - return res.status(400).send('Bad Request: missing required header: ce-subject'); + return res + .status(400) + .send('Bad Request: missing required header: ce-subject'); } console.log(`Detected change in GCS bucket: ${req.header('ce-subject')}`); - return res.status(200).send(`Detected change in GCS bucket: ${req.header('ce-subject')}`); + return res + .status(200) + .send(`Detected change in GCS bucket: ${req.header('ce-subject')}`); }); module.exports = app; diff --git a/eventarc/audit-storage/package.json b/eventarc/audit-storage/package.json index 5871426b2b..8a18bdb37f 100644 --- a/eventarc/audit-storage/package.json +++ b/eventarc/audit-storage/package.json @@ -25,6 +25,6 @@ "got": "^11.5.0", "mocha": "^8.0.0", "sinon": "^9.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/eventarc/audit-storage/test/app.test.js b/eventarc/audit-storage/test/app.test.js index 9da7046c57..072016b03c 100644 --- a/eventarc/audit-storage/test/app.test.js +++ b/eventarc/audit-storage/test/app.test.js @@ -32,7 +32,7 @@ describe('Unit Tests', () => { }); describe('should fail', () => { - it(`on a Bad Request with an empty payload`, async () => { + it('on a Bad Request with an empty payload', async () => { await request.post('/').type('json').send('').expect(400); }); }); @@ -47,13 +47,19 @@ describe('Unit Tests', () => { console.log.restore(); }); - it(`with a minimally valid GCS event`, async () => { + it('with a minimally valid GCS event', async () => { await request .post('/') .set('ce-subject', 'test-subject') .send() .expect(200) - .expect(() => assert.ok(console.log.calledWith('Detected change in GCS bucket: test-subject'))); + .expect(() => + assert.ok( + console.log.calledWith( + 'Detected change in GCS bucket: test-subject' + ) + ) + ); }); }); }); diff --git a/eventarc/generic/app.js b/eventarc/generic/app.js index b59dbb527c..05eeaeaf26 100644 --- a/eventarc/generic/app.js +++ b/eventarc/generic/app.js @@ -19,7 +19,7 @@ const app = express(); app.use(express.json()); app.post('/', (req, res) => { console.log('Event received!'); - + console.log('HEADERS:'); delete req.headers.Authorization; // do not log authorization header console.log(JSON.stringify(req.headers)); @@ -34,4 +34,4 @@ app.post('/', (req, res) => { }); module.exports = app; -// [END eventarc_generic_handler] \ No newline at end of file +// [END eventarc_generic_handler] diff --git a/eventarc/generic/package.json b/eventarc/generic/package.json index 2da4aff11d..627b623611 100644 --- a/eventarc/generic/package.json +++ b/eventarc/generic/package.json @@ -24,7 +24,7 @@ "got": "^11.5.0", "mocha": "^8.0.0", "sinon": "^9.0.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "uuid": "^8.0.0" } } diff --git a/eventarc/generic/test/app.test.js b/eventarc/generic/test/app.test.js index 595b5f2c57..34b490930e 100644 --- a/eventarc/generic/test/app.test.js +++ b/eventarc/generic/test/app.test.js @@ -31,17 +31,20 @@ describe('Unit Tests', () => { }); describe('should succeed', () => { - it(`should relay the CloudEvent`, async () => { + it('should relay the CloudEvent', async () => { await request .post('/') .type('json') .set('ce-id', 1234) .set('Authorization', 'MY-SECRET-VALUE') // never logged .send({testkey: 'testvalue'}) - .expect((res) => { + .expect(res => { const responseBody = res.body; - assert.strictEqual(responseBody.headers.host.startsWith('127.0.0.1'), true); + assert.strictEqual( + responseBody.headers.host.startsWith('127.0.0.1'), + true + ); assert.strictEqual(+responseBody.headers['ce-id'], 1234); assert.strictEqual(responseBody.headers['Authorization'], undefined); assert.deepStrictEqual(responseBody.body, {testkey: 'testvalue'}); diff --git a/eventarc/pubsub/app.js b/eventarc/pubsub/app.js index ad32b6f74a..4437166062 100644 --- a/eventarc/pubsub/app.js +++ b/eventarc/pubsub/app.js @@ -14,7 +14,9 @@ // [START eventarc_pubsub_handler] const express = require('express'); -const {toMessagePublishedData} = require('@google/events/cloud/pubsub/v1/MessagePublishedData'); +const { + toMessagePublishedData, +} = require('@google/events/cloud/pubsub/v1/MessagePublishedData'); const app = express(); app.use(express.json()); @@ -33,14 +35,15 @@ app.post('/', (req, res) => { } // Cast to MessagePublishedEvent for IDE autocompletion const pubSubMessage = toMessagePublishedData(req.body); - const name = pubSubMessage.message && pubSubMessage.message.data - ? Buffer.from(pubSubMessage.message.data, 'base64').toString().trim() - : 'World'; - + const name = + pubSubMessage.message && pubSubMessage.message.data + ? Buffer.from(pubSubMessage.message.data, 'base64').toString().trim() + : 'World'; + const result = `Hello, ${name}! ID: ${req.get('ce-id') || ''}`; console.log(result); res.send(result); }); module.exports = app; -// [END eventarc_pubsub_handler] \ No newline at end of file +// [END eventarc_pubsub_handler] diff --git a/eventarc/pubsub/package.json b/eventarc/pubsub/package.json index 9decfdeb0a..d7054c3eae 100644 --- a/eventarc/pubsub/package.json +++ b/eventarc/pubsub/package.json @@ -19,14 +19,14 @@ "system-test": "test/runner.sh mocha test/system.test.js --timeout=10000" }, "dependencies": { - "@google/events": "^2.0.0", + "@google/events": "^3.0.0", "express": "^4.16.4" }, "devDependencies": { "got": "^11.5.0", "mocha": "^8.0.0", "sinon": "^9.0.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "uuid": "^8.0.0" } } diff --git a/eventarc/pubsub/test/app.test.js b/eventarc/pubsub/test/app.test.js index 69744c00b3..7cbd73d174 100644 --- a/eventarc/pubsub/test/app.test.js +++ b/eventarc/pubsub/test/app.test.js @@ -31,11 +31,11 @@ describe('Unit Tests', () => { }); describe('should fail', () => { - it(`on a Bad Request with an empty payload`, async () => { + it('on a Bad Request with an empty payload', async () => { await request.post('/').type('json').send('').expect(400); }); - it(`on a Bad Request with an invalid payload`, async () => { + it('on a Bad Request with an invalid payload', async () => { await request .post('/') .type('json') @@ -43,41 +43,41 @@ describe('Unit Tests', () => { .expect(400); }); - it(`on a Bad Request with an invalid mimetype`, async () => { + it('on a Bad Request with an invalid mimetype', async () => { await request.post('/').type('text').send('{message: true}').expect(400); }); }); describe('should succeed', () => { - const data = Buffer.from('Events').toString(`base64`); - - it(`with empty Pub/Sub Message`, async () => { + const data = Buffer.from('Events').toString('base64'); + + it('with empty Pub/Sub Message', async () => { await request .post('/') .type('json') .send({message: {data: ''}}) - .expect((res) => { + .expect(res => { assert.equal(res.text, 'Hello, World! ID: '); }); }); - it(`with a minimally valid Pub/Sub Message`, async () => { + it('with a minimally valid Pub/Sub Message', async () => { await request .post('/') .type('json') .send({message: {data}}) - .expect((res) => { + .expect(res => { assert.equal(res.text, 'Hello, Events! ID: '); }); }); - it(`with CloudEvent HTTP headers`, async () => { + it('with CloudEvent HTTP headers', async () => { await request .post('/') .type('json') .set('ce-id', 1234) .send({message: {data}}) - .expect((res) => { + .expect(res => { assert.equal(res.text, 'Hello, Events! ID: 1234'); }); }); diff --git a/functions/billing/index.js b/functions/billing/index.js index 61f877adc0..54b5008f1e 100644 --- a/functions/billing/index.js +++ b/functions/billing/index.js @@ -35,7 +35,9 @@ const CHANNEL = process.env.SLACK_CHANNEL || 'general'; exports.notifySlack = async (pubsubEvent, context) => { const pubsubAttrs = pubsubEvent.attributes; const pubsubData = Buffer.from(pubsubEvent.data, 'base64').toString(); - const budgetNotificationText = `${JSON.stringify(pubsubAttrs)}, ${pubsubData}`; + const budgetNotificationText = `${JSON.stringify( + pubsubAttrs + )}, ${pubsubData}`; await slack.chat.postMessage({ token: BOT_ACCESS_TOKEN, @@ -57,9 +59,9 @@ exports.stopBilling = async (pubsubEvent, context) => { if (pubsubData.costAmount <= pubsubData.budgetAmount) { return `No action necessary. (Current cost: ${pubsubData.costAmount})`; } - + if (!PROJECT_ID) { - return `No project specified`; + return 'No project specified'; } _setAuthCredential(); @@ -80,7 +82,7 @@ const _setAuthCredential = () => { scopes: [ 'https://www.googleapis.com/auth/cloud-billing', 'https://www.googleapis.com/auth/cloud-platform', - ] + ], }); // Set credential globally for all requests @@ -95,12 +97,14 @@ const _setAuthCredential = () => { * @param {string} projectName Name of project to check if billing is enabled * @return {bool} Whether project has billing enabled or not */ -const _isBillingEnabled = async (projectName) => { +const _isBillingEnabled = async projectName => { try { const res = await billing.getBillingInfo({name: projectName}); return res.data.billingEnabled; } catch (e) { - console.log('Unable to determine if billing is enabled on specified project, assuming billing is enabled'); + console.log( + 'Unable to determine if billing is enabled on specified project, assuming billing is enabled' + ); return true; } }; @@ -110,7 +114,7 @@ const _isBillingEnabled = async (projectName) => { * @param {string} projectName Name of project disable billing on * @return {string} Text containing response from disabling billing */ -const _disableBillingForProject = async (projectName) => { +const _disableBillingForProject = async projectName => { const res = await billing.updateBillingInfo({ name: projectName, resource: {billingAccountName: ''}, // Disable billing @@ -175,8 +179,8 @@ const _listRunningInstances = async (projectId, zone) => { }); const instances = res.data.items || []; - const ranInstances = instances.filter((item) => item.status === 'RUNNING'); - return ranInstances.map((item) => item.name); + const ranInstances = instances.filter(item => item.status === 'RUNNING'); + return ranInstances.map(item => item.name); }; /** @@ -185,14 +189,14 @@ const _listRunningInstances = async (projectId, zone) => { */ const _stopInstances = async (projectId, zone, instanceNames) => { await Promise.all( - instanceNames.map((instanceName) => { + instanceNames.map(instanceName => { return compute.instances .stop({ project: projectId, zone: zone, instance: instanceName, }) - .then((res) => { + .then(res => { console.log(`Instance stopped successfully: ${instanceName}`); return res.data; }); @@ -224,10 +228,8 @@ const _listStoppedInstances = async (projectId, zone) => { }); const instances = res.data.items || []; - const stoppedInstances = instances.filter( - (item) => item.status !== 'RUNNING' - ); - return stoppedInstances.map((item) => item.name); + const stoppedInstances = instances.filter(item => item.status !== 'RUNNING'); + return stoppedInstances.map(item => item.name); }; /** @@ -239,7 +241,7 @@ const _startInstances = async (projectId, zone, instanceNames) => { return 'No stopped instances were found.'; } await Promise.all( - instanceNames.map((instanceName) => { + instanceNames.map(instanceName => { return compute.instances.start({ project: projectId, zone: zone, diff --git a/functions/billing/package.json b/functions/billing/package.json index 6468d06f17..614025f8a8 100644 --- a/functions/billing/package.json +++ b/functions/billing/package.json @@ -14,7 +14,7 @@ "license": "Apache-2.0", "dependencies": { "google-auth-library": "^6.0.0", - "googleapis": "^61.0.0", + "googleapis": "^62.0.0", "slack": "^11.0.1" }, "devDependencies": { diff --git a/functions/billing/test/index.test.js b/functions/billing/test/index.test.js index 8d4b5188cb..e0be81b10b 100644 --- a/functions/billing/test/index.test.js +++ b/functions/billing/test/index.test.js @@ -39,7 +39,7 @@ after(async () => { await require('../').startBilling(pubsubMessage); }); -const handleLinuxFailures = async (proc) => { +const handleLinuxFailures = async proc => { try { return await proc; } catch (err) { diff --git a/functions/billing/test/periodic.test.js b/functions/billing/test/periodic.test.js index b2da71e6dc..60156479b1 100644 --- a/functions/billing/test/periodic.test.js +++ b/functions/billing/test/periodic.test.js @@ -49,14 +49,14 @@ before(async () => { {retries: 8} ); } catch (err) { - console.error(`Failed to restart GCE instances:`, err); + console.error('Failed to restart GCE instances:', err); } }); describe('functions_billing_limit', () => { it('should shut down GCE instances when budget is exceeded', async () => { const ffProc = execPromise( - `functions-framework --target=limitUse --signature-type=event`, + 'functions-framework --target=limitUse --signature-type=event', {timeout: 1000, shell: true, cwd} ); diff --git a/functions/concepts/package.json b/functions/concepts/package.json index b1bcda8e53..1be7811181 100644 --- a/functions/concepts/package.json +++ b/functions/concepts/package.json @@ -17,7 +17,7 @@ "devDependencies": { "mocha": "^8.0.0", "sinon": "^9.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" }, "scripts": { "test": "mocha test/*.test.js --timeout=20000" diff --git a/functions/firebase/index.js b/functions/firebase/index.js index 12919d2bd5..eafeb3e6cb 100644 --- a/functions/firebase/index.js +++ b/functions/firebase/index.js @@ -18,20 +18,20 @@ * * @param {!Object} event The Cloud Functions event. */ -exports.helloRTDB = (event) => { +exports.helloRTDB = event => { const triggerResource = event.resource; const pathParams = event.params; if (pathParams) { - console.log(`Path parameters:`); - Object.keys(pathParams).forEach((key) => { + console.log('Path parameters:'); + Object.keys(pathParams).forEach(key => { console.log(` ${key}: ${pathParams[key]}`); }); } console.log(`Function triggered by change to: ${triggerResource}`); console.log(`Admin?: ${!!event.auth.admin}`); - console.log(`Delta:`); + console.log('Delta:'); console.log(JSON.stringify(event.delta, null, 2)); }; // [END functions_firebase_rtdb] @@ -42,19 +42,19 @@ exports.helloRTDB = (event) => { * * @param {!Object} event The Cloud Functions event. */ -exports.helloFirestore = (event) => { +exports.helloFirestore = event => { const triggerResource = event.resource; console.log(`Function triggered by event on: ${triggerResource}`); console.log(`Event type: ${event.eventType}`); if (event.oldValue && Object.keys(event.oldValue).length) { - console.log(`\nOld value:`); + console.log('\nOld value:'); console.log(JSON.stringify(event.oldValue, null, 2)); } if (event.value && Object.keys(event.value).length) { - console.log(`\nNew value:`); + console.log('\nNew value:'); console.log(JSON.stringify(event.value, null, 2)); } }; @@ -66,7 +66,7 @@ exports.helloFirestore = (event) => { * * @param {!Object} event The Cloud Functions event. */ -exports.helloAuth = (event) => { +exports.helloAuth = event => { try { console.log(`Function triggered by change to user: ${event.uid}`); console.log(`Created at: ${event.metadata.createdAt}`); @@ -88,7 +88,7 @@ const firestore = new Firestore({ }); // Converts strings added to /messages/{pushId}/original to uppercase -exports.makeUpperCase = (event) => { +exports.makeUpperCase = event => { const resource = event.value.name; const affectedDoc = firestore.doc(resource.split('/documents/')[1]); @@ -104,7 +104,7 @@ exports.makeUpperCase = (event) => { } else { // Value is already upper-case // Don't perform a(nother) write to avoid infinite loops - console.log('Value is already upper-case.') + console.log('Value is already upper-case.'); } }; // [END functions_firebase_reactive] @@ -115,7 +115,7 @@ exports.makeUpperCase = (event) => { * * @param {!Object} event The Cloud Functions event. */ -exports.helloAnalytics = (event) => { +exports.helloAnalytics = event => { const {resource} = event; console.log(`Function triggered by the following event: ${resource}`); @@ -135,7 +135,7 @@ exports.helloAnalytics = (event) => { * * @param {object} event The Cloud Functions event. */ -exports.helloRemoteConfig = (event) => { +exports.helloRemoteConfig = event => { console.log(`Update type: ${event.updateType}`); console.log(`Origin: ${event.updateOrigin}`); console.log(`Version: ${event.versionNumber}`); diff --git a/functions/firebase/package.json b/functions/firebase/package.json index 8f7866a2d8..183e86d80e 100644 --- a/functions/firebase/package.json +++ b/functions/firebase/package.json @@ -18,7 +18,7 @@ "mocha": "^8.0.0", "proxyquire": "^2.1.0", "sinon": "^9.0.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "uuid": "^8.0.0" }, "dependencies": { diff --git a/functions/firebase/test/index.test.js b/functions/firebase/test/index.test.js index 83f541add3..c72748e33e 100644 --- a/functions/firebase/test/index.test.js +++ b/functions/firebase/test/index.test.js @@ -35,8 +35,8 @@ const getSample = () => { }; const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; const restoreConsole = function () { @@ -205,9 +205,9 @@ describe('functions_firebase_reactive', () => { name: 'foo/documents/bar', fields: { original: { - stringValue: 'abc' - } - } + stringValue: 'abc', + }, + }, }; const event = { @@ -217,7 +217,10 @@ describe('functions_firebase_reactive', () => { sample.program.makeUpperCase(event); - assert.strictEqual(console.log.calledWith('Replacing value: abc --> ABC'), true); + assert.strictEqual( + console.log.calledWith('Replacing value: abc --> ABC'), + true + ); assert.strictEqual(sample.mocks.firestore.doc.calledWith('bar'), true); assert.strictEqual(sample.mocks.firestore.set.callCount, 1); }); @@ -229,9 +232,9 @@ describe('functions_firebase_reactive', () => { name: 'foo/documents/bar', fields: { original: { - stringValue: 'ABC' - } - } + stringValue: 'ABC', + }, + }, }; const event = { @@ -241,7 +244,10 @@ describe('functions_firebase_reactive', () => { sample.program.makeUpperCase(event); - assert.strictEqual(console.log.calledWith('Value is already upper-case.'), true); + assert.strictEqual( + console.log.calledWith('Value is already upper-case.'), + true + ); assert.strictEqual(sample.mocks.firestore.set.callCount, 0); }); }); diff --git a/functions/helloworld/package.json b/functions/helloworld/package.json index b6f9cf0395..fda24105ff 100644 --- a/functions/helloworld/package.json +++ b/functions/helloworld/package.json @@ -33,7 +33,7 @@ "request": "^2.88.0", "requestretry": "^4.0.0", "sinon": "^9.0.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "uuid": "^8.0.0" } } diff --git a/functions/helloworld/test/index.test.js b/functions/helloworld/test/index.test.js index d6b37d1642..b25d954d99 100644 --- a/functions/helloworld/test/index.test.js +++ b/functions/helloworld/test/index.test.js @@ -57,11 +57,11 @@ describe('index.test.js', () => { before(() => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); }); diff --git a/functions/helloworld/test/sample.integration.http.test.js b/functions/helloworld/test/sample.integration.http.test.js index e72e9dcbbe..24f9e8188d 100644 --- a/functions/helloworld/test/sample.integration.http.test.js +++ b/functions/helloworld/test/sample.integration.http.test.js @@ -70,6 +70,6 @@ describe('functions_helloworld_http HTTP integration test', () => { }); assert.strictEqual(response.statusCode, 200); - assert.strictEqual(response.body, `Hello World!`); + assert.strictEqual(response.body, 'Hello World!'); }); }); diff --git a/functions/helloworld/test/sample.integration.storage.test.js b/functions/helloworld/test/sample.integration.storage.test.js index a302b46403..50beca5cba 100644 --- a/functions/helloworld/test/sample.integration.storage.test.js +++ b/functions/helloworld/test/sample.integration.storage.test.js @@ -38,8 +38,8 @@ describe('functions_helloworld_storage integration test', () => { metageneration: '1', }, context: { - eventType: eventType - } + eventType: eventType, + }, }; // Run the functions-framework instance to host functions locally diff --git a/functions/helloworld/test/sample.system.http.test.js b/functions/helloworld/test/sample.system.http.test.js index 81be6c9baf..de4a97d6f5 100644 --- a/functions/helloworld/test/sample.system.http.test.js +++ b/functions/helloworld/test/sample.system.http.test.js @@ -23,7 +23,7 @@ describe('system tests', () => { .post('/helloHttp') .send({name: 'John'}) .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual(response.text, 'Hello John!'); }); }); @@ -33,7 +33,7 @@ describe('system tests', () => { await supertest .get('/helloHttp') .expect(200) - .expect((response) => { + .expect(response => { assert.strictEqual(response.text, 'Hello World!'); }); }); diff --git a/functions/helloworld/test/sample.system.pubsub.test.js b/functions/helloworld/test/sample.system.pubsub.test.js index 418eff06ee..cb86363e60 100644 --- a/functions/helloworld/test/sample.system.pubsub.test.js +++ b/functions/helloworld/test/sample.system.pubsub.test.js @@ -36,7 +36,7 @@ describe('system tests', () => { await topic.publish(Buffer.from(name)); // Wait for logs to become consistent - await promiseRetry((retry) => { + await promiseRetry(retry => { const logs = childProcess .execSync(`${baseCmd} logs read helloPubSub --start-time ${startTime}`) .toString(); @@ -59,13 +59,13 @@ describe('system tests', () => { await topic.publish(Buffer.from(''), {a: 'b'}); // Wait for logs to become consistent - await promiseRetry((retry) => { + await promiseRetry(retry => { const logs = childProcess .execSync(`${baseCmd} logs read helloPubSub --start-time ${startTime}`) .toString(); try { - assert.ok(logs.includes(`Hello, World!`)); + assert.ok(logs.includes('Hello, World!')); } catch (err) { retry(err); } diff --git a/functions/helloworld/test/sample.system.storage.test.js b/functions/helloworld/test/sample.system.storage.test.js index 666938f992..c401934314 100644 --- a/functions/helloworld/test/sample.system.storage.test.js +++ b/functions/helloworld/test/sample.system.storage.test.js @@ -42,14 +42,14 @@ describe('system tests', () => { }); // Wait for logs to become consistent - await promiseRetry((retry) => { + await promiseRetry(retry => { const logs = childProcess .execSync(`${baseCmd} logs read helloGCS --start-time ${startTime}`) .toString(); try { assert.ok(logs.includes(`Filename: ${gcsFileName}`)); - assert.ok(logs.includes(`Event Type: google.storage.object.finalize`)); + assert.ok(logs.includes('Event Type: google.storage.object.finalize')); } catch (err) { retry(err); } diff --git a/functions/helloworld/test/sample.unit.pubsub.test.js b/functions/helloworld/test/sample.unit.pubsub.test.js index 647579b884..d8263a3075 100644 --- a/functions/helloworld/test/sample.unit.pubsub.test.js +++ b/functions/helloworld/test/sample.unit.pubsub.test.js @@ -21,8 +21,8 @@ describe('functions_helloworld_pubsub', () => { const {helloPubSub} = require('..'); const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; const restoreConsole = function () { diff --git a/functions/helloworld/test/sample.unit.storage.test.js b/functions/helloworld/test/sample.unit.storage.test.js index d06f830516..09432fd7ee 100644 --- a/functions/helloworld/test/sample.unit.storage.test.js +++ b/functions/helloworld/test/sample.unit.storage.test.js @@ -21,8 +21,8 @@ describe('functions_helloworld_storage', () => { const {helloGCS} = require('..'); const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; const restoreConsole = function () { @@ -44,8 +44,8 @@ describe('functions_helloworld_storage', () => { }; const context = { eventId: 'g1bb3r1sh', - eventType: eventType - } + eventType: eventType, + }; // Call tested function and verify its behavior helloGCS(event, context); diff --git a/functions/http/test/index.test.js b/functions/http/test/index.test.js index b719b72820..9e7e49a1da 100644 --- a/functions/http/test/index.test.js +++ b/functions/http/test/index.test.js @@ -22,7 +22,7 @@ const uuid = require('uuid'); const getSample = () => { const requestPromise = sinon .stub() - .returns(new Promise((resolve) => resolve('test'))); + .returns(new Promise(resolve => resolve('test'))); return { sample: proxyquire('../', { @@ -66,7 +66,7 @@ const getMocks = () => { }; const stubConsole = function () { - sinon.stub(console, `error`); + sinon.stub(console, 'error'); }; const restoreConsole = function () { diff --git a/functions/imagemagick/index.js b/functions/imagemagick/index.js index 730ed3efe2..47c315d7c7 100644 --- a/functions/imagemagick/index.js +++ b/functions/imagemagick/index.js @@ -30,7 +30,7 @@ const {BLURRED_BUCKET_NAME} = process.env; // [START functions_imagemagick_analyze] // Blurs uploaded images that are flagged as Adult or Violence. -exports.blurOffensiveImages = async (event) => { +exports.blurOffensiveImages = async event => { // This event represents the triggering Cloud Storage object. const object = event; diff --git a/functions/imagemagick/test/index.test.js b/functions/imagemagick/test/index.test.js index 3c6f4ebe9e..061b0ea0ed 100644 --- a/functions/imagemagick/test/index.test.js +++ b/functions/imagemagick/test/index.test.js @@ -61,14 +61,14 @@ describe('functions/imagemagick tests', () => { }); before(() => { - startFF = (port) => { + startFF = port => { return execPromise( `functions-framework --target=blurOffensiveImages --signature-type=event --port=${port}`, {timeout: 15000, shell: true, cwd} ); }; - stopFF = async (ffProc) => { + stopFF = async ffProc => { try { return await ffProc; } catch (err) { @@ -84,7 +84,7 @@ describe('functions/imagemagick tests', () => { }); const stubConsole = function () { - sinon.stub(console, `error`); + sinon.stub(console, 'error'); }; const restoreConsole = function () { diff --git a/functions/log/index.js b/functions/log/index.js index aa4b126983..90a196759c 100644 --- a/functions/log/index.js +++ b/functions/log/index.js @@ -23,7 +23,7 @@ exports.helloWorld = (req, res) => { // [END functions_log_helloworld] // [START functions_log_stackdriver] -exports.processLogEntry = (data) => { +exports.processLogEntry = data => { const dataBuffer = Buffer.from(data.data, 'base64'); const logEntry = JSON.parse(dataBuffer.toString('ascii')).protoPayload; @@ -32,5 +32,3 @@ exports.processLogEntry = (data) => { console.log(`Initiator: ${logEntry.authenticationInfo.principalEmail}`); }; // [END functions_log_stackdriver] - -exports.getLogEntries = getLogEntries; diff --git a/functions/log/test/index.test.js b/functions/log/test/index.test.js index bc20484214..8abbe82801 100644 --- a/functions/log/test/index.test.js +++ b/functions/log/test/index.test.js @@ -41,8 +41,8 @@ const getSample = () => { }; const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; const restoreConsole = function () { diff --git a/functions/memorystore/redis/index.js b/functions/memorystore/redis/index.js index 654224d8dc..3c8d8cc6e4 100644 --- a/functions/memorystore/redis/index.js +++ b/functions/memorystore/redis/index.js @@ -23,7 +23,7 @@ const REDISHOST = process.env.REDISHOST || 'localhost'; const REDISPORT = process.env.REDISPORT || 6379; const redisClient = redis.createClient(REDISPORT, REDISHOST); -redisClient.on('error', (err) => console.error('ERR:REDIS:', err)); +redisClient.on('error', err => console.error('ERR:REDIS:', err)); const incrAsync = promisify(redisClient.incr).bind(redisClient); diff --git a/functions/ocr/app/index.js b/functions/ocr/app/index.js index 920539c11e..b606029347 100644 --- a/functions/ocr/app/index.js +++ b/functions/ocr/app/index.js @@ -60,7 +60,7 @@ const detectText = async (bucketName, filename) => { ); const [annotation] = textDetections.textAnnotations; const text = annotation ? annotation.description : ''; - console.log(`Extracted text from image:`, text); + console.log('Extracted text from image:', text); let [translateDetection] = await translate.detect(text); if (Array.isArray(translateDetection)) { @@ -74,7 +74,7 @@ const detectText = async (bucketName, filename) => { const TO_LANGS = process.env.TO_LANG.split(','); const topicName = process.env.TRANSLATE_TOPIC; - const tasks = TO_LANGS.map((lang) => { + const tasks = TO_LANGS.map(lang => { const messageData = { text: text, filename: filename, @@ -110,7 +110,7 @@ const renameImageForSave = (filename, lang) => { * * @param {object} event A Google Cloud Storage File object. */ -exports.processImage = async (event) => { +exports.processImage = async event => { const {bucket, name} = event; if (!bucket) { @@ -140,7 +140,7 @@ exports.processImage = async (event) => { * @param {string} {messageObject}.data The "data" property of the Cloud Pub/Sub * Message. This property will be a base64-encoded string that you must decode. */ -exports.translateText = async (event) => { +exports.translateText = async event => { const pubsubData = event.data; const jsonStr = Buffer.from(pubsubData, 'base64').toString(); const {text, filename, lang} = JSON.parse(jsonStr); @@ -164,7 +164,7 @@ exports.translateText = async (event) => { console.log(`Translating text into ${lang}`); const [translation] = await translate.translate(text, lang); - console.log(`Translated text:`, translation); + console.log('Translated text:', translation); const messageData = { text: translation, @@ -188,7 +188,7 @@ exports.translateText = async (event) => { * @param {string} {messageObject}.data The "data" property of the Cloud Pub/Sub * Message. This property will be a base64-encoded string that you must decode. */ -exports.saveResult = async (event) => { +exports.saveResult = async event => { const pubsubData = event.data; const jsonStr = Buffer.from(pubsubData, 'base64').toString(); const {text, filename, lang} = JSON.parse(jsonStr); @@ -218,6 +218,6 @@ exports.saveResult = async (event) => { console.log(`Saving result to ${newFilename} in bucket ${bucketName}`); await file.save(text); - console.log(`File saved.`); + console.log('File saved.'); }; // [END functions_ocr_save] diff --git a/functions/ocr/app/test/index.test.js b/functions/ocr/app/test/index.test.js index c0d17b6c52..ef3b0a4cf2 100644 --- a/functions/ocr/app/test/index.test.js +++ b/functions/ocr/app/test/index.test.js @@ -35,8 +35,8 @@ const errorMsg = (name, propertyName) => { }; const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; const restoreConsole = function () { @@ -71,7 +71,7 @@ describe('processImage', () => { console.log.calledWith(`Detected language "en" for ${filename}`) ); assert.ok( - console.log.calledWith(`Extracted text from image:`, `${text}\n`) + console.log.calledWith('Extracted text from image:', `${text}\n`) ); assert.ok( console.log.calledWith(`Detected language "en" for ${filename}`) diff --git a/functions/pubsub/index.js b/functions/pubsub/index.js index 90c24bc8e7..d98485f4b2 100644 --- a/functions/pubsub/index.js +++ b/functions/pubsub/index.js @@ -75,7 +75,7 @@ exports.publish = async (req, res) => { * @param {object} pubsubMessage The Cloud Pub/Sub Message object. * @param {string} pubsubMessage.data The "data" property of the Cloud Pub/Sub Message. */ -exports.subscribe = (pubsubMessage) => { +exports.subscribe = pubsubMessage => { // Print out the data from Pub/Sub, to prove that it worked console.log(Buffer.from(pubsubMessage.data, 'base64').toString()); }; diff --git a/functions/pubsub/test/index.test.js b/functions/pubsub/test/index.test.js index 029e016a08..dec924e1b1 100644 --- a/functions/pubsub/test/index.test.js +++ b/functions/pubsub/test/index.test.js @@ -30,8 +30,8 @@ const MESSAGE = 'Hello, world!'; describe('functions/pubsub', () => { const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; //Restore console diff --git a/functions/scheduleinstance/index.js b/functions/scheduleinstance/index.js index 6e0a50bab6..12aa866b6d 100644 --- a/functions/scheduleinstance/index.js +++ b/functions/scheduleinstance/index.js @@ -38,7 +38,7 @@ exports.startInstancePubSub = async (event, context, callback) => { const options = {filter: `labels.${payload.label}`}; const [vms] = await compute.getVMs(options); await Promise.all( - vms.map(async (instance) => { + vms.map(async instance => { if (payload.zone === instance.zone.id) { const [operation] = await compute .zone(payload.zone) @@ -52,7 +52,7 @@ exports.startInstancePubSub = async (event, context, callback) => { ); // Operation complete. Instance successfully started. - const message = `Successfully started instance(s)`; + const message = 'Successfully started instance(s)'; console.log(message); callback(null, message); } catch (err) { @@ -82,7 +82,7 @@ exports.stopInstancePubSub = async (event, context, callback) => { const options = {filter: `labels.${payload.label}`}; const [vms] = await compute.getVMs(options); await Promise.all( - vms.map(async (instance) => { + vms.map(async instance => { if (payload.zone === instance.zone.id) { const [operation] = await compute .zone(payload.zone) @@ -98,7 +98,7 @@ exports.stopInstancePubSub = async (event, context, callback) => { ); // Operation complete. Instance successfully stopped. - const message = `Successfully stopped instance(s)`; + const message = 'Successfully stopped instance(s)'; console.log(message); callback(null, message); } catch (err) { @@ -114,11 +114,11 @@ exports.stopInstancePubSub = async (event, context, callback) => { * @param {!object} payload the request payload to validate. * @return {!object} the payload object. */ -const _validatePayload = (payload) => { +const _validatePayload = payload => { if (!payload.zone) { - throw new Error(`Attribute 'zone' missing from payload`); + throw new Error("Attribute 'zone' missing from payload"); } else if (!payload.label) { - throw new Error(`Attribute 'label' missing from payload`); + throw new Error("Attribute 'label' missing from payload"); } return payload; }; diff --git a/functions/scheduleinstance/test/index.test.js b/functions/scheduleinstance/test/index.test.js index 0e1e03a001..50f580536b 100644 --- a/functions/scheduleinstance/test/index.test.js +++ b/functions/scheduleinstance/test/index.test.js @@ -21,7 +21,7 @@ const assert = require('assert'); const getSample = () => { const requestPromise = sinon .stub() - .returns(new Promise((resolve) => resolve('request sent'))); + .returns(new Promise(resolve => resolve('request sent'))); return { program: proxyquire('../', { @@ -47,8 +47,8 @@ const getMocks = () => { }; }; const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; //Restore console @@ -79,7 +79,7 @@ describe('functions_start_instance_pubsub', () => { assert.strictEqual(data, 'request sent'); }); - it(`startInstancePubSub: should fail with missing 'zone' attribute`, () => { + it("startInstancePubSub: should fail with missing 'zone' attribute", () => { const mocks = getMocks(); const sample = getSample(); const pubsubData = {label: 'testkey=value'}; @@ -94,11 +94,11 @@ describe('functions_start_instance_pubsub', () => { assert.deepStrictEqual( mocks.callback.firstCall.args[0], - new Error(`Attribute 'zone' missing from payload`) + new Error("Attribute 'zone' missing from payload") ); }); - it(`startInstancePubSub: should fail with missing 'label' attribute`, () => { + it("startInstancePubSub: should fail with missing 'label' attribute", () => { const mocks = getMocks(); const sample = getSample(); const pubsubData = {zone: 'test-zone'}; @@ -113,7 +113,7 @@ describe('functions_start_instance_pubsub', () => { assert.deepStrictEqual( mocks.callback.firstCall.args[0], - new Error(`Attribute 'label' missing from payload`) + new Error("Attribute 'label' missing from payload") ); }); @@ -132,7 +132,7 @@ describe('functions_start_instance_pubsub', () => { assert.deepStrictEqual( mocks.callback.firstCall.args[0], - new Error(`Attribute 'zone' missing from payload`) + new Error("Attribute 'zone' missing from payload") ); }); }); @@ -157,7 +157,7 @@ describe('functions_stop_instance_pubsub', () => { assert.strictEqual(data, 'request sent'); }); - it(`stopInstancePubSub: should fail with missing 'zone' attribute`, () => { + it("stopInstancePubSub: should fail with missing 'zone' attribute", () => { const mocks = getMocks(); const sample = getSample(); const pubsubData = {label: 'testkey=value'}; @@ -172,11 +172,11 @@ describe('functions_stop_instance_pubsub', () => { assert.deepStrictEqual( mocks.callback.firstCall.args[0], - new Error(`Attribute 'zone' missing from payload`) + new Error("Attribute 'zone' missing from payload") ); }); - it(`stopInstancePubSub: should fail with missing 'label' attribute`, () => { + it("stopInstancePubSub: should fail with missing 'label' attribute", () => { const mocks = getMocks(); const sample = getSample(); const pubsubData = {zone: 'test-zone'}; @@ -191,7 +191,7 @@ describe('functions_stop_instance_pubsub', () => { assert.deepStrictEqual( mocks.callback.firstCall.args[0], - new Error(`Attribute 'label' missing from payload`) + new Error("Attribute 'label' missing from payload") ); }); @@ -210,7 +210,7 @@ describe('functions_stop_instance_pubsub', () => { assert.deepStrictEqual( mocks.callback.firstCall.args[0], - new Error(`Attribute 'zone' missing from payload`) + new Error("Attribute 'zone' missing from payload") ); }); }); diff --git a/functions/sendgrid/index.js b/functions/sendgrid/index.js index d3c2bb20e6..ed0b886f8e 100644 --- a/functions/sendgrid/index.js +++ b/functions/sendgrid/index.js @@ -34,7 +34,7 @@ const bigquery = new BigQuery(); * @param {string} key Your SendGrid API key. * @returns {object} SendGrid client. */ -const 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' @@ -59,7 +59,7 @@ const getClient = (key) => { * @param {string} data.body Body of the email subject line. * @returns {object} Payload object. */ -const 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' @@ -191,7 +191,7 @@ exports.sendgridEmail = async (req, res) => { * * @param {string} authorization The authorization header of the request, e.g. "Basic ZmdvOhJhcg==" */ -const verifyWebhook = (authorization) => { +const verifyWebhook = authorization => { const basicAuth = Buffer.from( authorization.replace('Basic ', ''), 'base64' @@ -211,11 +211,11 @@ const verifyWebhook = (authorization) => { * * @param {*} obj Value to examine. */ -const fixNames = (obj) => { +const fixNames = obj => { if (Array.isArray(obj)) { obj.forEach(fixNames); } else if (obj && typeof obj === 'object') { - Object.keys(obj).forEach((key) => { + Object.keys(obj).forEach(key => { const value = obj[key]; fixNames(value); const fixedKey = key.replace('-', '_'); @@ -254,7 +254,7 @@ exports.sendgridWebhook = async (req, res) => { // Generate newline-delimited JSON // See https://cloud.google.com/bigquery/data-formats#json_format - const json = events.map((event) => JSON.stringify(event)).join('\n'); + 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) { @@ -301,7 +301,7 @@ const getTable = async () => { * @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 = async (event) => { +exports.sendgridLoad = async event => { const file = event.data; if (file.resourceState === 'not_exists') { diff --git a/functions/sendgrid/test/index.test.js b/functions/sendgrid/test/index.test.js index d8609b6f3c..5513c9ad43 100644 --- a/functions/sendgrid/test/index.test.js +++ b/functions/sendgrid/test/index.test.js @@ -145,11 +145,11 @@ const getMocks = () => { }; const stubConsole = function () { if ( - typeof console.log.restore !== `function` && - typeof console.error.restore !== `function` + typeof console.log.restore !== 'function' && + typeof console.error.restore !== 'function' ) { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); } }; diff --git a/functions/slack/index.js b/functions/slack/index.js index b2aa4b7ab3..0784255c3b 100644 --- a/functions/slack/index.js +++ b/functions/slack/index.js @@ -91,7 +91,7 @@ const formatSlackMessage = (query, response) => { * @param {string} req.headers Headers Slack SDK uses to authenticate request. * @param {string} req.rawBody Raw body of webhook request to check signature against. */ -const verifyWebhook = (req) => { +const verifyWebhook = req => { const signature = { signingSecret: process.env.SLACK_SECRET, requestSignature: req.headers['x-slack-signature'], @@ -113,7 +113,7 @@ const verifyWebhook = (req) => { * * @param {string} query The user's search query. */ -const makeSearchRequest = (query) => { +const makeSearchRequest = query => { return new Promise((resolve, reject) => { kgsearch.entities.search( { diff --git a/functions/slack/package.json b/functions/slack/package.json index fcd5e89f84..b4d138706e 100644 --- a/functions/slack/package.json +++ b/functions/slack/package.json @@ -16,7 +16,7 @@ }, "dependencies": { "@slack/events-api": "^2.3.0", - "googleapis": "^61.0.0" + "googleapis": "^62.0.0" }, "devDependencies": { "mocha": "^8.0.0", diff --git a/functions/slack/test/index.test.js b/functions/slack/test/index.test.js index 2340092b0f..9ebf20f6ff 100644 --- a/functions/slack/test/index.test.js +++ b/functions/slack/test/index.test.js @@ -43,7 +43,7 @@ const getSample = () => { return { program: proxyquire('../', { googleapis: {google: googleapis}, - process: { env: config }, + process: {env: config}, '@slack/events-api': eventsApi, }), mocks: { @@ -88,8 +88,8 @@ const getMocks = () => { }; const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; //Restore console diff --git a/functions/spanner/index.js b/functions/spanner/index.js index 48a49960da..5dc4bcc88b 100644 --- a/functions/spanner/index.js +++ b/functions/spanner/index.js @@ -46,8 +46,8 @@ exports.get = async (req, res) => { // Execute the query try { const results = await database.run(query); - const rows = results[0].map((row) => row.toJSON()); - rows.forEach((row) => { + const rows = results[0].map(row => row.toJSON()); + rows.forEach(row => { res.write( `SingerId: ${row.SingerId}, ` + `AlbumId: ${row.AlbumId}, ` + diff --git a/functions/spanner/test/index.test.js b/functions/spanner/test/index.test.js index 2bd57842c2..cb790ed343 100644 --- a/functions/spanner/test/index.test.js +++ b/functions/spanner/test/index.test.js @@ -36,7 +36,7 @@ const query = { }; const getSample = () => { - const resultsMock = entities.map((row) => { + const resultsMock = entities.map(row => { return {toJSON: sinon.stub().returns(row)}; }); const databaseMock = { diff --git a/functions/speech-to-speech/functions/index.js b/functions/speech-to-speech/functions/index.js index bbc8ee2860..fe56b3eb15 100644 --- a/functions/speech-to-speech/functions/index.js +++ b/functions/speech-to-speech/functions/index.js @@ -70,13 +70,13 @@ exports.speechTranslate = functions.https.onRequest( // The data object contains one or more recognition // alternatives ordered by accuracy. const transcription = sttResponse.results - .map((result) => result.alternatives[0].transcript) + .map(result => result.alternatives[0].transcript) .join('\n'); responseBody.transcription = transcription; responseBody.gcsBucket = outputBucket; const translations = []; - supportedLanguageCodes.forEach(async (languageCode) => { + supportedLanguageCodes.forEach(async languageCode => { const translation = {languageCode: languageCode}; const outputFilename = request.body.outputFilename || @@ -181,7 +181,7 @@ const uploadToCloudStorage = (path, contents) => { // [END upload_to_cloud_storage] // [START validate_request] -const validateRequest = (request) => { +const validateRequest = request => { return new Promise((resolve, reject) => { if (!request.body.encoding) { reject(new Error('Invalid encoding.')); diff --git a/functions/speech-to-speech/functions/test/index.test.js b/functions/speech-to-speech/functions/test/index.test.js index efc5ddc70d..c11bdd616e 100644 --- a/functions/speech-to-speech/functions/test/index.test.js +++ b/functions/speech-to-speech/functions/test/index.test.js @@ -40,7 +40,7 @@ describe('speechTranslate tests', () => { let ffProc; before(() => { ffProc = execPromise( - `functions-framework --target=speechTranslate --signature-type=http`, + 'functions-framework --target=speechTranslate --signature-type=http', {timeout: 8000, shell: true, cwd} ); }); @@ -203,7 +203,7 @@ describe('speechTranslate tests', () => { assert.strictEqual(response.statusCode, 200); // Test transcription - response.body.translations.forEach((translation) => { + response.body.translations.forEach(translation => { assert.ifError(translation.error); }); assert.strictEqual( diff --git a/functions/tips/index.js b/functions/tips/index.js index eb43a54fde..8a50d0b686 100644 --- a/functions/tips/index.js +++ b/functions/tips/index.js @@ -119,7 +119,7 @@ exports.avoidInfiniteRetries = (event, callback) => { // Do what the function is supposed to do console.log(`Processing event ${event} with age ${eventAge} ms.`); - + // Retry failed function executions const failed = false; if (failed) { @@ -139,11 +139,11 @@ exports.avoidInfiniteRetries = (event, callback) => { * @param {object} event.data Data included with the event. * @param {object} event.data.retry User-supplied parameter that tells the function whether to retry. */ -exports.retryPromise = (event) => { +exports.retryPromise = event => { const tryAgain = !!event.data.retry; if (tryAgain) { - throw new Error(`Retrying...`); + throw new Error('Retrying...'); } else { return Promise.reject(new Error('Not retrying...')); } @@ -188,7 +188,7 @@ const pubsub = new PubSub(); exports.gcpApiCall = (req, res) => { const topic = pubsub.topic(req.body.topic); - topic.publish(Buffer.from('Test message'), (err) => { + topic.publish(Buffer.from('Test message'), err => { if (err) { res.status(500).send(`Error publishing the message: ${err}`); } else { diff --git a/functions/tips/test/index.test.js b/functions/tips/test/index.test.js index 4a8923091e..8ee308a887 100644 --- a/functions/tips/test/index.test.js +++ b/functions/tips/test/index.test.js @@ -14,13 +14,13 @@ 'use strict'; -const sinon = require(`sinon`); -const assert = require(`assert`); +const sinon = require('sinon'); +const assert = require('assert'); -const sample = require(`../`); +const sample = require('../'); const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; //Restore console @@ -51,7 +51,7 @@ describe('functions_tips_retry', () => { } }); - it('should demonstrate retry behavior for a callback', (done) => { + it('should demonstrate retry behavior for a callback', done => { const cb = sinon.stub(); const err = new Error('Error!'); @@ -90,7 +90,7 @@ describe('functions_tips_gcp_apis', () => { // Instead of modifying the sample to return a promise, // use a delay here and keep the sample idiomatic - await new Promise((resolve) => setTimeout(resolve, 1000)); + await new Promise(resolve => setTimeout(resolve, 1000)); assert.ok(resMock.status.calledOnce); assert.ok(resMock.status.calledWith(200)); diff --git a/functions/tokenservice/functions/index.js b/functions/tokenservice/functions/index.js index 2bf6a0c30f..56a3a1ae7d 100644 --- a/functions/tokenservice/functions/index.js +++ b/functions/tokenservice/functions/index.js @@ -41,7 +41,7 @@ const generateAccessToken = ( // 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 - return new Promise((resolve) => { + return new Promise(resolve => { const post_options = { host: 'iamcredentials.googleapis.com', path: @@ -55,9 +55,9 @@ const generateAccessToken = ( // Set up the request let oauthToken = ''; - const post_req = https.request(post_options, (res) => { + const post_req = https.request(post_options, res => { res.setEncoding('utf8'); - res.on('data', (chunk) => { + res.on('data', chunk => { oauthToken += chunk; }); res.on('end', () => { @@ -67,7 +67,7 @@ const generateAccessToken = ( }); }); - post_req.on('error', (e) => { + post_req.on('error', e => { console.log('ERROR generating new token', e.message); return 'Error retrieving token'; }); @@ -87,8 +87,8 @@ const generateAccessToken = ( // [END generate_token] // [START retrieve_credentials] -const retrieveCredentials = (context) => { - return new Promise((resolve) => { +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(). // To do that, we will use the App Engine Default Service Account. @@ -99,10 +99,10 @@ const retrieveCredentials = (context) => { headers: {'Metadata-Flavor': 'Google'}, }; - const get_req = http.get(options, (res) => { + const get_req = http.get(options, res => { let body = ''; - res.on('data', (chunk) => { + res.on('data', chunk => { body += chunk; }); @@ -116,7 +116,7 @@ const retrieveCredentials = (context) => { return resolve(result); }); }); - get_req.on('error', (e) => { + get_req.on('error', e => { //console.log('Error retrieving credentials', e.message); return `Error retrieving token${e.message}`; }); @@ -128,7 +128,7 @@ exports.retrieveCredentials = retrieveCredentials; // [START validate_token] // This method verifies the token expiry by validating against current time -const isValid = (expiryTime) => { +const isValid = expiryTime => { const currentDate = new Date(); const expirationDate = new Date(expiryTime); // If within 5 minutes of expiration, return false diff --git a/functions/tokenservice/functions/package.json b/functions/tokenservice/functions/package.json index a5cccf0e2f..64b99ae708 100644 --- a/functions/tokenservice/functions/package.json +++ b/functions/tokenservice/functions/package.json @@ -28,7 +28,7 @@ "eslint-plugin-promise": "^4.0.1", "mocha": "^8.0.0", "prettier": "^2.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" }, "engines": { "node": ">=10.0.0" diff --git a/functions/tokenservice/functions/test/index.test.js b/functions/tokenservice/functions/test/index.test.js index 7e65a1b476..bfcf2b35ab 100644 --- a/functions/tokenservice/functions/test/index.test.js +++ b/functions/tokenservice/functions/test/index.test.js @@ -42,7 +42,7 @@ const contextValue = (uid = 'test-uid', email_verified = true) => ({ }, }); -const handleLinuxFailures = async (proc) => { +const handleLinuxFailures = async proc => { try { return await proc; } catch (err) { diff --git a/healthcare/datasets/package.json b/healthcare/datasets/package.json index 5d4ddb7e3d..ded542beb9 100644 --- a/healthcare/datasets/package.json +++ b/healthcare/datasets/package.json @@ -15,7 +15,7 @@ "mocha": "^8.0.0" }, "dependencies": { - "googleapis": "^61.0.0", + "googleapis": "^62.0.0", "uuid": "^8.0.0", "yargs": "^16.0.0" } diff --git a/healthcare/datasets/system-test/datasets.test.js b/healthcare/datasets/system-test/datasets.test.js index 0f645409f1..72f406739f 100644 --- a/healthcare/datasets/system-test/datasets.test.js +++ b/healthcare/datasets/system-test/datasets.test.js @@ -28,11 +28,11 @@ const cloudRegion = 'us-central1'; before(() => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); }); after(() => { @@ -53,7 +53,7 @@ it('should create a dataset', () => { it('should get a dataset', () => { const output = execSync( - `node getDataset.js ${projectId} ${cloudRegion} ${datasetId}`, + `node getDataset.js ${projectId} ${cloudRegion} ${datasetId}` ); assert.ok(output.includes('name')); }); @@ -63,7 +63,7 @@ it('should create and get a dataset IAM policy', () => { const localRole = 'roles/viewer'; let output = execSync( - `node setDatasetIamPolicy.js ${projectId} ${cloudRegion} ${datasetId} ${localMember} ${localRole}`, + `node setDatasetIamPolicy.js ${projectId} ${cloudRegion} ${datasetId} ${localMember} ${localRole}` ); assert.ok(output.includes, 'ETAG'); @@ -76,31 +76,29 @@ it('should create and get a dataset IAM policy', () => { it('should patch a dataset', () => { const timeZone = 'GMT'; const output = execSync( - `node patchDataset.js ${projectId} ${cloudRegion} ${datasetId} ${timeZone}`, - ); - assert.ok( - output.includes('patched with time zone') + `node patchDataset.js ${projectId} ${cloudRegion} ${datasetId} ${timeZone}` ); + assert.ok(output.includes('patched with time zone')); }); it('should list datasets', () => { - const output = execSync(`node listDatasets.js ${projectId} ${cloudRegion}`, { - }); + const output = execSync( + `node listDatasets.js ${projectId} ${cloudRegion}`, + {} + ); assert.ok(output.includes('datasets')); }); it('should de-identify data in a dataset and write to a new dataset', () => { const output = execSync( - `node deidentifyDataset.js ${projectId} ${cloudRegion} ${datasetId} ${destinationDatasetId} ${keeplistTags}`, - ); - assert.ok( - output.includes('De-identified data written') + `node deidentifyDataset.js ${projectId} ${cloudRegion} ${datasetId} ${destinationDatasetId} ${keeplistTags}` ); + assert.ok(output.includes('De-identified data written')); }); it('should delete a dataset', () => { const output = execSync( - `node deleteDataset.js ${projectId} ${cloudRegion} ${datasetId}`, + `node deleteDataset.js ${projectId} ${cloudRegion} ${datasetId}` ); assert.ok(output.includes('Deleted dataset')); }); diff --git a/healthcare/dicom/dicomWebSearchForInstances.js b/healthcare/dicom/dicomWebSearchForInstances.js index 6c37e8aaeb..22d85705b4 100644 --- a/healthcare/dicom/dicomWebSearchForInstances.js +++ b/healthcare/dicom/dicomWebSearchForInstances.js @@ -41,7 +41,7 @@ const main = ( // const datasetId = 'my-dataset'; // const dicomStoreId = 'my-dicom-store'; const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`; - const dicomWebPath = `instances`; + const dicomWebPath = 'instances'; const request = {parent, dicomWebPath}; const instances = await healthcare.projects.locations.datasets.dicomStores.searchForInstances( diff --git a/healthcare/dicom/dicomWebSearchStudies.js b/healthcare/dicom/dicomWebSearchStudies.js index 81d769093c..3bd7bf60d2 100644 --- a/healthcare/dicom/dicomWebSearchStudies.js +++ b/healthcare/dicom/dicomWebSearchStudies.js @@ -46,7 +46,7 @@ const main = ( // const datasetId = 'my-dataset'; // const dicomStoreId = 'my-dicom-store'; const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`; - const dicomWebPath = `studies`; + const dicomWebPath = 'studies'; const request = {parent, dicomWebPath}; const studies = await healthcare.projects.locations.datasets.dicomStores.searchForStudies( diff --git a/healthcare/dicom/dicomWebStoreInstance.js b/healthcare/dicom/dicomWebStoreInstance.js index 3cfaa37863..3a33f16aad 100644 --- a/healthcare/dicom/dicomWebStoreInstance.js +++ b/healthcare/dicom/dicomWebStoreInstance.js @@ -47,7 +47,7 @@ const main = ( // const dicomStoreId = 'my-dicom-store'; // const dcmFile = 'file.dcm'; const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`; - const dicomWebPath = `studies`; + const dicomWebPath = 'studies'; const binaryData = fs.createReadStream(dcmFile); const request = { parent, @@ -58,7 +58,7 @@ const main = ( const instance = await healthcare.projects.locations.datasets.dicomStores.storeInstances( request ); - console.log(`Stored DICOM instance:\n`, JSON.stringify(instance.data)); + console.log('Stored DICOM instance:\n', JSON.stringify(instance.data)); }; dicomWebStoreInstance(); diff --git a/healthcare/dicom/package.json b/healthcare/dicom/package.json index 78f6afd88b..e09d967698 100644 --- a/healthcare/dicom/package.json +++ b/healthcare/dicom/package.json @@ -17,7 +17,7 @@ "mocha": "^8.0.0" }, "dependencies": { - "googleapis": "^61.0.0", + "googleapis": "^62.0.0", "uuid": "^8.0.0", "yargs": "^16.0.0", "gtoken": "^5.0.0", diff --git a/healthcare/dicom/system-test/dicom_stores.test.js b/healthcare/dicom/system-test/dicom_stores.test.js index 4a7bbd4f8a..6c854e65a9 100644 --- a/healthcare/dicom/system-test/dicom_stores.test.js +++ b/healthcare/dicom/system-test/dicom_stores.test.js @@ -46,18 +46,16 @@ const installDeps = 'npm install'; // Run npm install on datasets directory because modalities // require bootstrapping datasets, and Kokoro needs to know // to install dependencies from the datasets directory. -assert.ok( - execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true}) -); +assert.ok(execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true})); before(async () => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); // Create a Cloud Storage bucket to be used for testing. await storage.createBucket(bucketName); diff --git a/healthcare/dicom/system-test/dicomweb.test.js b/healthcare/dicom/system-test/dicomweb.test.js index 490ac73521..63bfbd580e 100644 --- a/healthcare/dicom/system-test/dicomweb.test.js +++ b/healthcare/dicom/system-test/dicomweb.test.js @@ -46,18 +46,16 @@ const installDeps = 'npm install'; // Run npm install on datasets directory because modalities // require bootstrapping datasets, and Kokoro needs to know // to install dependencies from the datasets directory. -assert.ok( - execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true}) -); +assert.ok(execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true})); before(() => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); execSync(`node createDataset.js ${projectId} ${cloudRegion} ${datasetId}`, { cwd: cwdDatasets, @@ -73,7 +71,9 @@ after(() => { `node deleteDicomStore.js ${projectId} ${cloudRegion} ${datasetId} ${dicomStoreId}`, {cwd} ); - execSync(`node deleteDataset.js ${projectId} ${cloudRegion} ${datasetId}`, {cwd: cwdDatasets}); + execSync(`node deleteDataset.js ${projectId} ${cloudRegion} ${datasetId}`, { + cwd: cwdDatasets, + }); } catch (err) {} // Ignore error }); diff --git a/healthcare/fhir/createFhirResource.js b/healthcare/fhir/createFhirResource.js index 9e6c7bc529..772f9135b4 100644 --- a/healthcare/fhir/createFhirResource.js +++ b/healthcare/fhir/createFhirResource.js @@ -20,7 +20,7 @@ function main( cloudRegion = 'us-central1', datasetId, fhirStoreId, - resourceType, + resourceType ) { // [START healthcare_create_resource] const {google} = require('googleapis'); @@ -34,10 +34,10 @@ function main( // Replace the following body with the data for the resource you want to // create. const body = { - "name": [{"use": "official", "family": "Smith", "given": ["Darcy"]}], - "gender": "female", - "birthDate": "1970-01-01", - "resourceType": "Patient", + name: [{use: 'official', family: 'Smith', given: ['Darcy']}], + gender: 'female', + birthDate: '1970-01-01', + resourceType: 'Patient', }; google.options({auth, headers: {'Content-Type': 'application/fhir+json'}}); diff --git a/healthcare/fhir/createFhirStore.js b/healthcare/fhir/createFhirStore.js index 42d350cae0..29b7c5958d 100644 --- a/healthcare/fhir/createFhirStore.js +++ b/healthcare/fhir/createFhirStore.js @@ -44,7 +44,7 @@ const main = ( parent, fhirStoreId, resource: { - version + version, }, }; diff --git a/healthcare/fhir/deleteFhirResource.js b/healthcare/fhir/deleteFhirResource.js index 059ea41dd0..c4e1581bb5 100644 --- a/healthcare/fhir/deleteFhirResource.js +++ b/healthcare/fhir/deleteFhirResource.js @@ -51,7 +51,7 @@ const main = ( await healthcare.projects.locations.datasets.fhirStores.fhir.delete( request ); - console.log(`Deleted FHIR resource`); + console.log('Deleted FHIR resource'); }; deleteFhirResource(); diff --git a/healthcare/fhir/deleteFhirResourcePurge.js b/healthcare/fhir/deleteFhirResourcePurge.js index d85a9bfa71..699259f212 100644 --- a/healthcare/fhir/deleteFhirResourcePurge.js +++ b/healthcare/fhir/deleteFhirResourcePurge.js @@ -47,7 +47,7 @@ const main = ( await healthcare.projects.locations.datasets.fhirStores.fhir.ResourcePurge( request ); - console.log(`Deleted all historical versions of resource`); + console.log('Deleted all historical versions of resource'); }; deleteFhirResourcePurge(); diff --git a/healthcare/fhir/executeFhirBundle.js b/healthcare/fhir/executeFhirBundle.js index 95a0edc56d..699e5230a6 100644 --- a/healthcare/fhir/executeFhirBundle.js +++ b/healthcare/fhir/executeFhirBundle.js @@ -48,7 +48,7 @@ function main( const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.executeBundle( request ); - console.log(`FHIR bundle executed`); + console.log('FHIR bundle executed'); console.log(resource.data); } diff --git a/healthcare/fhir/package.json b/healthcare/fhir/package.json index 78f6afd88b..e09d967698 100644 --- a/healthcare/fhir/package.json +++ b/healthcare/fhir/package.json @@ -17,7 +17,7 @@ "mocha": "^8.0.0" }, "dependencies": { - "googleapis": "^61.0.0", + "googleapis": "^62.0.0", "uuid": "^8.0.0", "yargs": "^16.0.0", "gtoken": "^5.0.0", diff --git a/healthcare/fhir/patchFhirResource.js b/healthcare/fhir/patchFhirResource.js index f00dc280bc..1c29000a8a 100644 --- a/healthcare/fhir/patchFhirResource.js +++ b/healthcare/fhir/patchFhirResource.js @@ -33,7 +33,10 @@ function main( }); // TODO(developer): replace patchOptions with your desired JSON patch body const patchOptions = [{op: 'replace', path: '/active', value: false}]; - google.options({auth, headers: {'Content-Type': 'application/json-patch+json'}}); + google.options({ + auth, + headers: {'Content-Type': 'application/json-patch+json'}, + }); // TODO(developer): uncomment these lines before running the sample // const cloudRegion = 'us-central1'; @@ -45,11 +48,11 @@ function main( const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`; const request = { name, - requestBody: patchOptions + requestBody: patchOptions, }; const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.patch( - request, + request ); console.log(`Patched ${resourceType} resource`); } diff --git a/healthcare/fhir/system-test/fhir_resources.test.js b/healthcare/fhir/system-test/fhir_resources.test.js index b5e817b876..d396357c8b 100644 --- a/healthcare/fhir/system-test/fhir_resources.test.js +++ b/healthcare/fhir/system-test/fhir_resources.test.js @@ -40,30 +40,26 @@ const installDeps = 'npm install'; // Run npm install on datasets directory because modalities // require bootstrapping datasets, and Kokoro needs to know // to install dependencies from the datasets directory. -assert.ok( - execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true}) -); +assert.ok(execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true})); before(() => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` - ); - execSync( - `node createDataset.js ${projectId} ${cloudRegion} ${datasetId}`, - {cwd: cwdDatasets} + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); + execSync(`node createDataset.js ${projectId} ${cloudRegion} ${datasetId}`, { + cwd: cwdDatasets, + }); }); after(() => { try { - execSync( - `node deleteDataset.js ${projectId} ${cloudRegion} ${datasetId}`, - {cwd: cwdDatasets} - ); + execSync(`node deleteDataset.js ${projectId} ${cloudRegion} ${datasetId}`, { + cwd: cwdDatasets, + }); } catch (err) {} // Ignore error }); @@ -76,9 +72,7 @@ it('should create a FHIR resource', () => { `node createFhirResource ${projectId} ${cloudRegion} ${datasetId} ${fhirStoreId} ${resourceType}`, {cwd} ); - const createdResource = new RegExp( - `Created FHIR resource with ID (.*)` - ); + const createdResource = new RegExp('Created FHIR resource with ID (.*)'); assert.strictEqual(createdResource.test(output), true); [, resourceId] = createdResource.exec(output); }); @@ -174,7 +168,10 @@ it('should purge all historical versions of a FHIR resource', () => { `node deleteFhirResourcePurge.js ${projectId} ${cloudRegion} ${datasetId} ${fhirStoreId} ${resourceType} ${resourceId}`, {cwd} ); - assert.strictEqual(new RegExp('Deleted all historical versions of resource').test(output), true); + assert.strictEqual( + new RegExp('Deleted all historical versions of resource').test(output), + true + ); }); it('should execute a Bundle', () => { diff --git a/healthcare/fhir/system-test/fhir_stores.test.js b/healthcare/fhir/system-test/fhir_stores.test.js index 03d49a16c6..4a9b6ec1fc 100644 --- a/healthcare/fhir/system-test/fhir_stores.test.js +++ b/healthcare/fhir/system-test/fhir_stores.test.js @@ -48,18 +48,16 @@ const installDeps = 'npm install'; // Run npm install on datasets directory because modalities // require bootstrapping datasets, and Kokoro needs to know // to install dependencies from the datasets directory. -assert.ok( - execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true}) -); +assert.ok(execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true})); before(async () => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); // Create a Cloud Storage bucket to be used for testing. await storage.createBucket(bucketName); @@ -71,10 +69,9 @@ before(async () => { // Create a Pub/Sub topic to be used for testing. const [topic] = await pubSubClient.createTopic(topicName); console.log(`Topic ${topic.name} created.`); - execSync( - `node createDataset.js ${projectId} ${cloudRegion} ${datasetId}`, - {cwd: cwdDatasets} - ); + execSync(`node createDataset.js ${projectId} ${cloudRegion} ${datasetId}`, { + cwd: cwdDatasets, + }); }); after(async () => { @@ -87,10 +84,9 @@ after(async () => { await pubSubClient.topic(topicName).delete(); console.log(`Topic ${topicName} deleted.`); - execSync( - `node deleteDataset.js ${projectId} ${cloudRegion} ${datasetId}`, - {cwd: cwdDatasets} - ); + execSync(`node deleteDataset.js ${projectId} ${cloudRegion} ${datasetId}`, { + cwd: cwdDatasets, + }); } catch (err) {} // Ignore error }); diff --git a/healthcare/hl7v2/createHl7v2Message.js b/healthcare/hl7v2/createHl7v2Message.js index 2206178d55..6972c76d19 100644 --- a/healthcare/hl7v2/createHl7v2Message.js +++ b/healthcare/hl7v2/createHl7v2Message.js @@ -51,7 +51,7 @@ const main = ( request ); const {data} = response; - console.log(`Created HL7v2 message with data:\n`, data); + console.log('Created HL7v2 message with data:\n', data); }; createHl7v2Message(); diff --git a/healthcare/hl7v2/ingestHl7v2Message.js b/healthcare/hl7v2/ingestHl7v2Message.js index 23515631a4..1ec4b28077 100644 --- a/healthcare/hl7v2/ingestHl7v2Message.js +++ b/healthcare/hl7v2/ingestHl7v2Message.js @@ -53,7 +53,7 @@ const main = ( const data = response.data.hl7Ack; const buff = new Buffer.from(data, 'base64'); const hl7Ack = buff.toString('ascii'); - console.log(`Ingested HL7v2 message with ACK:\n`, hl7Ack); + console.log('Ingested HL7v2 message with ACK:\n', hl7Ack); }; ingestHl7v2Message(); diff --git a/healthcare/hl7v2/package.json b/healthcare/hl7v2/package.json index e915c9a8cb..ba6aac96c9 100644 --- a/healthcare/hl7v2/package.json +++ b/healthcare/hl7v2/package.json @@ -16,7 +16,7 @@ "mocha": "^8.0.0" }, "dependencies": { - "googleapis": "^61.0.0", + "googleapis": "^62.0.0", "uuid": "^8.0.0", "yargs": "^16.0.0" } diff --git a/healthcare/hl7v2/patchHl7v2Store.js b/healthcare/hl7v2/patchHl7v2Store.js index f68eb0e55f..80d14d2707 100644 --- a/healthcare/hl7v2/patchHl7v2Store.js +++ b/healthcare/hl7v2/patchHl7v2Store.js @@ -47,8 +47,8 @@ const main = ( notificationConfigs: [ { pubsubTopic: `projects/${projectId}/topics/${pubsubTopic}`, - } - ] + }, + ], }, }; diff --git a/healthcare/hl7v2/system-test/hl7v2_messages.test.js b/healthcare/hl7v2/system-test/hl7v2_messages.test.js index c0110fc8b7..408893596d 100644 --- a/healthcare/hl7v2/system-test/hl7v2_messages.test.js +++ b/healthcare/hl7v2/system-test/hl7v2_messages.test.js @@ -39,18 +39,16 @@ const installDeps = 'npm install'; // Run npm install on datasets directory because modalities // require bootstrapping datasets, and Kokoro needs to know // to install dependencies from the datasets directory. -assert.ok( - execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true}) -); +assert.ok(execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true})); before(() => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); execSync(`node createDataset.js ${projectId} ${cloudRegion} ${datasetId}`, { cwd: cwdDatasets, diff --git a/healthcare/hl7v2/system-test/hl7v2_stores.test.js b/healthcare/hl7v2/system-test/hl7v2_stores.test.js index 32a046cdf7..1eb9be6d4f 100644 --- a/healthcare/hl7v2/system-test/hl7v2_stores.test.js +++ b/healthcare/hl7v2/system-test/hl7v2_stores.test.js @@ -37,18 +37,16 @@ const installDeps = 'npm install'; // Run npm install on datasets directory because modalities // require bootstrapping datasets, and Kokoro needs to know // to install dependencies from the datasets directory. -assert.ok( - execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true}) -); +assert.ok(execSync(installDeps, {cwd: `${cwdDatasets}`, shell: true})); before(async () => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); // Create a Pub/Sub topic to be used for testing. const [topic] = await pubSubClient.createTopic(topicName); diff --git a/healthcare/sleep.js b/healthcare/sleep.js index d7bbb893c3..531a29619b 100644 --- a/healthcare/sleep.js +++ b/healthcare/sleep.js @@ -14,8 +14,8 @@ 'use strict'; -const sleep = (ms) => { - return new Promise((resolve) => setTimeout(resolve, ms)); +const sleep = ms => { + return new Promise(resolve => setTimeout(resolve, ms)); }; module.exports = sleep; diff --git a/iot/http_example/cloudiot_http_example.js b/iot/http_example/cloudiot_http_example.js index 8a5323f743..40d3b6f014 100644 --- a/iot/http_example/cloudiot_http_example.js +++ b/iot/http_example/cloudiot_http_example.js @@ -37,10 +37,11 @@ const createJwt = (projectId, privateKeyFile, algorithm) => { // [END iot_http_jwt] console.log('Google Cloud IoT Core HTTP example.'); -const {argv} = require(`yargs`) +const {argv} = require('yargs') .options({ projectId: { - default: process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, + default: + process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, description: 'The Project ID to use. Defaults to the value of the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.', requiresArg: true, @@ -104,11 +105,11 @@ const {argv} = require(`yargs`) }, }) .example( - `node $0 cloudiot_http_example.js --projectId=blue-jet-123 --registryId=my-registry --deviceId=my-node-device --privateKeyFile=../rsaPrivate.pem --algorithm=RS256` + 'node $0 cloudiot_http_example.js --projectId=blue-jet-123 --registryId=my-registry --deviceId=my-node-device --privateKeyFile=../rsaPrivate.pem --algorithm=RS256' ) .wrap(120) .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/iot-core/docs`) + .epilogue('For more information, see https://cloud.google.com/iot-core/docs') .help() .strict(); diff --git a/iot/http_example/package.json b/iot/http_example/package.json index 120b4061b9..9e6a49d9b4 100644 --- a/iot/http_example/package.json +++ b/iot/http_example/package.json @@ -23,7 +23,7 @@ }, "devDependencies": { "@google-cloud/pubsub": "^2.0.0", - "googleapis": "^61.0.0", + "googleapis": "^62.0.0", "mocha": "^8.0.0", "uuid": "^8.0.0" } diff --git a/iot/http_example/system-test/cloudiot_http_example.test.js b/iot/http_example/system-test/cloudiot_http_example.test.js index cf4b89285d..978c4ab171 100644 --- a/iot/http_example/system-test/cloudiot_http_example.test.js +++ b/iot/http_example/system-test/cloudiot_http_example.test.js @@ -34,11 +34,11 @@ assert.ok( before(async () => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); const pubsub = new PubSub(); const [topic] = await pubsub.createTopic(topicName); diff --git a/iot/manager/manager.js b/iot/manager/manager.js index 3895346911..fa4416cdea 100644 --- a/iot/manager/manager.js +++ b/iot/manager/manager.js @@ -33,12 +33,12 @@ if (client === undefined) { } // Configures the topic for Cloud IoT Core. -const setupIotTopic = async (topicName) => { +const setupIotTopic = async topicName => { const {PubSub} = require('@google-cloud/pubsub'); const pubsub = new PubSub(); const topic = pubsub.topic(topicName); - const serviceAccount = `serviceAccount:cloud-iot@system.gserviceaccount.com`; + const serviceAccount = 'serviceAccount:cloud-iot@system.gserviceaccount.com'; let policy = await topic.iam.getPolicy(); policy = policy[0] || {}; @@ -52,7 +52,7 @@ const setupIotTopic = async (topicName) => { members: [serviceAccount], }; - policy.bindings.forEach((_binding) => { + policy.bindings.forEach(_binding => { if (_binding.role === binding.role) { binding = _binding; hasRole = true; @@ -78,7 +78,7 @@ const setupIotTopic = async (topicName) => { } }; -const createIotTopic = async (topicName) => { +const createIotTopic = async topicName => { // Imports the Google Cloud client library const {PubSub} = require('@google-cloud/pubsub'); @@ -746,7 +746,7 @@ const getDeviceConfigs = async ( if (configs.length === 0) { console.log(`No configs for device: ${deviceId}`); } else { - console.log(`Configs:`); + console.log('Configs:'); } for (let i = 0; i < configs.length; i++) { @@ -845,7 +845,7 @@ const sendCommand = async ( try { const responses = await iotClient.sendCommandToDevice(request); - + console.log('Sent command: ', responses[0]); } catch (err) { console.error('Could not send command:', err); @@ -890,7 +890,7 @@ const getRegistry = async (client, registryId, projectId, cloudRegion) => { // Returns an authorized API client by discovering the Cloud IoT Core API with // the provided API key. -const getClient = async (serviceAccountJson) => { +const getClient = async serviceAccountJson => { // the getClient method looks for the GOOGLE_CLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS // environment variables if serviceAccountJson is not passed in const authClient = await google.auth.getClient({ @@ -942,10 +942,10 @@ const getIamPolicy = async (client, registryId, projectId, cloudRegion) => { console.log('ETAG:', etag); bindings = bindings || []; - bindings.forEach((_binding) => { + bindings.forEach(_binding => { console.log(`Role: ${_binding.role}`); _binding.members || (_binding.members = []); - _binding.members.forEach((_member) => { + _binding.members.forEach(_member => { console.log(`\t${_member}`); }); }); @@ -1004,10 +1004,10 @@ const setIamPolicy = async ( console.log('ETAG:', etag); bindings = bindings || []; - bindings.forEach((_binding) => { + bindings.forEach(_binding => { console.log(`Role: ${_binding.role}`); _binding.members || (_binding.members = []); - _binding.members.forEach((_member) => { + _binding.members.forEach(_member => { console.log(`\t${_member}`); }); }); @@ -1281,7 +1281,7 @@ const listGateways = async (client, projectId, cloudRegion, registryId) => { }); const devices = responses[0]; - devices.forEach((device) => { + devices.forEach(device => { if ( device.gatewayConfig !== undefined && device.gatewayConfig.gatewayType === 'GATEWAY' @@ -1394,7 +1394,8 @@ require(`yargs`) // eslint-disable-line }, projectId: { alias: 'p', - default: process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, + default: + process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, description: 'The Project ID to use. Defaults to the value of the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.', requiresArg: true, @@ -1409,10 +1410,10 @@ require(`yargs`) // eslint-disable-line }, }) .command( - `createRsa256Device `, - `Creates an RSA256 device.`, + 'createRsa256Device ', + 'Creates an RSA256 device.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await createRsaDevice( client, @@ -1425,10 +1426,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `createEs256Device `, - `Creates an ES256 device.`, + 'createEs256Device ', + 'Creates an ES256 device.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await createEsDevice( client, @@ -1441,10 +1442,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `createUnauthDevice `, - `Creates a device without authorization.`, + 'createUnauthDevice ', + 'Creates a device without authorization.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await createUnauthDevice( client, @@ -1456,8 +1457,8 @@ require(`yargs`) // eslint-disable-line } ) .command( - `createDevice `, - `Creates a device with the given public key. Public key can be ommitted and added later on.`, + 'createDevice ', + 'Creates a device with the given public key. Public key can be ommitted and added later on.', { publicKeyFormat: { default: 'RSA_X509_PEM', @@ -1473,7 +1474,7 @@ require(`yargs`) // eslint-disable-line type: 'string', }, }, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await createDevice( client, @@ -1487,10 +1488,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `createRegistry `, - `Creates a device registry.`, + 'createRegistry ', + 'Creates a device registry.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await createRegistry( client, @@ -1502,10 +1503,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `lookupRegistry `, - `Gets a device registry.`, + 'lookupRegistry ', + 'Gets a device registry.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await lookupRegistry( client, @@ -1516,22 +1517,22 @@ require(`yargs`) // eslint-disable-line } ) .command( - `createIotTopic `, - `Creates and configures a PubSub topic for Cloud IoT Core.`, + 'createIotTopic ', + 'Creates and configures a PubSub topic for Cloud IoT Core.', {}, - (opts) => createIotTopic(opts.pubsubTopic) + opts => createIotTopic(opts.pubsubTopic) ) .command( - `setupIotTopic `, - `Configures the PubSub topic for Cloud IoT Core.`, + 'setupIotTopic ', + 'Configures the PubSub topic for Cloud IoT Core.', {}, - (opts) => setupIotTopic(opts.pubsubTopic) + opts => setupIotTopic(opts.pubsubTopic) ) .command( - `deleteDevice `, - `Deletes a device from the device registry.`, + 'deleteDevice ', + 'Deletes a device from the device registry.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await deleteDevice( client, @@ -1543,10 +1544,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `clearRegistry `, - `!!Be careful! Removes all devices and then deletes a device registry!!`, + 'clearRegistry ', + '!!Be careful! Removes all devices and then deletes a device registry!!', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await clearRegistry( client, @@ -1557,10 +1558,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `deleteRegistry `, - `Deletes a device registry.`, + 'deleteRegistry ', + 'Deletes a device registry.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await deleteRegistry( client, @@ -1571,10 +1572,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `getDevice `, - `Retrieves device info given a device ID.`, + 'getDevice ', + 'Retrieves device info given a device ID.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await getDevice( client, @@ -1586,10 +1587,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `getDeviceConfigs `, - `Retrieves device configurations given a device ID.`, + 'getDeviceConfigs ', + 'Retrieves device configurations given a device ID.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); getDeviceConfigs( client, @@ -1601,10 +1602,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `getDeviceState `, - `Retrieves device state given a device ID.`, + 'getDeviceState ', + 'Retrieves device state given a device ID.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); getDeviceState( client, @@ -1616,10 +1617,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `getRegistry `, - `Retrieves a registry.`, + 'getRegistry ', + 'Retrieves a registry.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await getRegistry( client, @@ -1630,10 +1631,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `listDevices `, - `Lists the devices in a given registry.`, + 'listDevices ', + 'Lists the devices in a given registry.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await listDevices( client, @@ -1644,19 +1645,19 @@ require(`yargs`) // eslint-disable-line } ) .command( - `listRegistries`, - `Lists the registries in a given project.`, + 'listRegistries', + 'Lists the registries in a given project.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await listRegistries(client, opts.projectId, opts.cloudRegion); } ) .command( - `patchEs256 `, - `Patches a device with ES256 authorization credentials.`, + 'patchEs256 ', + 'Patches a device with ES256 authorization credentials.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await patchEs256ForAuth( client, @@ -1669,10 +1670,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `patchRsa256 `, - `Patches a device with RSA256 authentication credentials.`, + 'patchRsa256 ', + 'Patches a device with RSA256 authentication credentials.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await patchRsa256ForAuth( client, @@ -1685,10 +1686,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `setConfig `, - `Sets a devices configuration to the specified data.`, + 'setConfig ', + 'Sets a devices configuration to the specified data.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await setDeviceConfig( client, @@ -1702,10 +1703,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `sendCommand `, - `Sends a command message to a device subscribed to the commands topic`, + 'sendCommand ', + 'Sends a command message to a device subscribed to the commands topic', {}, - async (opts) => { + async opts => { await sendCommand( opts.deviceId, opts.registryId, @@ -1716,10 +1717,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `getIamPolicy `, - `Gets the IAM permissions for a given registry`, + 'getIamPolicy ', + 'Gets the IAM permissions for a given registry', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await getIamPolicy( client, @@ -1730,10 +1731,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `setIamPolicy `, - `Gets the IAM permissions for a given registry`, + 'setIamPolicy ', + 'Gets the IAM permissions for a given registry', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await setIamPolicy( client, @@ -1746,8 +1747,8 @@ require(`yargs`) // eslint-disable-line } ) .command( - `createGateway`, - `Creates a gateway`, + 'createGateway', + 'Creates a gateway', { registryId: { description: @@ -1790,7 +1791,7 @@ require(`yargs`) // eslint-disable-line type: 'string', }, }, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await createGateway( client, @@ -1804,10 +1805,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `listGateways `, - `Lists gateways in a registry.`, + 'listGateways ', + 'Lists gateways in a registry.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await listGateways( client, @@ -1818,10 +1819,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `bindDeviceToGateway `, - `Binds a device to a gateway`, + 'bindDeviceToGateway ', + 'Binds a device to a gateway', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await bindDeviceToGateway( client, @@ -1834,10 +1835,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `unbindDeviceFromGateway `, - `Unbinds a device from a gateway`, + 'unbindDeviceFromGateway ', + 'Unbinds a device from a gateway', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await unbindDeviceFromGateway( client, @@ -1850,10 +1851,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `unbindDeviceFromAllGateways `, - `Unbinds a device from all gateways`, + 'unbindDeviceFromAllGateways ', + 'Unbinds a device from all gateways', {}, - async (opts) => { + async opts => { await unbindDeviceFromAllGateways( opts.projectId, opts.cloudRegion, @@ -1863,18 +1864,18 @@ require(`yargs`) // eslint-disable-line } ) .command( - `unbindAllDevices `, - `Unbinds all devices in a given registry. Mainly for clearing registries`, + 'unbindAllDevices ', + 'Unbinds all devices in a given registry. Mainly for clearing registries', {}, - async (opts) => { + async opts => { await unbindAllDevices(opts.projectId, opts.cloudRegion, opts.registryId); } ) .command( - `listDevicesForGateway `, - `Lists devices in a gateway.`, + 'listDevicesForGateway ', + 'Lists devices in a gateway.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await listDevicesForGateway( client, @@ -1886,10 +1887,10 @@ require(`yargs`) // eslint-disable-line } ) .command( - `listGatewaysForDevice `, - `Lists gateways for a given device.`, + 'listGatewaysForDevice ', + 'Lists gateways for a given device.', {}, - async (opts) => { + async opts => { const client = await getClient(opts.serviceAccount); await listGatewaysForDevice( client, @@ -1901,46 +1902,46 @@ require(`yargs`) // eslint-disable-line } ) .example( - `node $0 createDevice my-device my-registry RS256_X509_PEM ./rsa_cert.pem` + 'node $0 createDevice my-device my-registry RS256_X509_PEM ./rsa_cert.pem' ) .example( - `node $0 createEs256Device my-es-device my-registry ../ec_public.pem` + 'node $0 createEs256Device my-es-device my-registry ../ec_public.pem' ) .example( - `node $0 createRegistry my-registry my-iot-topic --serviceAccount=$secure/svc.json --projectId=my-project-id` + 'node $0 createRegistry my-registry my-iot-topic --serviceAccount=$secure/svc.json --projectId=my-project-id' ) .example( - `node $0 createRsa256Device my-rsa-device my-registry ../rsa_cert.pem` + 'node $0 createRsa256Device my-rsa-device my-registry ../rsa_cert.pem' ) .example( - `node $0 createGateway --registryId=my-registry --gatewayId=my-gateway\ - --format=RS256_X509_PEM --key=./rsa_cert.pem` + 'node $0 createGateway --registryId=my-registry --gatewayId=my-gateway\ + --format=RS256_X509_PEM --key=./rsa_cert.pem' ) - .example(`node $0 createUnauthDevice my-device my-registry`) - .example(`node $0 deleteDevice my-device my-registry`) - .example(`node $0 deleteRegistry my-device my-registry`) - .example(`node $0 getDevice my-device my-registry`) - .example(`node $0 getDeviceState my-device my-registry`) - .example(`node $0 getIamPolicy my-registry`) - .example(`node $0 getRegistry my-registry`) + .example('node $0 createUnauthDevice my-device my-registry') + .example('node $0 deleteDevice my-device my-registry') + .example('node $0 deleteRegistry my-device my-registry') + .example('node $0 getDevice my-device my-registry') + .example('node $0 getDeviceState my-device my-registry') + .example('node $0 getIamPolicy my-registry') + .example('node $0 getRegistry my-registry') .example( - `node $0 listDevices -s path/svc.json -p your-project-id -c asia-east1 my-registry` + 'node $0 listDevices -s path/svc.json -p your-project-id -c asia-east1 my-registry' ) .example( - `node $0 listRegistries -s path/svc.json -p your-project-id -c europe-west1` + 'node $0 listRegistries -s path/svc.json -p your-project-id -c europe-west1' ) - .example(`node $0 patchRsa256 my-device my-registry ../rsa_cert.pem`) - .example(`node $0 patchEs256 my-device my-registry ../ec_public.pem`) - .example(`node $0 setConfig my-device my-registry "test" 0`) - .example(`node $0 sendCommand my-device my-registry test`) + .example('node $0 patchRsa256 my-device my-registry ../rsa_cert.pem') + .example('node $0 patchEs256 my-device my-registry ../ec_public.pem') + .example('node $0 setConfig my-device my-registry "test" 0') + .example('node $0 sendCommand my-device my-registry test') .example( - `node $0 setIamPolicy my-registry user:example@example.com roles/viewer` + 'node $0 setIamPolicy my-registry user:example@example.com roles/viewer' ) .example( - `node $0 setupTopic my-iot-topic --serviceAccount=$HOME/creds_iot.json --projectId=my-project-id` + 'node $0 setupTopic my-iot-topic --serviceAccount=$HOME/creds_iot.json --projectId=my-project-id' ) .wrap(120) .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/iot-core/docs`) + .epilogue('For more information, see https://cloud.google.com/iot-core/docs') .help() .strict().argv; diff --git a/iot/manager/package.json b/iot/manager/package.json index cd2708bafb..82aebe3a19 100644 --- a/iot/manager/package.json +++ b/iot/manager/package.json @@ -19,7 +19,7 @@ "dependencies": { "@google-cloud/iot": "^2.0.0", "@google-cloud/pubsub": "^2.0.0", - "googleapis": "^61.0.0", + "googleapis": "^62.0.0", "yargs": "^16.0.0" }, "devDependencies": { diff --git a/iot/manager/system-test/manager.test.js b/iot/manager/system-test/manager.test.js index b28eb4fc8a..9f6418ccd5 100644 --- a/iot/manager/system-test/manager.test.js +++ b/iot/manager/system-test/manager.test.js @@ -44,11 +44,11 @@ before(async () => { }); assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); // Create a topic to be used for testing. const [topic] = await pubSubClient.createTopic(topicName); diff --git a/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js b/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js index 3df71cb130..ee35de1c28 100644 --- a/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js +++ b/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js @@ -91,7 +91,7 @@ const publishAsync = ( // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. // Cloud IoT Core also supports qos=0 for at most once delivery. console.log('Publishing message:', payload); - client.publish(mqttTopic, payload, {qos: 1}, (err) => { + client.publish(mqttTopic, payload, {qos: 1}, err => { if (!err) { shouldBackoff = false; backoffTime = MINIMUM_BACKOFF_TIME; @@ -118,7 +118,7 @@ const publishAsync = ( client = mqtt.connect(connectionArgs); // [END iot_mqtt_jwt_refresh] - client.on('connect', (success) => { + client.on('connect', success => { console.log('connect'); if (!success) { console.log('Client not connected...'); @@ -139,7 +139,7 @@ const publishAsync = ( shouldBackoff = true; }); - client.on('error', (err) => { + client.on('error', err => { console.log('error', err); }); @@ -230,7 +230,7 @@ const mqttDeviceDemo = ( // same as the device registry's Cloud Pub/Sub topic. const mqttTopic = `/devices/${deviceId}/${messageType}`; - client.on('connect', (success) => { + client.on('connect', success => { console.log('connect'); if (!success) { console.log('Client not connected...'); @@ -244,7 +244,7 @@ const mqttDeviceDemo = ( shouldBackoff = true; }); - client.on('error', (err) => { + client.on('error', err => { console.log('error', err); }); @@ -280,7 +280,7 @@ const attachDevice = (deviceId, client, jwt) => { attachPayload = `{ 'authorization' : ${jwt} }`; } - client.publish(attachTopic, attachPayload, {qos: 1}, (err) => { + client.publish(attachTopic, attachPayload, {qos: 1}, err => { if (!err) { shouldBackoff = false; backoffTime = MINIMUM_BACKOFF_TIME; @@ -301,7 +301,7 @@ const detachDevice = (deviceId, client, jwt) => { detachPayload = `{ 'authorization' : ${jwt} }`; } - client.publish(detachTopic, detachPayload, {qos: 1}, (err) => { + client.publish(detachTopic, detachPayload, {qos: 1}, err => { if (!err) { shouldBackoff = false; backoffTime = MINIMUM_BACKOFF_TIME; @@ -361,7 +361,7 @@ const publishAsyncGateway = ( // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. // Cloud IoT Core also supports qos=0 for at most once delivery. console.log(`Publishing message: ${payload} to ${mqttTopic}`); - client.publish(mqttTopic, payload, {qos: 1}, (err) => { + client.publish(mqttTopic, payload, {qos: 1}, err => { if (!err) { shouldBackoff = false; backoffTime = MINIMUM_BACKOFF_TIME; @@ -440,7 +440,7 @@ const sendDataFromBoundDevice = ( const iatTime = parseInt(Date.now() / 1000); const client = mqtt.connect(connectionArgs); - client.on('connect', (success) => { + client.on('connect', success => { if (!success) { console.log('Client not connected...'); } else if (!publishChainInProgress) { @@ -471,7 +471,7 @@ const sendDataFromBoundDevice = ( shouldBackoff = true; }); - client.on('error', (err) => { + client.on('error', err => { console.log('error', err); }); @@ -528,7 +528,7 @@ const listenForConfigMessages = ( // Create a client, and connect to the Google MQTT bridge. const client = mqtt.connect(connectionArgs); - client.on('connect', (success) => { + client.on('connect', success => { if (!success) { console.log('Client not connected...'); } else { @@ -554,7 +554,7 @@ const listenForConfigMessages = ( shouldBackoff = true; }); - client.on('error', (err) => { + client.on('error', err => { console.log('error', err); }); @@ -615,7 +615,7 @@ const listenForErrorMessages = ( // Create a client, and connect to the Google MQTT bridge. const client = mqtt.connect(connectionArgs); - client.on('connect', (success) => { + client.on('connect', success => { if (!success) { console.log('Client not connected...'); } else { @@ -638,7 +638,7 @@ const listenForErrorMessages = ( shouldBackoff = true; }); - client.on('error', (err) => { + client.on('error', err => { console.log('error', err); }); @@ -654,10 +654,11 @@ const listenForErrorMessages = ( // [END iot_listen_for_error_messages] }; -const {argv} = require(`yargs`) +const {argv} = require('yargs') .options({ projectId: { - default: process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, + default: + process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, description: 'The Project ID to use. Defaults to the value of the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.', requiresArg: true, @@ -714,8 +715,8 @@ const {argv} = require(`yargs`) }, }) .command( - `mqttDeviceDemo`, - `Connects a device, sends data, and receives data`, + 'mqttDeviceDemo', + 'Connects a device, sends data, and receives data', { messageType: { default: 'events', @@ -731,7 +732,7 @@ const {argv} = require(`yargs`) type: 'number', }, }, - (opts) => { + opts => { mqttDeviceDemo( opts.deviceId, opts.registryId, @@ -747,8 +748,8 @@ const {argv} = require(`yargs`) } ) .command( - `sendDataFromBoundDevice`, - `Sends data from a gateway on behalf of a bound device.`, + 'sendDataFromBoundDevice', + 'Sends data from a gateway on behalf of a bound device.', { gatewayId: { description: 'Cloud IoT gateway ID.', @@ -763,7 +764,7 @@ const {argv} = require(`yargs`) type: 'number', }, }, - (opts) => { + opts => { sendDataFromBoundDevice( opts.deviceId, opts.gatewayId, @@ -780,8 +781,8 @@ const {argv} = require(`yargs`) } ) .command( - `listenForConfigMessages`, - `Listens for configuration changes on a gateway and bound device.`, + 'listenForConfigMessages', + 'Listens for configuration changes on a gateway and bound device.', { gatewayId: { description: 'Cloud IoT gateway ID.', @@ -796,7 +797,7 @@ const {argv} = require(`yargs`) type: 'number', }, }, - (opts) => { + opts => { listenForConfigMessages( opts.deviceId, opts.gatewayId, @@ -812,8 +813,8 @@ const {argv} = require(`yargs`) } ) .command( - `listenForErrorMessages`, - `Listens for error messages on a gateway.`, + 'listenForErrorMessages', + 'Listens for error messages on a gateway.', { gatewayId: { description: 'Cloud IoT gateway ID.', @@ -828,7 +829,7 @@ const {argv} = require(`yargs`) type: 'number', }, }, - (opts) => { + opts => { listenForErrorMessages( opts.deviceId, opts.gatewayId, @@ -844,19 +845,19 @@ const {argv} = require(`yargs`) } ) .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` + '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` + '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` + '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` + '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`) + .epilogue('For more information, see https://cloud.google.com/iot-core/docs') .help() .strict(); diff --git a/iot/mqtt_example/system-test/cloudiot_mqtt_example.test.js b/iot/mqtt_example/system-test/cloudiot_mqtt_example.test.js index bf7ff1cbc6..807ebbfd6e 100644 --- a/iot/mqtt_example/system-test/cloudiot_mqtt_example.test.js +++ b/iot/mqtt_example/system-test/cloudiot_mqtt_example.test.js @@ -26,7 +26,7 @@ const projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT; const topicName = `nodejs-iot-test-mqtt-topic-${uuid.v4()}`; const registryName = `nodejs-iot-test-mqtt-registry-${uuid.v4()}`; -const region = `us-central1`; +const region = 'us-central1'; const rsaPublicCert = process.env.NODEJS_IOT_RSA_PUBLIC_CERT; const rsaPrivateKey = process.env.NODEJS_IOT_RSA_PRIVATE_KEY; @@ -45,11 +45,11 @@ assert.ok( before(async () => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); // Create a unique topic to be used for testing. const [topic] = await pubSubClient.createTopic(topicName); @@ -205,8 +205,8 @@ it('should send state message', () => { }); }); -it.only('should receive command message', async () => { - const deviceId = `commands-device`; +it('should receive command message', async () => { + const deviceId = 'commands-device'; const message = 'rotate 180 degrees'; childProcess.execSync( @@ -239,7 +239,7 @@ it.only('should receive command message', async () => { }); }); -it('should listen for bound device config message', () => { +it.skip('should listen for bound device config message', () => { const gatewayId = `nodejs-test-gateway-iot-${uuid.v4()}`; childProcess.execSync( `${helper} createGateway ${registryName} ${gatewayId} --publicKeyFormat=RSA_X509_PEM --publicKeyFile=${rsaPublicCert}`, @@ -276,7 +276,7 @@ it('should listen for bound device config message', () => { }); }); -it('should listen for error topic messages', () => { +it.skip('should listen for error topic messages', () => { const gatewayId = `nodejs-test-gateway-iot-${uuid.v4()}`; childProcess.execSync( `${helper} createGateway ${registryName} ${gatewayId} --publicKeyFormat=RSA_X509_PEM --publicKeyFile=${rsaPublicCert}`, @@ -315,7 +315,7 @@ it('should listen for error topic messages', () => { }); }); -it('should send data from bound device', async () => { +it.skip('should send data from bound device', async () => { const gatewayId = `nodejs-test-gateway-iot-${uuid.v4()}`; childProcess.execSync( `${helper} createGateway ${registryName} ${gatewayId} --publicKeyFormat=RSA_X509_PEM --publicKeyFile=${rsaPublicCert}`, diff --git a/iot/scripts/iam.js b/iot/scripts/iam.js index 779ff948e8..4a60ada5fd 100644 --- a/iot/scripts/iam.js +++ b/iot/scripts/iam.js @@ -19,7 +19,7 @@ * For more information, see https://cloud.google.com/iot. */ -const setTopicPolicy = async (topicName) => { +const setTopicPolicy = async topicName => { // Imports the Google Cloud client library const {PubSub} = require('@google-cloud/pubsub'); @@ -44,7 +44,7 @@ const setTopicPolicy = async (topicName) => { members: [serviceAccount], }; - policy.bindings.forEach((_binding) => { + policy.bindings.forEach(_binding => { if (_binding.role === binding.role) { binding = _binding; hasRole = true; diff --git a/jobs/v3/auto-complete-sample.js b/jobs/v3/auto-complete-sample.js index 161cba6a8a..32a20b3bba 100644 --- a/jobs/v3/auto-complete-sample.js +++ b/jobs/v3/auto-complete-sample.js @@ -14,8 +14,8 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const basicJobSample = require(`./basic-job-sample`); +const basicCompanySample = require('./basic-company-sample'); +const basicJobSample = require('./basic-job-sample'); const createAuthCredential = require('./create-auth-credential'); const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; diff --git a/jobs/v3/basic-job-sample.js b/jobs/v3/basic-job-sample.js index dccaf4c5f0..4c9c924e35 100644 --- a/jobs/v3/basic-job-sample.js +++ b/jobs/v3/basic-job-sample.js @@ -14,8 +14,8 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const createAuthCredential = require(`./create-auth-credential`); +const basicCompanySample = require('./basic-company-sample'); +const createAuthCredential = require('./create-auth-credential'); const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; @@ -40,7 +40,7 @@ const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; /** * Generate a basic job with given companyName. */ -const generateJobWithRequiredFields = (companyName) => { +const generateJobWithRequiredFields = companyName => { const applicationUris = ['http://careers.google.com']; const description = 'Design, develop, test, deploy, maintain and improve software.'; @@ -79,7 +79,7 @@ const createJob = async (jobServiceClient, jobToBeCreated) => { console.log(`Job created: ${JSON.stringify(jobCreated.data)}`); return jobCreated.data; } catch (e) { - console.error(`Got exception while creating job!`); + console.error('Got exception while creating job!'); throw e; } }; @@ -126,7 +126,7 @@ const updateJob = async (jobServiceClient, jobName, jobToBeUpdated) => { console.log(`Job updated: ${JSON.stringify(jobUpdated.data)}`); return jobUpdated.data; } catch (e) { - console.error(`Got exception while updating job!`); + console.error('Got exception while updating job!'); throw e; } }; @@ -157,7 +157,7 @@ const updateJobWithFieldMask = async ( console.log(`Job updated: ${JSON.stringify(jobUpdated.data)}`); return jobUpdated.data; } catch (e) { - console.error(`Got exception while updating job with field mask!`); + console.error('Got exception while updating job with field mask!'); throw e; } }; diff --git a/jobs/v3/batchdelete-jobs-sample.js b/jobs/v3/batchdelete-jobs-sample.js index f35f5b45fd..8cf679cd13 100644 --- a/jobs/v3/batchdelete-jobs-sample.js +++ b/jobs/v3/batchdelete-jobs-sample.js @@ -14,9 +14,9 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const basicJobSample = require(`./basic-job-sample`); -const createAuthCredential = require(`./create-auth-credential`); +const basicCompanySample = require('./basic-company-sample'); +const basicJobSample = require('./basic-job-sample'); +const createAuthCredential = require('./create-auth-credential'); const customAttributeSample = require('./custom-attribute-sample'); const sleep = require('./sleep'); @@ -36,7 +36,7 @@ const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; const batchDelete = async (jobServiceClient, companyName, jobs) => { try { let batchDeleteQuery = `companyName = "${companyName}"`; - jobs.forEach((job) => { + jobs.forEach(job => { batchDeleteQuery += ` AND requisitionId = "${job.requisitionId}"`; }); diff --git a/jobs/v3/commute-search-sample.js b/jobs/v3/commute-search-sample.js index 3f600fca85..cc1c349655 100644 --- a/jobs/v3/commute-search-sample.js +++ b/jobs/v3/commute-search-sample.js @@ -14,9 +14,9 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const basicJobSample = require(`./basic-job-sample`); -const createAuthCredential = require(`./create-auth-credential`); +const basicCompanySample = require('./basic-company-sample'); +const basicJobSample = require('./basic-job-sample'); +const createAuthCredential = require('./create-auth-credential'); const sleep = require('./sleep'); const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; diff --git a/jobs/v3/custom-attribute-sample.js b/jobs/v3/custom-attribute-sample.js index c4b35b206d..4cbcd67f16 100644 --- a/jobs/v3/custom-attribute-sample.js +++ b/jobs/v3/custom-attribute-sample.js @@ -14,8 +14,8 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const basicJobSample = require(`./basic-job-sample`); +const basicCompanySample = require('./basic-company-sample'); +const basicJobSample = require('./basic-job-sample'); const createAuthCredential = require('./create-auth-credential'); const sleep = require('./sleep'); @@ -39,7 +39,7 @@ const REQUEST_META_DATA = { /** * Generate a job with a custom attribute. */ -const generateJobWithACustomAttribute = (companyName) => { +const generateJobWithACustomAttribute = companyName => { const requisitionId = `jobWithACustomAttribute: ${new Date().getTime()}`; const jobTitle = 'Software Engineer'; const applicationUrls = ['http://careers.google.com']; @@ -70,7 +70,7 @@ const generateJobWithACustomAttribute = (companyName) => { /** * CustomAttributeFilter on String value CustomAttribute */ -const filtersOnStringValueCustomAttribute = async (jobServiceClient) => { +const filtersOnStringValueCustomAttribute = async jobServiceClient => { try { const customAttributeFilter = 'NOT EMPTY(someFieldName1)'; const jobQuery = {customAttributeFilter: customAttributeFilter}; @@ -97,7 +97,7 @@ const filtersOnStringValueCustomAttribute = async (jobServiceClient) => { /** * CustomAttributeFilter on Long value CustomAttribute */ -const filtersOnLongValueCustomAttribute = async (jobServiceClient) => { +const filtersOnLongValueCustomAttribute = async jobServiceClient => { try { const customAttributeFilter = '(255 <= someFieldName2) AND' + ' (someFieldName2 <= 257)'; @@ -125,7 +125,7 @@ const filtersOnLongValueCustomAttribute = async (jobServiceClient) => { /** * CustomAttributeFilter on multiple CustomAttributes */ -const filtersOnMultiCustomAttributes = async (jobServiceClient) => { +const filtersOnMultiCustomAttributes = async jobServiceClient => { try { const customAttributeFilter = '(someFieldName1 = "value1") AND ((255 <= someFieldName2) OR ' + diff --git a/jobs/v3/email-alert-search-sample.js b/jobs/v3/email-alert-search-sample.js index aab2b36d6e..91b78e4c1d 100644 --- a/jobs/v3/email-alert-search-sample.js +++ b/jobs/v3/email-alert-search-sample.js @@ -14,8 +14,8 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const basicJobSample = require(`./basic-job-sample`); +const basicCompanySample = require('./basic-company-sample'); +const basicJobSample = require('./basic-job-sample'); const createAuthCredential = require('./create-auth-credential'); const sleep = require('./sleep'); diff --git a/jobs/v3/featured-job-search-sample.js b/jobs/v3/featured-job-search-sample.js index 5d84052aef..3237d30f8d 100644 --- a/jobs/v3/featured-job-search-sample.js +++ b/jobs/v3/featured-job-search-sample.js @@ -14,9 +14,9 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const basicJobSample = require(`./basic-job-sample`); -const createAuthCredential = require(`./create-auth-credential`); +const basicCompanySample = require('./basic-company-sample'); +const basicJobSample = require('./basic-job-sample'); +const createAuthCredential = require('./create-auth-credential'); const sleep = require('./sleep'); const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; @@ -34,7 +34,7 @@ const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; /** * Creates a job as featured. */ -const generateFeaturedJob = (companyName) => { +const generateFeaturedJob = companyName => { const requisitionId = `"featuredJob: ${new Date().getTime()}}`; const jobTitle = 'Software Engineer'; const applicationUrls = ['http://careers.google.com']; diff --git a/jobs/v3/general-search-sample.js b/jobs/v3/general-search-sample.js index fe5d487a27..dc6e5388f4 100644 --- a/jobs/v3/general-search-sample.js +++ b/jobs/v3/general-search-sample.js @@ -14,9 +14,9 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const basicJobSample = require(`./basic-job-sample`); -const createAuthCredential = require(`./create-auth-credential`); +const basicCompanySample = require('./basic-company-sample'); +const basicJobSample = require('./basic-job-sample'); +const createAuthCredential = require('./create-auth-credential'); const sleep = require('./sleep'); const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; diff --git a/jobs/v3/histogram-sample.js b/jobs/v3/histogram-sample.js index 1169707484..50cfa54baa 100644 --- a/jobs/v3/histogram-sample.js +++ b/jobs/v3/histogram-sample.js @@ -14,9 +14,9 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const basicJobSample = require(`./basic-job-sample`); -const createAuthCredential = require(`./create-auth-credential`); +const basicCompanySample = require('./basic-company-sample'); +const basicJobSample = require('./basic-job-sample'); +const createAuthCredential = require('./create-auth-credential'); const customAttributeSample = require('./custom-attribute-sample'); const sleep = require('./sleep'); @@ -40,7 +40,7 @@ const histogramSearch = async (jobServiceClient, companyName) => { }; const customAttributeHistogramFacet = { - key: `someFieldName1`, + key: 'someFieldName1', stringValueHistogram: true, }; diff --git a/jobs/v3/location-search-sample.js b/jobs/v3/location-search-sample.js index 34df024acd..6a20ea41f9 100644 --- a/jobs/v3/location-search-sample.js +++ b/jobs/v3/location-search-sample.js @@ -14,9 +14,9 @@ 'use strict'; -const basicCompanySample = require(`./basic-company-sample`); -const basicJobSample = require(`./basic-job-sample`); -const createAuthCredential = require(`./create-auth-credential`); +const basicCompanySample = require('./basic-company-sample'); +const basicJobSample = require('./basic-job-sample'); +const createAuthCredential = require('./create-auth-credential'); const sleep = require('./sleep'); const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; diff --git a/jobs/v3/package.json b/jobs/v3/package.json index e2e198d0f4..5a3e888fc6 100644 --- a/jobs/v3/package.json +++ b/jobs/v3/package.json @@ -16,7 +16,7 @@ "system-test": "mocha system-test/*.test.js --timeout=40000" }, "dependencies": { - "googleapis": "^61.0.0", + "googleapis": "^62.0.0", "uuid": "^8.0.0", "yargs": "^16.0.0" }, diff --git a/jobs/v3/quickstart.js b/jobs/v3/quickstart.js index b5cfb20b00..33befbde9c 100755 --- a/jobs/v3/quickstart.js +++ b/jobs/v3/quickstart.js @@ -58,9 +58,9 @@ google.auth.getApplicationDefault((err, authClient) => { if (companies.length) { console.log('Companies:'); - companies.forEach((company) => console.log(company.name)); + companies.forEach(company => console.log(company.name)); } else { - console.log(`No companies found.`); + console.log('No companies found.'); } }); }); diff --git a/jobs/v3/sleep.js b/jobs/v3/sleep.js index d7bbb893c3..531a29619b 100644 --- a/jobs/v3/sleep.js +++ b/jobs/v3/sleep.js @@ -14,8 +14,8 @@ 'use strict'; -const sleep = (ms) => { - return new Promise((resolve) => setTimeout(resolve, ms)); +const sleep = ms => { + return new Promise(resolve => setTimeout(resolve, ms)); }; module.exports = sleep; diff --git a/jobs/v3/system-test/basic-company-sample.test.js b/jobs/v3/system-test/basic-company-sample.test.js index b5c0d62082..3686eaba45 100644 --- a/jobs/v3/system-test/basic-company-sample.test.js +++ b/jobs/v3/system-test/basic-company-sample.test.js @@ -16,7 +16,7 @@ const assert = require('assert'); const {execSync} = require('child_process'); -const runSample = `require('./basic-company-sample').runSample()`; +const runSample = "require('./basic-company-sample').runSample()"; it('Should create a company, get a company, update a company, update a company with field mask and delete a company', () => { const output = execSync(`node -e ${runSample}`); diff --git a/jobs/v3/system-test/basic-job-sample.test.js b/jobs/v3/system-test/basic-job-sample.test.js index c13aea0ba8..0f28ad0e10 100644 --- a/jobs/v3/system-test/basic-job-sample.test.js +++ b/jobs/v3/system-test/basic-job-sample.test.js @@ -14,19 +14,19 @@ 'use strict'; -const assert = require(`assert`); +const assert = require('assert'); const {execSync} = require('child_process'); -const runSample = `require('./basic-job-sample').runSample()`; +const runSample = "require('./basic-job-sample').runSample()"; -it(`Should create a job, get a job, update a job, update a job with field mask, and delete a job`, () => { +it('Should create a job, get a job, update a job, update a job with field mask, and delete a job', () => { const output = execSync(`node -e ${runSample}`); const pattern = - `.*Job generated:.*\n` + - `.*Job created:.*\n` + - `.*Job existed:.*\n` + - `.*Job updated:.*changedDescription.*\n` + - `.*Job updated:.*changedJobTitle.*\n` + - `.*Job deleted.*`; + '.*Job generated:.*\n' + + '.*Job created:.*\n' + + '.*Job existed:.*\n' + + '.*Job updated:.*changedDescription.*\n' + + '.*Job updated:.*changedJobTitle.*\n' + + '.*Job deleted.*'; assert.strictEqual(new RegExp(pattern).test(output), true); }); diff --git a/jobs/v3/system-test/batchdelete-jobs-sample.test.js b/jobs/v3/system-test/batchdelete-jobs-sample.test.js index 6f8cd11b1a..40eb9d0305 100644 --- a/jobs/v3/system-test/batchdelete-jobs-sample.test.js +++ b/jobs/v3/system-test/batchdelete-jobs-sample.test.js @@ -16,7 +16,7 @@ const assert = require('assert'); const {execSync} = require('child_process'); -const runSample = `require('./batchdelete-jobs-sample')`; +const runSample = "require('./batchdelete-jobs-sample')"; it('Should batchDelete jobs.', () => { const output = execSync(`node -e ${runSample}`); diff --git a/jobs/v3/system-test/custom-attribute-sample.test.js b/jobs/v3/system-test/custom-attribute-sample.test.js index c2c2c787c9..40c1e21a56 100644 --- a/jobs/v3/system-test/custom-attribute-sample.test.js +++ b/jobs/v3/system-test/custom-attribute-sample.test.js @@ -16,7 +16,7 @@ const assert = require('assert'); const {execSync} = require('child_process'); -const runSample = `require('./custom-attribute-sample').runSample()`; +const runSample = "require('./custom-attribute-sample').runSample()"; it('should search job with custom attribute filter', () => { const output = execSync(`node -e ${runSample}`); diff --git a/jobs/v4/job_search_autocomplete_job_title.js b/jobs/v4/job_search_autocomplete_job_title.js index 020fc540a2..5873dd0cc9 100644 --- a/jobs/v4/job_search_autocomplete_job_title.js +++ b/jobs/v4/job_search_autocomplete_job_title.js @@ -12,7 +12,13 @@ const talent = require('@google-cloud/talent').v4beta1; * @param projectId {string} Your Google Cloud Project ID * @param tenantId {string} Identifier of the Tenantd */ -function sampleCompleteQuery(projectId, tenantId, query, numResults, languageCode) { +function sampleCompleteQuery( + projectId, + tenantId, + query, + numResults, + languageCode +) { const client = new talent.CompletionClient(); // const projectId = 'Your Google Cloud Project ID'; // const tenantId = 'Your Tenant ID (using tenancy is optional)'; @@ -27,7 +33,8 @@ function sampleCompleteQuery(projectId, tenantId, query, numResults, languageCod pageSize: numResults, languageCodes: languageCodes, }; - client.completeQuery(request) + client + .completeQuery(request) .then(responses => { const response = responses[0]; for (const result of response.completionResults) { @@ -41,32 +48,36 @@ function sampleCompleteQuery(projectId, tenantId, query, numResults, languageCod }); } - // [END job_search_autocomplete_job_title_core] // [END job_search_autocomplete_job_title] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('query', { default: '[partially typed job title]', - string: true + string: true, }) .option('num_results', { default: 5, - number: true + number: true, }) .option('language_code', { default: 'en-US', - string: true - }) - .argv; + string: true, + }).argv; -sampleCompleteQuery(argv.project_id, argv.tenant_id, argv.query, argv.num_results, argv.language_code); \ No newline at end of file +sampleCompleteQuery( + argv.project_id, + argv.tenant_id, + argv.query, + argv.num_results, + argv.language_code +); diff --git a/jobs/v4/job_search_batch_delete_job.js b/jobs/v4/job_search_batch_delete_job.js index 926ca37def..5dd6880ac7 100644 --- a/jobs/v4/job_search_batch_delete_job.js +++ b/jobs/v4/job_search_batch_delete_job.js @@ -28,27 +28,25 @@ function sampleBatchDeleteJobs(projectId, tenantId, filter) { client.batchDeleteJobs(request).catch(err => { console.error(err); }); - console.log(`Batch deleted jobs from filter`); + console.log('Batch deleted jobs from filter'); } - // [END job_search_batch_delete_job_core] // [END job_search_batch_delete_job] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('filter', { default: '[Query]', - string: true - }) - .argv; + string: true, + }).argv; -sampleBatchDeleteJobs(argv.project_id, argv.tenant_id, argv.filter); \ No newline at end of file +sampleBatchDeleteJobs(argv.project_id, argv.tenant_id, argv.filter); diff --git a/jobs/v4/job_search_commute_search.js b/jobs/v4/job_search_commute_search.js index 3693a5c2c2..e8bceee4ab 100644 --- a/jobs/v4/job_search_commute_search.js +++ b/jobs/v4/job_search_commute_search.js @@ -46,7 +46,8 @@ function sampleSearchJobs(projectId, tenantId) { jobQuery: jobQuery, }; - client.searchJobs(request) + client + .searchJobs(request) .then(responses => { const resources = responses[0]; for (const resource of resources) { @@ -62,20 +63,18 @@ function sampleSearchJobs(projectId, tenantId) { }); } - // [END job_search_commute_search_core] // [END job_search_commute_search] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true - }) - .argv; + string: true, + }).argv; -sampleSearchJobs(argv.project_id, argv.tenant_id); \ No newline at end of file +sampleSearchJobs(argv.project_id, argv.tenant_id); diff --git a/jobs/v4/job_search_create_client_event.js b/jobs/v4/job_search_create_client_event.js index 78145d8b4f..18ed7d3551 100644 --- a/jobs/v4/job_search_create_client_event.js +++ b/jobs/v4/job_search_create_client_event.js @@ -36,7 +36,8 @@ function sampleCreateClientEvent(projectId, tenantId, requestId, eventId) { // List of job names associated with this event const jobsElement = 'projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]'; - const jobsElement2 = 'projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]'; + const jobsElement2 = + 'projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]'; const jobs = [jobsElement, jobsElement2]; const jobEvent = { type: type, @@ -52,38 +53,42 @@ function sampleCreateClientEvent(projectId, tenantId, requestId, eventId) { parent: formattedParent, clientEvent: clientEvent, }; - client.createClientEvent(request) + client + .createClientEvent(request) .then(responses => { const response = responses[0]; - console.log(`Created client event`); + console.log('Created client event'); }) .catch(err => { console.error(err); }); } - // [END job_search_create_client_event_core] // [END job_search_create_client_event] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('request_id', { default: '[request_id from ResponseMetadata]', - string: true + string: true, }) .option('event_id', { default: '[Set this to a unique identifier]', - string: true - }) - .argv; + string: true, + }).argv; -sampleCreateClientEvent(argv.project_id, argv.tenant_id, argv.request_id, argv.event_id); \ No newline at end of file +sampleCreateClientEvent( + argv.project_id, + argv.tenant_id, + argv.request_id, + argv.event_id +); diff --git a/jobs/v4/job_search_create_company.js b/jobs/v4/job_search_create_company.js index fd4af2e9d5..2ad9eae3af 100644 --- a/jobs/v4/job_search_create_company.js +++ b/jobs/v4/job_search_create_company.js @@ -27,10 +27,11 @@ function sampleCreateCompany(projectId, tenantId, displayName, externalId) { parent: formattedParent, company: company, }; - client.createCompany(request) + client + .createCompany(request) .then(responses => { const response = responses[0]; - console.log(`Created Company`); + console.log('Created Company'); console.log(`Name: ${response.name}`); console.log(`Display Name: ${response.displayName}`); console.log(`External ID: ${response.externalId}`); @@ -40,28 +41,31 @@ function sampleCreateCompany(projectId, tenantId, displayName, externalId) { }); } - // [END job_search_create_company_core] // [END job_search_create_company] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('display_name', { default: 'My Company Name', - string: true + string: true, }) .option('external_id', { default: 'Identifier of this company in my system', - string: true - }) - .argv; + string: true, + }).argv; -sampleCreateCompany(argv.project_id, argv.tenant_id, argv.display_name, argv.external_id); \ No newline at end of file +sampleCreateCompany( + argv.project_id, + argv.tenant_id, + argv.display_name, + argv.external_id +); diff --git a/jobs/v4/job_search_create_job.js b/jobs/v4/job_search_create_job.js index 7f7ffb39a8..c0d33e3ae3 100644 --- a/jobs/v4/job_search_create_job.js +++ b/jobs/v4/job_search_create_job.js @@ -12,7 +12,18 @@ const talent = require('@google-cloud/talent').v4beta1; * @param projectId {string} Your Google Cloud Project ID * @param tenantId {string} Identifier of the Tenant */ -function sampleCreateJob(projectId, tenantId, companyName, requisitionId, title, description, jobApplicationUrl, addressOne, addressTwo, languageCode) { +function sampleCreateJob( + projectId, + tenantId, + companyName, + requisitionId, + title, + description, + jobApplicationUrl, + addressOne, + addressTwo, + languageCode +) { const client = new talent.JobServiceClient(); // const projectId = 'Your Google Cloud Project ID'; // const tenantId = 'Your Tenant ID (using tenancy is optional)'; @@ -43,7 +54,8 @@ function sampleCreateJob(projectId, tenantId, companyName, requisitionId, title, parent: formattedParent, job: job, }; - client.createJob(request) + client + .createJob(request) .then(responses => { const response = responses[0]; console.log(`Created job: ${response.name}`); @@ -53,52 +65,61 @@ function sampleCreateJob(projectId, tenantId, companyName, requisitionId, title, }); } - // [END job_search_create_job_core] // [END job_search_create_job] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('company_name', { default: 'Company name, e.g. projects/your-project/companies/company-id', - string: true + string: true, }) .option('requisition_id', { default: 'Job requisition ID, aka Posting ID. Unique per job.', - string: true + string: true, }) .option('title', { default: 'Software Engineer', - string: true + string: true, }) .option('description', { default: 'This is a description of this wonderful job!', - string: true + string: true, }) .option('job_application_url', { default: 'https://www.example.org/job-posting/123', - string: true + string: true, }) .option('address_one', { default: '1600 Amphitheatre Parkway, Mountain View, CA 94043', - string: true + string: true, }) .option('address_two', { default: '111 8th Avenue, New York, NY 10011', - string: true + string: true, }) .option('language_code', { default: 'en-US', - string: true - }) - .argv; + string: true, + }).argv; -sampleCreateJob(argv.project_id, argv.tenant_id, argv.company_name, argv.requisition_id, argv.title, argv.description, argv.job_application_url, argv.address_one, argv.address_two, argv.language_code); \ No newline at end of file +sampleCreateJob( + argv.project_id, + argv.tenant_id, + argv.company_name, + argv.requisition_id, + argv.title, + argv.description, + argv.job_application_url, + argv.address_one, + argv.address_two, + argv.language_code +); diff --git a/jobs/v4/job_search_create_job_custom_attributes.js b/jobs/v4/job_search_create_job_custom_attributes.js index a4bd9a94fe..bccfed9329 100644 --- a/jobs/v4/job_search_create_job_custom_attributes.js +++ b/jobs/v4/job_search_create_job_custom_attributes.js @@ -12,7 +12,13 @@ const talent = require('@google-cloud/talent').v4beta1; * @param projectId {string} Your Google Cloud Project ID * @param tenantId {string} Identifier of the Tenantd */ -function sampleCreateJob(projectId, tenantId, companyName, requisitionId, languageCode) { +function sampleCreateJob( + projectId, + tenantId, + companyName, + requisitionId, + languageCode +) { const client = new talent.JobServiceClient(); // const projectId = 'Your Google Cloud Project ID'; // const tenantId = 'Your Tenant ID (using tenancy is optional)'; @@ -29,7 +35,8 @@ function sampleCreateJob(projectId, tenantId, companyName, requisitionId, langua parent: formattedParent, job: job, }; - client.createJob(request) + client + .createJob(request) .then(responses => { const response = responses[0]; console.log(`Created job: ${response.name}`); @@ -39,32 +46,36 @@ function sampleCreateJob(projectId, tenantId, companyName, requisitionId, langua }); } - // [END job_search_create_job_custom_attributes_core] // [END job_search_create_job_custom_attributes] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('company_name', { default: 'Company name, e.g. projects/your-project/companies/company-id', - string: true + string: true, }) .option('requisition_id', { default: 'Job requisition ID, aka Posting ID. Unique per job.', - string: true + string: true, }) .option('language_code', { default: 'en-US', - string: true - }) - .argv; + string: true, + }).argv; -sampleCreateJob(argv.project_id, argv.tenant_id, argv.company_name, argv.requisition_id, argv.language_code); \ No newline at end of file +sampleCreateJob( + argv.project_id, + argv.tenant_id, + argv.company_name, + argv.requisition_id, + argv.language_code +); diff --git a/jobs/v4/job_search_create_tenant.js b/jobs/v4/job_search_create_tenant.js index 18326d4c67..f300997079 100644 --- a/jobs/v4/job_search_create_tenant.js +++ b/jobs/v4/job_search_create_tenant.js @@ -19,10 +19,11 @@ function sampleCreateTenant(projectId, externalId) { parent: formattedParent, tenant: tenant, }; - client.createTenant(request) + client + .createTenant(request) .then(responses => { const response = responses[0]; - console.log(`Created Tenant`); + console.log('Created Tenant'); console.log(`Name: ${response.name}`); console.log(`External ID: ${response.externalId}`); }) @@ -31,20 +32,18 @@ function sampleCreateTenant(projectId, externalId) { }); } - // [END job_search_create_tenant_core] // [END job_search_create_tenant] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('external_id', { default: 'Your Unique Identifier for Tenant', - string: true - }) - .argv; + string: true, + }).argv; -sampleCreateTenant(argv.project_id, argv.external_id); \ No newline at end of file +sampleCreateTenant(argv.project_id, argv.external_id); diff --git a/jobs/v4/job_search_custom_ranking_search.js b/jobs/v4/job_search_custom_ranking_search.js index eea6ce7b76..f0b207abf0 100644 --- a/jobs/v4/job_search_custom_ranking_search.js +++ b/jobs/v4/job_search_custom_ranking_search.js @@ -40,7 +40,8 @@ function sampleSearchJobs(projectId, tenantId) { orderBy: orderBy, }; - client.searchJobs(request) + client + .searchJobs(request) .then(responses => { const resources = responses[0]; for (const resource of resources) { @@ -56,20 +57,18 @@ function sampleSearchJobs(projectId, tenantId) { }); } - // [END job_search_custom_ranking_search_core] // [END job_search_custom_ranking_search] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true - }) - .argv; + string: true, + }).argv; -sampleSearchJobs(argv.project_id, argv.tenant_id); \ No newline at end of file +sampleSearchJobs(argv.project_id, argv.tenant_id); diff --git a/jobs/v4/job_search_delete_company.js b/jobs/v4/job_search_delete_company.js index ba2b8699b8..a2f492c100 100644 --- a/jobs/v4/job_search_delete_company.js +++ b/jobs/v4/job_search_delete_company.js @@ -16,27 +16,25 @@ function sampleDeleteCompany(projectId, tenantId, companyId) { client.deleteCompany({name: formattedName}).catch(err => { console.error(err); }); - console.log(`Deleted company`); + console.log('Deleted company'); } - // [END job_search_delete_company_core] // [END job_search_delete_company] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('company_id', { default: 'ID of the company to delete', - string: true - }) - .argv; + string: true, + }).argv; -sampleDeleteCompany(argv.project_id, argv.tenant_id, argv.company_id); \ No newline at end of file +sampleDeleteCompany(argv.project_id, argv.tenant_id, argv.company_id); diff --git a/jobs/v4/job_search_delete_job.js b/jobs/v4/job_search_delete_job.js index 6046e72cdd..f34004a0aa 100644 --- a/jobs/v4/job_search_delete_job.js +++ b/jobs/v4/job_search_delete_job.js @@ -16,27 +16,25 @@ function sampleDeleteJob(projectId, tenantId, jobId) { client.deleteJob({name: formattedName}).catch(err => { console.error(err); }); - console.log(`Deleted job.`); + console.log('Deleted job.'); } - // [END job_search_delete_job_core] // [END job_search_delete_job] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('job_id', { default: 'Company ID', - string: true - }) - .argv; + string: true, + }).argv; -sampleDeleteJob(argv.project_id, argv.tenant_id, argv.job_id); \ No newline at end of file +sampleDeleteJob(argv.project_id, argv.tenant_id, argv.job_id); diff --git a/jobs/v4/job_search_delete_tenant.js b/jobs/v4/job_search_delete_tenant.js index 17d3904c54..162fd20784 100644 --- a/jobs/v4/job_search_delete_tenant.js +++ b/jobs/v4/job_search_delete_tenant.js @@ -15,23 +15,21 @@ function sampleDeleteTenant(projectId, tenantId) { client.deleteTenant({name: formattedName}).catch(err => { console.error(err); }); - console.log(`Deleted Tenant.`); + console.log('Deleted Tenant.'); } - // [END job_search_delete_tenant_core] // [END job_search_delete_tenant] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID)', - string: true - }) - .argv; + string: true, + }).argv; -sampleDeleteTenant(argv.project_id, argv.tenant_id); \ No newline at end of file +sampleDeleteTenant(argv.project_id, argv.tenant_id); diff --git a/jobs/v4/job_search_get_company.js b/jobs/v4/job_search_get_company.js index c6be75e6f4..359895ddd9 100644 --- a/jobs/v4/job_search_get_company.js +++ b/jobs/v4/job_search_get_company.js @@ -13,7 +13,8 @@ function sampleGetCompany(projectId, tenantId, companyId) { // const tenantId = 'Your Tenant ID (using tenancy is optional)'; // const companyId = 'Company ID'; const formattedName = client.companyPath(projectId, tenantId, companyId); - client.getCompany({name: formattedName}) + client + .getCompany({name: formattedName}) .then(responses => { const response = responses[0]; console.log(`Company name: ${response.name}`); @@ -24,24 +25,22 @@ function sampleGetCompany(projectId, tenantId, companyId) { }); } - // [END job_search_get_company_core] // [END job_search_get_company] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('company_id', { default: 'Company ID', - string: true - }) - .argv; + string: true, + }).argv; -sampleGetCompany(argv.project_id, argv.tenant_id, argv.company_id); \ No newline at end of file +sampleGetCompany(argv.project_id, argv.tenant_id, argv.company_id); diff --git a/jobs/v4/job_search_get_job.js b/jobs/v4/job_search_get_job.js index 4eb69a140a..803c969a1e 100644 --- a/jobs/v4/job_search_get_job.js +++ b/jobs/v4/job_search_get_job.js @@ -13,7 +13,8 @@ function sampleGetJob(projectId, tenantId, jobId) { // const tenantId = 'Your Tenant ID (using tenancy is optional)'; // const jobId = 'Job ID'; const formattedName = client.jobPath(projectId, tenantId, jobId); - client.getJob({name: formattedName}) + client + .getJob({name: formattedName}) .then(responses => { const response = responses[0]; console.log(`Job name: ${response.name}`); @@ -36,24 +37,22 @@ function sampleGetJob(projectId, tenantId, jobId) { }); } - // [END job_search_get_job_core] // [END job_search_get_job] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('job_id', { default: 'Job ID', - string: true - }) - .argv; + string: true, + }).argv; -sampleGetJob(argv.project_id, argv.tenant_id, argv.job_id); \ No newline at end of file +sampleGetJob(argv.project_id, argv.tenant_id, argv.job_id); diff --git a/jobs/v4/job_search_get_tenant.js b/jobs/v4/job_search_get_tenant.js index a182cec7f8..42d30f5360 100644 --- a/jobs/v4/job_search_get_tenant.js +++ b/jobs/v4/job_search_get_tenant.js @@ -12,7 +12,8 @@ function sampleGetTenant(projectId, tenantId) { // const projectId = 'Your Google Cloud Project ID'; // const tenantId = 'Your Tenant ID'; const formattedName = client.tenantPath(projectId, tenantId); - client.getTenant({name: formattedName}) + client + .getTenant({name: formattedName}) .then(responses => { const response = responses[0]; console.log(`Name: ${response.name}`); @@ -23,20 +24,18 @@ function sampleGetTenant(projectId, tenantId) { }); } - // [END job_search_get_tenant_core] // [END job_search_get_tenant] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID', - string: true - }) - .argv; + string: true, + }).argv; -sampleGetTenant(argv.project_id, argv.tenant_id); \ No newline at end of file +sampleGetTenant(argv.project_id, argv.tenant_id); diff --git a/jobs/v4/job_search_histogram_search.js b/jobs/v4/job_search_histogram_search.js index 8ef7b4b628..315c48d102 100644 --- a/jobs/v4/job_search_histogram_search.js +++ b/jobs/v4/job_search_histogram_search.js @@ -38,7 +38,8 @@ function sampleSearchJobs(projectId, tenantId, query) { histogramQueries: histogramQueries, }; - client.searchJobs(request) + client + .searchJobs(request) .then(responses => { const resources = responses[0]; for (const resource of resources) { @@ -54,24 +55,22 @@ function sampleSearchJobs(projectId, tenantId, query) { }); } - // [END job_search_histogram_search_core] // [END job_search_histogram_search] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('query', { default: 'count(base_compensation, [bucket(12, 20)])', - string: true - }) - .argv; + string: true, + }).argv; -sampleSearchJobs(argv.project_id, argv.tenant_id, argv.query); \ No newline at end of file +sampleSearchJobs(argv.project_id, argv.tenant_id, argv.query); diff --git a/jobs/v4/job_search_list_companies.js b/jobs/v4/job_search_list_companies.js index 1b5d9cef46..cb74563b28 100644 --- a/jobs/v4/job_search_list_companies.js +++ b/jobs/v4/job_search_list_companies.js @@ -19,7 +19,8 @@ function sampleListCompanies(projectId, tenantId) { // const tenantId = 'Your Tenant ID (using tenancy is optional)'; const formattedParent = client.tenantPath(projectId, tenantId); - client.listCompanies({parent: formattedParent}) + client + .listCompanies({parent: formattedParent}) .then(responses => { const resources = responses[0]; for (const resource of resources) { @@ -33,20 +34,18 @@ function sampleListCompanies(projectId, tenantId) { }); } - // [END job_search_list_companies_core] // [END job_search_list_companies] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true - }) - .argv; + string: true, + }).argv; -sampleListCompanies(argv.project_id, argv.tenant_id); \ No newline at end of file +sampleListCompanies(argv.project_id, argv.tenant_id); diff --git a/jobs/v4/job_search_list_jobs.js b/jobs/v4/job_search_list_jobs.js index 22b656c1fe..7c8df41abc 100644 --- a/jobs/v4/job_search_list_jobs.js +++ b/jobs/v4/job_search_list_jobs.js @@ -24,7 +24,8 @@ function sampleListJobs(projectId, tenantId, filter) { filter: filter, }; - client.listJobs(request) + client + .listJobs(request) .then(responses => { const resources = responses[0]; for (const resource of resources) { @@ -39,24 +40,22 @@ function sampleListJobs(projectId, tenantId, filter) { }); } - // [END job_search_list_jobs_core] // [END job_search_list_jobs] // tslint:disable-next-line:no-any -const argv = require(`yargs`) +const argv = require('yargs') .option('project_id', { default: 'Your Google Cloud Project ID', - string: true + string: true, }) .option('tenant_id', { default: 'Your Tenant ID (using tenancy is optional)', - string: true + string: true, }) .option('filter', { default: 'companyName=projects/my-project/companies/company-id', - string: true - }) - .argv; + string: true, + }).argv; -sampleListJobs(argv.project_id, argv.tenant_id, argv.filter); \ No newline at end of file +sampleListJobs(argv.project_id, argv.tenant_id, argv.filter); diff --git a/jobs/v4/job_search_list_tenants.js b/jobs/v4/job_search_list_tenants.js index 546a295fc1..7316417413 100644 --- a/jobs/v4/job_search_list_tenants.js +++ b/jobs/v4/job_search_list_tenants.js @@ -13,7 +13,8 @@ function sampleListTenants(projectId) { // const projectId = 'Your Google Cloud Project ID'; const formattedParent = client.projectPath(projectId); - client.listTenants({parent: formattedParent}) + client + .listTenants({parent: formattedParent}) .then(responses => { const resources = responses[0]; for (const resource of resources) { @@ -26,16 +27,13 @@ function sampleListTenants(projectId) { }); } - // [END job_search_list_tenants_core] // [END job_search_list_tenants] // tslint:disable-next-line:no-any -const argv = require(`yargs`) - .option('project_id', { - default: 'Your Google Cloud Project ID', - string: true - }) - .argv; +const argv = require('yargs').option('project_id', { + default: 'Your Google Cloud Project ID', + string: true, +}).argv; -sampleListTenants(argv.project_id); \ No newline at end of file +sampleListTenants(argv.project_id); diff --git a/memorystore/redis/server.js b/memorystore/redis/server.js index 5e5f24bd8e..0aff1a06dc 100644 --- a/memorystore/redis/server.js +++ b/memorystore/redis/server.js @@ -21,7 +21,7 @@ const REDISHOST = process.env.REDISHOST || 'localhost'; const REDISPORT = process.env.REDISPORT || 6379; const client = redis.createClient(REDISPORT, REDISHOST); -client.on('error', (err) => console.error('ERR:REDIS:', err)); +client.on('error', err => console.error('ERR:REDIS:', err)); // create a server http diff --git a/package.json b/package.json index d2a0e3952d..aadd92ff03 100644 --- a/package.json +++ b/package.json @@ -13,18 +13,12 @@ }, "private": true, "scripts": { - "lint": "eslint '**/*.js'", - "fix": "eslint --fix '**/*.js'", + "lint": "gts check", + "fix": "gts fix", "test": "echo 'Please run tests in each sample directory.' && exit 1" }, "devDependencies": { - "eslint": "^7.0.0", - "eslint-config-prettier": "^6.0.0", - "eslint-plugin-node": "^11.0.0", - "eslint-plugin-prettier": "^3.1.0", - "eslint-plugin-promise": "^4.1.1", "gts": "^3.0.0", - "prettier": "^2.0.0", "requestretry": "^4.0.0", "typescript": "^4.0.0" } diff --git a/run/hello-broken/test/system.test.js b/run/hello-broken/test/system.test.js index 1de85e64fe..0f43eb6546 100644 --- a/run/hello-broken/test/system.test.js +++ b/run/hello-broken/test/system.test.js @@ -62,8 +62,8 @@ describe('End-to-End Tests', () => { ); assert.strictEqual( response.body, - `Hello World!`, - `Expected fallback "World" not found` + 'Hello World!', + 'Expected fallback "World" not found' ); }); }); diff --git a/run/helloworld/package.json b/run/helloworld/package.json index 2b9bbd7773..11f958a3b6 100644 --- a/run/helloworld/package.json +++ b/run/helloworld/package.json @@ -19,6 +19,6 @@ "devDependencies": { "got": "^11.0.0", "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/run/idp-sql/app.js b/run/idp-sql/app.js index 0b5f9f4985..63ad7ab157 100644 --- a/run/idp-sql/app.js +++ b/run/idp-sql/app.js @@ -14,10 +14,10 @@ 'use strict'; -const { getVotes, getVoteCount, insertVote } = require('./cloud-sql'); +const {getVotes, getVoteCount, insertVote} = require('./cloud-sql'); const express = require('express'); -const { buildRenderedHtml } = require('./handlebars'); -const { authenticateJWT, requestLogger } = require('./middleware'); +const {buildRenderedHtml} = require('./handlebars'); +const {authenticateJWT, requestLogger} = require('./middleware'); const app = express(); app.use(express.static(__dirname + '/static')); @@ -54,7 +54,9 @@ app.get('/', requestLogger, async (req, res) => { leadTeam = 'DOGS'; voteDiff = dogsTotalVotes - catsTotalVotes; } - leaderMessage = `${leadTeam} are winning by ${voteDiff} vote${voteDiff > 1 ? 's' : ''}.`; + leaderMessage = `${leadTeam} are winning by ${voteDiff} vote${ + voteDiff > 1 ? 's' : '' + }.`; } else { leaderMessage = 'CATS and DOGS are evenly matched!'; } @@ -70,9 +72,10 @@ app.get('/', requestLogger, async (req, res) => { }); res.status(200).send(renderedHtml); } catch (err) { - const message = "Error while connecting to the Cloud SQL database. " + - "Check that your username and password are correct, that the Cloud SQL " + - "proxy is running (locally), and that the database/table exists and is " + + const message = + 'Error while connecting to the Cloud SQL database. ' + + 'Check that your username and password are correct, that the Cloud SQL ' + + 'proxy is running (locally), and that the database/table exists and is ' + `ready for use: ${err}`; req.logger.error(message); // request-based logger with trace support res @@ -104,7 +107,7 @@ app.post('/', requestLogger, authenticateJWT, async (req, res) => { // Save the data to the database. try { await insertVote(vote); - req.logger.info({message: 'vote_inserted', vote}); // request-based logger with trace support + req.logger.info({message: 'vote_inserted', vote}); // request-based logger with trace support } catch (err) { req.logger.error(`Error while attempting to submit vote: ${err}`); res diff --git a/run/idp-sql/cloud-sql.js b/run/idp-sql/cloud-sql.js index 1ddcce46dd..2a89abd9a5 100644 --- a/run/idp-sql/cloud-sql.js +++ b/run/idp-sql/cloud-sql.js @@ -13,8 +13,8 @@ // limitations under the License. const Knex = require('knex'); -const { getCredConfig } = require('./secrets'); -const { logger } = require('./logging'); +const {getCredConfig} = require('./secrets'); +const {logger} = require('./logging'); const TABLE = process.env.TABLE || 'votes'; let knex, credConfig; @@ -31,17 +31,17 @@ const config = { createTimeoutMillis: 30000, idleTimeoutMillis: 600000, createRetryIntervalMillis: 200, -} +}; // [START run_user_auth_sql_connect] /** -* Connect to the Cloud SQL instance through UNIX Sockets -* -* @param {object} credConfig The Cloud SQL connection configuration from Secret Manager -* @returns {object} Knex's PostgreSQL client -*/ -const connectWithUnixSockets = async (credConfig) => { - const dbSocketPath = process.env.DB_SOCKET_PATH || "/cloudsql" + * Connect to the Cloud SQL instance through UNIX Sockets + * + * @param {object} credConfig The Cloud SQL connection configuration from Secret Manager + * @returns {object} Knex's PostgreSQL client + */ +const connectWithUnixSockets = async credConfig => { + const dbSocketPath = process.env.DB_SOCKET_PATH || '/cloudsql'; // Establish a connection to the database return Knex({ client: 'pg', @@ -51,15 +51,15 @@ const connectWithUnixSockets = async (credConfig) => { database: credConfig.DB_NAME, // e.g. 'my-database' host: `${dbSocketPath}/${credConfig.CLOUD_SQL_CONNECTION_NAME}`, }, - ...config + ...config, }); -} +}; // [END run_user_auth_sql_connect] // Method to connect locally on Windows -const connectWithTcp = (credConfig) => { +const connectWithTcp = credConfig => { // Extract host and port from socket address - const dbSocketAddr = process.env.DB_HOST.split(":") // e.g. '127.0.0.1:5432' + const dbSocketAddr = process.env.DB_HOST.split(':'); // e.g. '127.0.0.1:5432' // Establish a connection to the database return Knex({ client: 'pg', @@ -70,17 +70,16 @@ const connectWithTcp = (credConfig) => { host: dbSocketAddr[0], // e.g. '127.0.0.1' port: dbSocketAddr[1], // e.g. '5432' }, - ...config + ...config, }); -} - +}; /** -* Connect to the Cloud SQL instance through TCP or UNIX Sockets -* dependent on DB_HOST env var -* -* @returns {object} Knex's PostgreSQL client -*/ + * Connect to the Cloud SQL instance through TCP or UNIX Sockets + * dependent on DB_HOST env var + * + * @returns {object} Knex's PostgreSQL client + */ const connect = async () => { if (!credConfig) credConfig = await getCredConfig(); if (process.env.DB_HOST) { @@ -88,24 +87,24 @@ const connect = async () => { } else { return connectWithUnixSockets(credConfig); } -} +}; /** -* Insert a vote record into the database. -* -* @param {object} vote The vote record to insert. -* @returns {Promise} -*/ -const insertVote = async (vote) => { + * Insert a vote record into the database. + * + * @param {object} vote The vote record to insert. + * @returns {Promise} + */ +const insertVote = async vote => { if (!knex) knex = await connect(); return knex(TABLE).insert(vote); }; /** -* Retrieve the latest 5 vote records from the database. -* -* @returns {Promise} -*/ + * Retrieve the latest 5 vote records from the database. + * + * @returns {Promise} + */ const getVotes = async () => { if (!knex) knex = await connect(); return knex @@ -116,26 +115,26 @@ const getVotes = async () => { }; /** -* Retrieve the total count of records for a given candidate -* from the database. -* -* @param {object} candidate The candidate for which to get the total vote count -* @returns {Promise} -*/ -const getVoteCount = async (candidate) => { + * Retrieve the total count of records for a given candidate + * from the database. + * + * @param {object} candidate The candidate for which to get the total vote count + * @returns {Promise} + */ +const getVoteCount = async candidate => { if (!knex) knex = await connect(); return knex(TABLE).count('vote_id').where('candidate', candidate); }; /** -* Create "votes" table in the Cloud SQL database -*/ + * Create "votes" table in the Cloud SQL database + */ const createTable = async () => { if (!knex) knex = await connect(); const exists = await knex.schema.hasTable(TABLE); if (!exists) { try { - await knex.schema.createTable(TABLE, (table) => { + await knex.schema.createTable(TABLE, table => { table.bigIncrements('vote_id').notNull(); table.timestamp('time_cast').notNull(); table.specificType('candidate', 'CHAR(6) NOT NULL'); @@ -152,7 +151,7 @@ const createTable = async () => { const closeConnection = () => { if (!knex) knex.destroy(); logger.info('DB connection closed.'); -} +}; module.exports = { getVoteCount, @@ -160,4 +159,4 @@ module.exports = { insertVote, createTable, closeConnection, -} +}; diff --git a/run/idp-sql/handlebars.js b/run/idp-sql/handlebars.js index a8505469ca..4dbb969002 100644 --- a/run/idp-sql/handlebars.js +++ b/run/idp-sql/handlebars.js @@ -13,25 +13,25 @@ // limitations under the License. const handlebars = require('handlebars'); -const { readFile } = require('fs').promises; +const {readFile} = require('fs').promises; let index, template; /** -* Builds and executes Handlebars.js template for rendered HTML -* -* @param {object} config The template config object. -* @returns {Promise} -*/ -const buildRenderedHtml = async (config) => { + * Builds and executes Handlebars.js template for rendered HTML + * + * @param {object} config The template config object. + * @returns {Promise} + */ +const buildRenderedHtml = async config => { if (!index) index = await readFile(__dirname + '/views/index.html', 'utf8'); if (!template) template = handlebars.compile(index); return template(config); }; // Register customer Handlebars.js helper -handlebars.registerHelper('ternary', function(comp1, comp2, opt1, opt2) { - return (comp1.trim() == comp2.trim()) ? opt1 : opt2; +handlebars.registerHelper('ternary', (comp1, comp2, opt1, opt2) => { + return comp1.trim() == comp2.trim() ? opt1 : opt2; }); -module.exports = { buildRenderedHtml } +module.exports = {buildRenderedHtml}; diff --git a/run/idp-sql/index.js b/run/idp-sql/index.js index f4e68fdfcc..f630e917c3 100644 --- a/run/idp-sql/index.js +++ b/run/idp-sql/index.js @@ -14,11 +14,11 @@ const app = require('./app'); const pkg = require('./package.json'); -const { logger } = require('./logging'); -const { initTracing } = require('./middleware'); -const { createTable, closeConnection } = require('./cloud-sql'); +const {logger} = require('./logging'); +const {initTracing} = require('./middleware'); +const {createTable, closeConnection} = require('./cloud-sql'); -const { GoogleAuth } = require('google-auth-library'); +const {GoogleAuth} = require('google-auth-library'); const auth = new GoogleAuth(); const PORT = process.env.PORT || 8080; @@ -49,7 +49,7 @@ process.on('SIGTERM', () => { logger.on('finish', () => { console.log(`${pkg.name}: logs flushed`); process.exit(0); - }) + }); }); main(); diff --git a/run/idp-sql/logging.js b/run/idp-sql/logging.js index 521b513758..583f1ace6b 100644 --- a/run/idp-sql/logging.js +++ b/run/idp-sql/logging.js @@ -13,7 +13,7 @@ // limitations under the License. // Create a Winston logger that streams to Stackdriver Logging. -const { createLogger, transports ,format } = require('winston'); +const {createLogger, transports, format} = require('winston'); // Add severity label for Stackdriver log parsing const addSeverity = format((info, opts) => { @@ -26,12 +26,12 @@ const logger = createLogger({ format: format.combine( addSeverity(), format.timestamp(), - format.json(), + format.json() // format.prettyPrint(), // Uncomment for local debugging ), transports: [new transports.Console()], }); module.exports = { - logger + logger, }; diff --git a/run/idp-sql/middleware.js b/run/idp-sql/middleware.js index d290756767..0cf17e6ecc 100644 --- a/run/idp-sql/middleware.js +++ b/run/idp-sql/middleware.js @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -const { logger } = require('./logging'); // Import winston logger instance +const {logger} = require('./logging'); // Import winston logger instance // [START run_user_auth_jwt] const firebase = require('firebase-admin'); @@ -26,25 +26,28 @@ const authenticateJWT = (req, res, next) => { const token = authHeader.split(' ')[1]; // If the provided ID token has the correct format, is not expired, and is // properly signed, the method returns the decoded ID token - firebase.auth().verifyIdToken(token).then(function(decodedToken) { - let uid = decodedToken.uid; - req.uid = uid; - next(); - }).catch((err) => { - req.logger.error(`Error with authentication: ${err}`); - return res.sendStatus(403); - }); + firebase + .auth() + .verifyIdToken(token) + .then(decodedToken => { + const uid = decodedToken.uid; + req.uid = uid; + next(); + }) + .catch(err => { + req.logger.error(`Error with authentication: ${err}`); + return res.sendStatus(403); + }); } else { return res.sendStatus(401); } -} +}; // [END run_user_auth_jwt] - let project; -const initTracing = (projectId) => { +const initTracing = projectId => { project = projectId; -} +}; // Add logging field with trace ID for logging correlation // For more info, see https://cloud.google.com/run/docs/logging#correlate-logs @@ -52,15 +55,15 @@ const requestLogger = (req, res, next) => { const traceHeader = req.header('X-Cloud-Trace-Context'); let trace; if (traceHeader) { - const [traceId] = traceHeader.split("/"); + const [traceId] = traceHeader.split('/'); trace = `projects/${project}/traces/${traceId}`; } req.logger = logger.child({'logging.googleapis.com/trace': trace}); next(); -} +}; module.exports = { authenticateJWT, requestLogger, - initTracing -} + initTracing, +}; diff --git a/run/idp-sql/package.json b/run/idp-sql/package.json index 976f1ed634..6518311ac7 100644 --- a/run/idp-sql/package.json +++ b/run/idp-sql/package.json @@ -33,6 +33,6 @@ "mocha": "^8.0.0", "short-uuid": "^4.1.0", "sinon": "^9.2.0", - "supertest": "^4.0.0" + "supertest": "^6.0.0" } } diff --git a/run/idp-sql/secrets.js b/run/idp-sql/secrets.js index c67d67e997..c6c0a2b864 100644 --- a/run/idp-sql/secrets.js +++ b/run/idp-sql/secrets.js @@ -12,13 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -const { logger } = require('./logging'); +const {logger} = require('./logging'); // CLOUD_SQL_CREDENTIALS_SECRET is the resource ID of the secret, passed in by environment variable. // Format: projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION const {CLOUD_SQL_CREDENTIALS_SECRET} = process.env; - // [START run_user_auth_secrets] const {SecretManagerServiceClient} = require('@google-cloud/secret-manager'); let client; @@ -43,24 +42,29 @@ async function getCredConfig() { // to retreive database credentials return JSON.parse(secrets.toString('utf8')); } catch (err) { - throw Error(`Unable to parse secret from Secret Manager. Make sure that the secret is JSON formatted: ${err}`) + throw Error( + `Unable to parse secret from Secret Manager. Make sure that the secret is JSON formatted: ${err}` + ); } } else { - logger.info('CLOUD_SQL_CREDENTIALS_SECRET env var not set. Defaulting to environment variables.'); + logger.info( + 'CLOUD_SQL_CREDENTIALS_SECRET env var not set. Defaulting to environment variables.' + ); if (!process.env.DB_USER) throw Error('DB_USER needs to be set.'); if (!process.env.DB_PASSWORD) throw Error('DB_PASSWORD needs to be set.'); if (!process.env.DB_NAME) throw Error('DB_NAME needs to be set.'); - if (!process.env.CLOUD_SQL_CONNECTION_NAME) throw Error('CLOUD_SQL_CONNECTION_NAME needs to be set.'); + if (!process.env.CLOUD_SQL_CONNECTION_NAME) + throw Error('CLOUD_SQL_CONNECTION_NAME needs to be set.'); return { DB_USER: process.env.DB_USER, DB_PASSWORD: process.env.DB_PASSWORD, DB_NAME: process.env.DB_NAME, - CLOUD_SQL_CONNECTION_NAME: process.env.CLOUD_SQL_CONNECTION_NAME - } + CLOUD_SQL_CONNECTION_NAME: process.env.CLOUD_SQL_CONNECTION_NAME, + }; } } module.exports = { - getCredConfig -} + getCredConfig, +}; diff --git a/run/idp-sql/static/config.js b/run/idp-sql/static/config.js index 31f5a1822f..e9a35270fc 100644 --- a/run/idp-sql/static/config.js +++ b/run/idp-sql/static/config.js @@ -1,6 +1,6 @@ // [START run_end_user_firebase_config] const config = { - apiKey: "API_KEY", - authDomain: "PROJECT_ID.firebaseapp.com", + apiKey: 'API_KEY', + authDomain: 'PROJECT_ID.firebaseapp.com', }; // [END run_end_user_firebase_config] diff --git a/run/idp-sql/static/firebase.js b/run/idp-sql/static/firebase.js index 7e05f16cd5..b2f38b37f3 100644 --- a/run/idp-sql/static/firebase.js +++ b/run/idp-sql/static/firebase.js @@ -2,7 +2,7 @@ firebase.initializeApp(config); // Watch for state change from sign in function initApp() { - firebase.auth().onAuthStateChanged(function(user) { + firebase.auth().onAuthStateChanged(user => { if (user) { // User is signed in. document.getElementById('signInButton').innerText = 'Sign Out'; @@ -14,29 +14,36 @@ function initApp() { } }); } -window.onload = function() { +window.onload = function () { initApp(); -} +}; // [START run_end_user_firebase_sign_in] function signIn() { - var provider = new firebase.auth.GoogleAuthProvider(); + const provider = new firebase.auth.GoogleAuthProvider(); provider.addScope('https://www.googleapis.com/auth/userinfo.email'); - firebase.auth().signInWithPopup(provider).then(function(result) { - // Returns the signed in user along with the provider's credential - console.log(`${result.user.displayName} logged in.`); - window.alert(`Welcome ${result.user.displayName}!`) - }).catch((err) => { - console.log(`Error during sign in: ${err.message}`) - }); + firebase + .auth() + .signInWithPopup(provider) + .then(result => { + // Returns the signed in user along with the provider's credential + console.log(`${result.user.displayName} logged in.`); + window.alert(`Welcome ${result.user.displayName}!`); + }) + .catch(err => { + console.log(`Error during sign in: ${err.message}`); + }); } // [END run_end_user_firebase_sign_in] function signOut() { - firebase.auth().signOut().then(function(result) { - }).catch((err) => { - console.log(`Error during sign out: ${err.message}`) - }) + firebase + .auth() + .signOut() + .then(result => {}) + .catch(err => { + console.log(`Error during sign out: ${err.message}`); + }); } // Toggle Sign in/out button @@ -60,7 +67,7 @@ async function vote(team) { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', - 'Authorization': `Bearer ${token}` + Authorization: `Bearer ${token}`, }, body: 'team=' + team, // send application data (vote) }); diff --git a/run/idp-sql/test/app.test.js b/run/idp-sql/test/app.test.js index 133d622804..d8323e2b37 100644 --- a/run/idp-sql/test/app.test.js +++ b/run/idp-sql/test/app.test.js @@ -17,7 +17,7 @@ const assert = require('assert'); const path = require('path'); const supertest = require('supertest'); -const { buildRenderedHtml } = require('../handlebars'); +const {buildRenderedHtml} = require('../handlebars'); let request; @@ -28,9 +28,7 @@ describe('Unit Tests', () => { }); it('should reject request without JWT token', async () => { - await request - .post('/') - .expect(401); + await request.post('/').expect(401); }); it('should reject request with invalid JWT token', async () => { @@ -45,12 +43,11 @@ describe('Unit Tests', () => { votes: [], catsCount: 1, dogsCount: 100, - leadTeam: "Dogs", + leadTeam: 'Dogs', voteDiff: 99, - leaderMessage: "Dogs are winning", + leaderMessage: 'Dogs are winning', }); assert(renderedHtml.includes('

100 votes

')); - }) - + }); }); diff --git a/run/idp-sql/test/system.test.js b/run/idp-sql/test/system.test.js index 30d3554ff4..7f2efa33a7 100644 --- a/run/idp-sql/test/system.test.js +++ b/run/idp-sql/test/system.test.js @@ -17,7 +17,7 @@ const assert = require('assert'); const admin = require('firebase-admin'); const got = require('got'); -const { execSync } = require('child_process'); +const {execSync} = require('child_process'); admin.initializeApp(); @@ -30,7 +30,7 @@ describe('System Tests', () => { let {SERVICE_NAME} = process.env; if (!SERVICE_NAME) { console.log('"SERVICE_NAME" env var not found. Defaulting to "idp-sql"'); - SERVICE_NAME = "idp-sql"; + SERVICE_NAME = 'idp-sql'; } const {SAMPLE_VERSION} = process.env; const PLATFORM = 'managed'; @@ -56,13 +56,14 @@ describe('System Tests', () => { let BASE_URL, ID_TOKEN; before(async () => { // Deploy service using Cloud Build - const buildCmd = `gcloud builds submit --project ${GOOGLE_CLOUD_PROJECT} ` + - `--config ./test/e2e_test_setup.yaml ` + + const buildCmd = + `gcloud builds submit --project ${GOOGLE_CLOUD_PROJECT} ` + + '--config ./test/e2e_test_setup.yaml ' + `--substitutions _SERVICE=${SERVICE_NAME},_PLATFORM=${PLATFORM},_REGION=${REGION}` + `,_DB_PASSWORD=${DB_PASSWORD},_CLOUD_SQL_CONNECTION_NAME=${CLOUD_SQL_CONNECTION_NAME}`; - if(SAMPLE_VERSION) buildCmd + `,_VERSION=${SAMPLE_VERSION}`; - if(DB_USER) buildCmd + `,_DB_USER=${DB_USER}`; - if(DB_NAME) buildCmd + `,_DB_NAME=${DB_NAME}`; + if (SAMPLE_VERSION) buildCmd + `,_VERSION=${SAMPLE_VERSION}`; + if (DB_USER) buildCmd + `,_DB_USER=${DB_USER}`; + if (DB_NAME) buildCmd + `,_DB_NAME=${DB_NAME}`; console.log('Starting Cloud Build...'); execSync(buildCmd); @@ -71,37 +72,42 @@ describe('System Tests', () => { // Retrieve URL of Cloud Run service const url = execSync( `gcloud run services describe ${SERVICE_NAME} --project=${GOOGLE_CLOUD_PROJECT} ` + - `--platform=${PLATFORM} --region=${REGION} --format='value(status.url)'`); + `--platform=${PLATFORM} --region=${REGION} --format='value(status.url)'` + ); BASE_URL = url.toString('utf-8'); if (!BASE_URL) throw Error('Cloud Run service URL not found'); // Retrieve ID token for testing const customToken = await admin.auth().createCustomToken('a-user-id'); - const response = await got(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${IDP_KEY}`, { - method: 'POST', - body: JSON.stringify({ - token: customToken, - returnSecureToken: true - }), - }); + const response = await got( + `https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${IDP_KEY}`, + { + method: 'POST', + body: JSON.stringify({ + token: customToken, + returnSecureToken: true, + }), + } + ); const tokens = JSON.parse(response.body); ID_TOKEN = tokens.idToken; if (!ID_TOKEN) throw Error('Unable to acquire an ID token.'); - }) + }); after(() => { - const cleanUpCmd = `gcloud builds submit --project ${GOOGLE_CLOUD_PROJECT} ` + - `--config ./test/e2e_test_cleanup.yaml ` + - `--substitutions _SERVICE=${SERVICE_NAME},_PLATFORM=${PLATFORM},_REGION=${REGION}` - if(SAMPLE_VERSION) cleanUpCmd + `,_VERSION=${SAMPLE_VERSION}`; + const cleanUpCmd = + `gcloud builds submit --project ${GOOGLE_CLOUD_PROJECT} ` + + '--config ./test/e2e_test_cleanup.yaml ' + + `--substitutions _SERVICE=${SERVICE_NAME},_PLATFORM=${PLATFORM},_REGION=${REGION}`; + if (SAMPLE_VERSION) cleanUpCmd + `,_VERSION=${SAMPLE_VERSION}`; execSync(cleanUpCmd); - }) + }); it('Can successfully make a request', async () => { const options = { prefixUrl: BASE_URL.trim(), - retry: 3 + retry: 3, }; const response = await got('', options); assert.strictEqual(response.statusCode, 200); @@ -113,9 +119,9 @@ describe('System Tests', () => { method: 'POST', form: {team: 'DOGS'}, headers: { - Authorization: `Bearer ${ID_TOKEN.trim()}` + Authorization: `Bearer ${ID_TOKEN.trim()}`, }, - retry: 3 + retry: 3, }; const response = await got('', options); assert.strictEqual(response.statusCode, 200); @@ -127,9 +133,9 @@ describe('System Tests', () => { method: 'POST', form: {team: 'DOGS'}, headers: { - Authorization: `Bearer iam-a-token` + Authorization: 'Bearer iam-a-token', }, - retry: 3 + retry: 3, }; let err; try { @@ -145,7 +151,7 @@ describe('System Tests', () => { prefixUrl: BASE_URL.trim(), method: 'POST', form: {team: 'DOGS'}, - retry: 3 + retry: 3, }; let err; try { @@ -155,5 +161,4 @@ describe('System Tests', () => { } assert.strictEqual(err.response.statusCode, 401); }); - }); diff --git a/run/image-processing/image.js b/run/image-processing/image.js index 614147bc86..42f0cafb47 100644 --- a/run/image-processing/image.js +++ b/run/image-processing/image.js @@ -30,7 +30,7 @@ const {BLURRED_BUCKET_NAME} = process.env; // [START run_imageproc_handler_analyze] // Blurs uploaded images that are flagged as Adult or Violence. -exports.blurOffensiveImages = async (event) => { +exports.blurOffensiveImages = async event => { // This event represents the triggering Cloud Storage object. const object = event; diff --git a/run/image-processing/package.json b/run/image-processing/package.json index d7010e859f..7086b00884 100644 --- a/run/image-processing/package.json +++ b/run/image-processing/package.json @@ -28,6 +28,6 @@ "devDependencies": { "got": "^11.5.0", "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/run/image-processing/test/app.test.js b/run/image-processing/test/app.test.js index 89a4e14cde..d15fdd6208 100644 --- a/run/image-processing/test/app.test.js +++ b/run/image-processing/test/app.test.js @@ -10,11 +10,11 @@ describe('Unit Tests', () => { }); describe('should fail', () => { - it(`on a Bad Request with an empty payload`, async () => { + it('on a Bad Request with an empty payload', async () => { await request.post('/').type('json').send('').expect(400); }); - it(`on a Bad Request with an invalid payload`, async () => { + it('on a Bad Request with an invalid payload', async () => { await request .post('/') .type('json') @@ -22,11 +22,11 @@ describe('Unit Tests', () => { .expect(400); }); - it(`on a Bad Request with an invalid mimetype`, async () => { + it('on a Bad Request with an invalid mimetype', async () => { await request.post('/').type('text').send('{message: true}').expect(400); }); - it(`if the decoded message.data is not well-formed JSON`, async () => { + it('if the decoded message.data is not well-formed JSON', async () => { await request .post('/') .type('json') @@ -45,7 +45,7 @@ describe('Unit Tests', () => { .type('json') .send({ message: { - data: Buffer.from('{ "json": "value" }').toString(`base64`), + data: Buffer.from('{ "json": "value" }').toString('base64'), }, }) .expect(400); @@ -56,7 +56,7 @@ describe('Unit Tests', () => { .type('json') .send({ message: { - data: Buffer.from('{ "name": "value" }').toString(`base64`), + data: Buffer.from('{ "name": "value" }').toString('base64'), }, }) .expect(400); @@ -67,7 +67,7 @@ describe('Unit Tests', () => { .type('json') .send({ message: { - data: Buffer.from('{ "bucket": "value" }').toString(`base64`), + data: Buffer.from('{ "bucket": "value" }').toString('base64'), }, }) .expect(400); @@ -77,15 +77,15 @@ describe('Unit Tests', () => { }); describe('Integration Tests', () => { - it(`Image analysis can proceed to Vision API scan`, async () => { + it('Image analysis can proceed to Vision API scan', async () => { await request .post('/') .type('json') .send({ message: { data: Buffer.from( - `{ "bucket": "---", "name": "does-not-exist" }` - ).toString(`base64`), + '{ "bucket": "---", "name": "does-not-exist" }' + ).toString('base64'), }, }) .expect(204); diff --git a/run/logging-manual/test/system.test.js b/run/logging-manual/test/system.test.js index 0e055e6259..de93c86fec 100644 --- a/run/logging-manual/test/system.test.js +++ b/run/logging-manual/test/system.test.js @@ -33,7 +33,7 @@ const getLogEntriesPolling = async (filter, max_attempts) => { return []; }; -const getLogEntries = async (filter) => { +const getLogEntries = async filter => { const preparedFilter = `resource.type="cloud_run_revision" ${filter}`; const entries = await logging.getEntries({ filter: preparedFilter, @@ -83,7 +83,7 @@ describe('Logging', () => { 5 )}"`; const entries = await getLogEntriesPolling(filter); - entries.forEach((entry) => { + entries.forEach(entry => { if (entry.metadata.httpRequest) { requestLog = entry; } else { diff --git a/run/markdown-preview/editor/app.js b/run/markdown-preview/editor/app.js index ab17d3e6f0..ee5375ab50 100644 --- a/run/markdown-preview/editor/app.js +++ b/run/markdown-preview/editor/app.js @@ -14,7 +14,7 @@ const express = require('express'); const handlebars = require('handlebars'); -const { readFile } = require('fs').promises; +const {readFile} = require('fs').promises; const renderRequest = require('./render.js'); const app = express(); @@ -26,15 +26,17 @@ let markdownDefault, compiledTemplate, renderedHtml; const buildRenderedHtml = async () => { try { markdownDefault = await readFile(__dirname + '/templates/markdown.md'); - compiledTemplate = handlebars.compile(await readFile(__dirname + '/templates/index.html', 'utf8')); + compiledTemplate = handlebars.compile( + await readFile(__dirname + '/templates/index.html', 'utf8') + ); renderedHtml = compiledTemplate({default: markdownDefault}); return renderedHtml; - } catch(err) { - throw Error ('Error loading template: ', err); + } catch (err) { + throw Error('Error loading template: ', err); } }; -app.get('/', async (req, res) => { +app.get('/', async (req, res) => { try { if (!renderedHtml) renderedHtml = await buildRenderedHtml(); res.status(200).send(renderedHtml); @@ -44,7 +46,7 @@ app.get('/', async (req, res) => { } }); -// The renderRequest makes a request to the Renderer service. +// The renderRequest makes a request to the Renderer service. // The request returns the Markdown text converted to HTML. // [START run_secure_request_do] app.post('/render', async (req, res) => { @@ -62,5 +64,5 @@ app.post('/render', async (req, res) => { // Exports for testing purposes. module.exports = { app, - buildRenderedHtml -}; \ No newline at end of file + buildRenderedHtml, +}; diff --git a/run/markdown-preview/editor/index.js b/run/markdown-preview/editor/index.js index 3e56daf1aa..73512995b6 100644 --- a/run/markdown-preview/editor/index.js +++ b/run/markdown-preview/editor/index.js @@ -16,6 +16,4 @@ const {app} = require('./app'); const pkg = require('./package.json'); const PORT = process.env.PORT || 8080; -app.listen(PORT, () => - console.log(`${pkg.name} listening on port ${PORT}`) -); +app.listen(PORT, () => console.log(`${pkg.name} listening on port ${PORT}`)); diff --git a/run/markdown-preview/editor/package.json b/run/markdown-preview/editor/package.json index 458afb28f8..86b59282c0 100644 --- a/run/markdown-preview/editor/package.json +++ b/run/markdown-preview/editor/package.json @@ -26,6 +26,6 @@ }, "devDependencies": { "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/run/markdown-preview/editor/render.js b/run/markdown-preview/editor/render.js index b68102c211..7fe4720378 100644 --- a/run/markdown-preview/editor/render.js +++ b/run/markdown-preview/editor/render.js @@ -22,18 +22,19 @@ let client, serviceUrl; // renderRequest creates a new HTTP request with IAM ID Token credential. // This token is automatically handled by private Cloud Run (fully managed) and Cloud Functions. -const renderRequest = async (markdown) => { - if (!process.env.EDITOR_UPSTREAM_RENDER_URL) throw Error('EDITOR_UPSTREAM_RENDER_URL needs to be set.'); +const renderRequest = async markdown => { + if (!process.env.EDITOR_UPSTREAM_RENDER_URL) + throw Error('EDITOR_UPSTREAM_RENDER_URL needs to be set.'); serviceUrl = process.env.EDITOR_UPSTREAM_RENDER_URL; // Build the request to the Renderer receiving service. - const serviceRequestOptions = { + const serviceRequestOptions = { method: 'POST', headers: { - 'Content-Type': 'text/plain' + 'Content-Type': 'text/plain', }, body: markdown, - timeout: 3000 + timeout: 3000, }; try { @@ -42,18 +43,19 @@ const renderRequest = async (markdown) => { // Fetch the client request headers and add them to the service request headers. // The client request headers include an ID token that authenticates the request. const clientHeaders = await client.getRequestHeaders(); - serviceRequestOptions.headers['Authorization'] = clientHeaders['Authorization']; - } catch(err) { + serviceRequestOptions.headers['Authorization'] = + clientHeaders['Authorization']; + } catch (err) { throw Error('could not create an identity token: ', err); - }; + } try { // serviceResponse converts the Markdown plaintext to HTML. const serviceResponse = await got(serviceUrl, serviceRequestOptions); return serviceResponse.body; - } catch (err) { + } catch (err) { throw Error('request to rendering service failed: ', err); - }; + } }; // [END run_secure_request] diff --git a/run/markdown-preview/editor/test/app.test.js b/run/markdown-preview/editor/test/app.test.js index 643d2e05d8..8a74c50856 100644 --- a/run/markdown-preview/editor/test/app.test.js +++ b/run/markdown-preview/editor/test/app.test.js @@ -20,27 +20,26 @@ const supertest = require('supertest'); describe('Editor unit tests', () => { describe('Initialize app', () => { - it('should successfully load the index page', async function () { + it('should successfully load the index page', async () => { const {app} = require(path.join(__dirname, '..', 'app')); const request = supertest(app); await request.get('/').expect(200); - }) + }); }); describe('Handlebars compiler', async () => { let template; - before( async () => { + before(async () => { const {buildRenderedHtml} = require(path.join(__dirname, '..', 'app')); template = await buildRenderedHtml(); - }) + }); it('includes HTML from the templates', () => { - let htmlString = template.includes('Markdown Editor'); + const htmlString = template.includes('Markdown Editor'); assert.equal(htmlString, true); }); }); - }); describe('Integration tests', () => { @@ -60,12 +59,22 @@ describe('Integration tests', () => { it('responds 200 OK on "POST /render" with valid JSON', async () => { // A valid type will make a request to the /render endpoint. // TODO: This test outputs a JSON parsing SyntaxError from supertest but does not fail the assert. - await request.post('/render').type('json').set('Accept', 'text/html').send({"data":"markdown"}).expect(200).expect('content-type', 'text/html; charset=utf-8'); + await request + .post('/render') + .type('json') + .set('Accept', 'text/html') + .send({data: 'markdown'}) + .expect(200) + .expect('content-type', 'text/html; charset=utf-8'); }); - + it('responds 400 Bad Request on "POST /render" without valid JSON', async () => { - // An incorrect type will not successfully make a request and will print an error in the console. - await request.post('/render').type('json').send('string: incorrect data type').expect(400); + // An incorrect type will not successfully make a request and will print an error in the console. + await request + .post('/render') + .type('json') + .send('string: incorrect data type') + .expect(400); }); }); }); diff --git a/run/markdown-preview/editor/test/system.test.js b/run/markdown-preview/editor/test/system.test.js index 23fa1c3d0b..7edb4926c6 100644 --- a/run/markdown-preview/editor/test/system.test.js +++ b/run/markdown-preview/editor/test/system.test.js @@ -27,15 +27,15 @@ describe('End-to-End Tests', () => { throw Error( '"BASE_URL" environment variable is required. For example: https://service-x8xabcdefg-uc.a.run.app' ); - }; + } it('Can successfully make a request', async () => { const options = { prefixUrl: BASE_URL.trim(), headers: { - Authorization: `Bearer ${ID_TOKEN.trim()}` + Authorization: `Bearer ${ID_TOKEN.trim()}`, }, - retry: 3 + retry: 3, }; const response = await got('', options); assert.strictEqual(response.statusCode, 200); @@ -46,18 +46,17 @@ describe('End-to-End Tests', () => { prefixUrl: BASE_URL.trim(), headers: { Authorization: `Bearer ${ID_TOKEN.trim()}`, - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }, method: 'POST', - json: { - "data": "**markdown**" + json: { + data: '**markdown**', }, - retry: 3 + retry: 3, }; const response = await got('render', options); assert.strictEqual(response.statusCode, 200); assert.strictEqual(response.body, '

markdown

\n'); }); }); - }); diff --git a/run/markdown-preview/renderer/app.js b/run/markdown-preview/renderer/app.js index 2c1e6c8f26..a984b37045 100644 --- a/run/markdown-preview/renderer/app.js +++ b/run/markdown-preview/renderer/app.js @@ -19,12 +19,12 @@ const app = express(); app.use(express.text()); app.post('/', (req, res) => { - if (typeof(req.body) !== 'string') { + if (typeof req.body !== 'string') { const msg = 'Markdown data could not be retrieved.'; console.log(msg); res.status(400).send(`Error: ${msg}`); return; - }; + } const markdown = req.body; try { // Get the Markdown text and convert it into HTML using markdown-it. @@ -33,11 +33,11 @@ app.post('/', (req, res) => { const md = new MarkdownIt(); const html = md.render(markdown); res.status(200).send(html); - } catch(err) { + } catch (err) { console.log('Error rendering Markdown: ', err); res.status(400).send(err); } -}) +}); // Export for testing purposes. module.exports = app; diff --git a/run/markdown-preview/renderer/index.js b/run/markdown-preview/renderer/index.js index 90bcfa3924..a04863db38 100644 --- a/run/markdown-preview/renderer/index.js +++ b/run/markdown-preview/renderer/index.js @@ -16,6 +16,4 @@ const app = require('./app'); const pkg = require('./package.json'); const PORT = process.env.PORT || 8080; -app.listen(PORT, () => - console.log(`${pkg.name} listening on port ${PORT}`) -); \ No newline at end of file +app.listen(PORT, () => console.log(`${pkg.name} listening on port ${PORT}`)); diff --git a/run/markdown-preview/renderer/package.json b/run/markdown-preview/renderer/package.json index a801cc42d7..202e8d5ff0 100644 --- a/run/markdown-preview/renderer/package.json +++ b/run/markdown-preview/renderer/package.json @@ -25,6 +25,6 @@ "got": "^11.5.0", "mocha": "^8.0.0", "sinon": "^9.0.2", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/run/markdown-preview/renderer/test/app.test.js b/run/markdown-preview/renderer/test/app.test.js index ee40373f41..f41033bef1 100644 --- a/run/markdown-preview/renderer/test/app.test.js +++ b/run/markdown-preview/renderer/test/app.test.js @@ -30,30 +30,50 @@ describe('Unit Tests', () => { it('should return Bad Request with an invalid type', async () => { const consoleStub = sinon.stub(console, 'log'); // Ensure that the expected error is logged. - await request.post('/').type('json').send({"json": "json"}); + await request.post('/').type('json').send({json: 'json'}); const message = console.log.getCall(0).args[0]; - assert.equal(message, "Markdown data could not be retrieved."); + assert.equal(message, 'Markdown data could not be retrieved.'); consoleStub.restore(); }); it('should succeed with a valid request', async () => { - const markdown = "**markdown text**"; - const response = await request.post('/').type('text').send(markdown).expect(200); + const markdown = '**markdown text**'; + const response = await request + .post('/') + .type('text') + .send(markdown) + .expect(200); const body = response.text; - assert.equal(body, "

markdown text

\n") + assert.equal(body, '

markdown text

\n'); }); it('should succeed with a request that includes xss', async () => { - let markdown = ""; - await request.post('/').type('text').send(markdown).expect(200).then(res => { - const body = res.text; - assert.deepStrictEqual(body, "

<script>script</script>

\n"); - }); - markdown = 'Google' - await request.post('/').type('text').send(markdown).expect(200).then(res => { - const body = res.text; - assert.deepStrictEqual(body, "

<a onblur="alert(secret)" href="http://www.google.com">Google</a>

\n"); - }); - }) -}) - + let markdown = ''; + await request + .post('/') + .type('text') + .send(markdown) + .expect(200) + .then(res => { + const body = res.text; + assert.deepStrictEqual( + body, + '

<script>script</script>

\n' + ); + }); + markdown = + 'Google'; + await request + .post('/') + .type('text') + .send(markdown) + .expect(200) + .then(res => { + const body = res.text; + assert.deepStrictEqual( + body, + '

<a onblur="alert(secret)" href="http://www.google.com">Google</a>

\n' + ); + }); + }); +}); diff --git a/run/pubsub/app.js b/run/pubsub/app.js index 2cb52082bf..d8dfee00c0 100644 --- a/run/pubsub/app.js +++ b/run/pubsub/app.js @@ -36,5 +36,3 @@ app.post('/', (req, res) => { module.exports = app; // [END run_pubsub_handler] - - diff --git a/run/pubsub/package.json b/run/pubsub/package.json index 5590e574d9..0ce7daf25c 100644 --- a/run/pubsub/package.json +++ b/run/pubsub/package.json @@ -26,7 +26,7 @@ "got": "^11.5.0", "mocha": "^8.0.0", "sinon": "^9.0.0", - "supertest": "^5.0.0", + "supertest": "^6.0.0", "uuid": "^8.0.0" } } diff --git a/run/pubsub/test/app.test.js b/run/pubsub/test/app.test.js index 7d11777053..ca7c9a4319 100644 --- a/run/pubsub/test/app.test.js +++ b/run/pubsub/test/app.test.js @@ -33,11 +33,11 @@ describe('Unit Tests', () => { }); describe('should fail', () => { - it(`on a Bad Request with an empty payload`, async () => { + it('on a Bad Request with an empty payload', async () => { await request.post('/').type('json').send('').expect(400); }); - it(`on a Bad Request with an invalid payload`, async () => { + it('on a Bad Request with an invalid payload', async () => { await request .post('/') .type('json') @@ -45,7 +45,7 @@ describe('Unit Tests', () => { .expect(400); }); - it(`on a Bad Request with an invalid mimetype`, async () => { + it('on a Bad Request with an invalid mimetype', async () => { await request.post('/').type('text').send('{message: true}').expect(400); }); }); @@ -60,7 +60,7 @@ describe('Unit Tests', () => { console.log.restore(); }); - it(`with a minimally valid Pub/Sub Message`, async () => { + it('with a minimally valid Pub/Sub Message', async () => { await request .post('/') .type('json') @@ -69,9 +69,9 @@ describe('Unit Tests', () => { .expect(() => assert.ok(console.log.calledWith('Hello World!'))); }); - it(`with a populated Pub/Sub Message`, async () => { + it('with a populated Pub/Sub Message', async () => { const name = uuid.v4(); - const data = Buffer.from(name).toString(`base64`); + const data = Buffer.from(name).toString('base64'); await request .post('/') diff --git a/run/system-package/app.js b/run/system-package/app.js index eb91d42236..4b0c6eed6c 100644 --- a/run/system-package/app.js +++ b/run/system-package/app.js @@ -44,7 +44,7 @@ app.get('/diagram.png', (req, res) => { // [START run_system_package_exec] // Generate a diagram based on a graphviz DOT diagram description. -const createDiagram = (dot) => { +const createDiagram = dot => { if (!dot) { throw new Error('syntax: no graphviz definition provided'); } diff --git a/run/system-package/package.json b/run/system-package/package.json index 5fa72feb72..a4011fe51e 100644 --- a/run/system-package/package.json +++ b/run/system-package/package.json @@ -15,6 +15,6 @@ "devDependencies": { "got": "^11.5.0", "mocha": "^8.0.0", - "supertest": "^5.0.0" + "supertest": "^6.0.0" } } diff --git a/run/system-package/test/app.test.js b/run/system-package/test/app.test.js index fa82ccb021..566860e608 100644 --- a/run/system-package/test/app.test.js +++ b/run/system-package/test/app.test.js @@ -24,41 +24,41 @@ describe('Unit Tests', () => { describe('should fail', () => { const errorContentType = 'text/html; charset=utf-8'; - it(`should fail on a Bad Request with an empty query string`, async () => { + it('should fail on a Bad Request with an empty query string', async () => { await request .get('/diagram.png') .type('text') .expect(400) .expect('Content-Type', errorContentType) - .expect((res) => { + .expect(res => { if (res.headers['cache-control']) { throw new Error('Found cache header on uncached response'); } }); }); - it(`should fail on a Bad Request with an empty dot parameter`, async () => { + it('should fail on a Bad Request with an empty dot parameter', async () => { await request .get('/diagram.png') .type('text') .query({dot: ''}) .expect(400) .expect('Content-Type', errorContentType) - .expect((res) => { + .expect(res => { if (res.headers['cache-control']) { throw new Error('Found cache header on uncached response'); } }); }); - it(`should fail on a Bad Request with an invalid payload`, async () => { + it('should fail on a Bad Request with an invalid payload', async () => { await request - .get(`/diagram.png`) + .get('/diagram.png') .type('text') - .query({dot: `digraph`}) + .query({dot: 'digraph'}) .expect(400) .expect('Content-Type', errorContentType) - .expect((res) => { + .expect(res => { if (res.headers['cache-control']) { throw new Error('Found cache header on uncached response'); } @@ -67,11 +67,11 @@ describe('Unit Tests', () => { }); describe('should succeed', () => { - it(`should succeed with a valid DOT description`, async () => { + it('should succeed with a valid DOT description', async () => { await request - .get(`/diagram.png`) - .type(`text`) - .query({dot: `digraph G { A -> {B, C, D} -> {F} }`}) + .get('/diagram.png') + .type('text') + .query({dot: 'digraph G { A -> {B, C, D} -> {F} }'}) .expect(200) .expect('Content-Type', 'image/png') .expect('Cache-Control', 'public, max-age=86400'); diff --git a/storage-transfer/package.json b/storage-transfer/package.json index 0a4767d7e8..1c5bf85171 100644 --- a/storage-transfer/package.json +++ b/storage-transfer/package.json @@ -17,7 +17,7 @@ "test": "npm run unit-test && npm run system-test" }, "dependencies": { - "googleapis": "^61.0.0", + "googleapis": "^62.0.0", "moment": "^2.24.0", "yargs": "^16.0.0" }, diff --git a/storage-transfer/system-test/transfer.test.js b/storage-transfer/system-test/transfer.test.js index 21634d8a84..ee8ef3a0bd 100644 --- a/storage-transfer/system-test/transfer.test.js +++ b/storage-transfer/system-test/transfer.test.js @@ -33,8 +33,8 @@ const description = 'this is a test'; const status = 'DISABLED'; const stubConsole = function stubConsole() { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; const restoreConsole = function restoreConsole() { @@ -45,11 +45,11 @@ const restoreConsole = function restoreConsole() { before(async () => { assert( process.env.GOOGLE_CLOUD_PROJECT, - `Must set GOOGLE_CLOUD_PROJECT environment variable!` + 'Must set GOOGLE_CLOUD_PROJECT environment variable!' ); assert( process.env.GOOGLE_APPLICATION_CREDENTIALS, - `Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!` + 'Must set GOOGLE_APPLICATION_CREDENTIALS environment variable!' ); stubConsole(); @@ -89,7 +89,7 @@ after(() => { } catch (err) {} // ignore error }); -it('should create a storage transfer job', (done) => { +it('should create a storage transfer job', done => { const options = { srcBucket: firstBucketName, destBucket: secondBucketName, @@ -113,7 +113,7 @@ it('should create a storage transfer job', (done) => { }); }); -it('should get a transferJob', (done) => { +it('should get a transferJob', done => { program.getTransferJob(jobName, (err, transferJob) => { assert.ifError(err); assert.strictEqual(transferJob.name, jobName); @@ -127,7 +127,7 @@ it('should get a transferJob', (done) => { }); }); -it('should update a transferJob', (done) => { +it('should update a transferJob', done => { const options = { job: jobName, field: 'status', @@ -147,21 +147,19 @@ it('should update a transferJob', (done) => { }); }); -it('should list transferJobs', (done) => { +it('should list transferJobs', done => { program.listTransferJobs((err, transferJobs) => { assert.ifError(err); assert.strictEqual( - transferJobs.some((transferJob) => transferJob.name === jobName), + transferJobs.some(transferJob => transferJob.name === jobName), true ); assert.strictEqual( - transferJobs.some( - (transferJob) => transferJob.description === description - ), + transferJobs.some(transferJob => transferJob.description === description), true ); assert.strictEqual( - transferJobs.some((transferJob) => transferJob.status === status), + transferJobs.some(transferJob => transferJob.status === status), true ); assert.strictEqual( @@ -172,7 +170,7 @@ it('should list transferJobs', (done) => { }); }); -it('should list transferOperations', (done) => { +it('should list transferOperations', done => { program.listTransferOperations(jobName, (err, operations) => { assert.ifError(err); assert.strictEqual(Array.isArray(operations), true); diff --git a/storage-transfer/test/transfer.test.js b/storage-transfer/test/transfer.test.js index 3cee6a918b..31b406a682 100644 --- a/storage-transfer/test/transfer.test.js +++ b/storage-transfer/test/transfer.test.js @@ -75,8 +75,8 @@ const getSample = () => { }; }; const stubConsole = function () { - sinon.stub(console, `error`); - sinon.stub(console, `log`); + sinon.stub(console, 'error'); + sinon.stub(console, 'log'); }; //Restore console diff --git a/storage-transfer/transfer.js b/storage-transfer/transfer.js index d8c97f0b41..92ffe10d69 100644 --- a/storage-transfer/transfer.js +++ b/storage-transfer/transfer.js @@ -24,9 +24,9 @@ const storagetransfer = google.storagetransfer('v1'); // [END setup] // [START auth] -const auth = async (callback) => { +const auth = async callback => { const authClient = await google.auth.getClient({ - scopes: ['https://www.googleapis.com/auth/cloud-platform'] + scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); callback(authClient); @@ -49,7 +49,7 @@ const createTransferJob = (options, callback) => { const startDate = moment(options.date, 'YYYY/MM/DD'); const transferTime = moment(options.time, 'HH:mm'); - auth((authClient) => { + auth(authClient => { const transferJob = { projectId: process.env.GOOGLE_CLOUD_PROJECT, status: 'ENABLED', @@ -107,7 +107,7 @@ const createTransferJob = (options, callback) => { * @param {function} callback The callback function. */ const getTransferJob = (jobName, callback) => { - auth((authClient) => { + auth(authClient => { storagetransfer.transferJobs.get( { auth: authClient, @@ -139,7 +139,7 @@ const getTransferJob = (jobName, callback) => { * @param {function} callback The callback function. */ const updateTransferJob = (options, callback) => { - auth((authClient) => { + auth(authClient => { const patchRequest = { projectId: process.env.GOOGLE_CLOUD_PROJECT, transferJob: { @@ -182,8 +182,8 @@ const updateTransferJob = (options, callback) => { * * @param {function} callback The callback function. */ -const listTransferJobs = (callback) => { - auth((authClient) => { +const listTransferJobs = callback => { + auth(authClient => { storagetransfer.transferJobs.list( { auth: authClient, @@ -212,7 +212,7 @@ const listTransferJobs = (callback) => { * @param {function} callback The callback function. */ const listTransferOperations = (jobName, callback) => { - auth((authClient) => { + auth(authClient => { const filter = { project_id: process.env.GOOGLE_CLOUD_PROJECT, }; @@ -250,7 +250,7 @@ const listTransferOperations = (jobName, callback) => { * @param {function} callback The callback function. */ const getTransferOperation = (transferOperationName, callback) => { - auth((authClient) => { + auth(authClient => { storagetransfer.transferOperations.get( { name: transferOperationName, @@ -278,13 +278,13 @@ const getTransferOperation = (transferOperationName, callback) => { * @param {function} callback The callback function. */ const pauseTransferOperation = (transferOperationName, callback) => { - auth((authClient) => { + auth(authClient => { storagetransfer.transferOperations.pause( { name: transferOperationName, auth: authClient, }, - (err) => { + err => { if (err) { return callback(err); } @@ -305,13 +305,13 @@ const pauseTransferOperation = (transferOperationName, callback) => { * @param {function} callback The callback function. */ const resumeTransferOperation = (transferOperationName, callback) => { - auth((authClient) => { + auth(authClient => { storagetransfer.transferOperations.resume( { name: transferOperationName, auth: authClient, }, - (err) => { + err => { if (err) { return callback(err); } @@ -337,7 +337,7 @@ const program = (module.exports = { getTransferOperation: getTransferOperation, pauseTransferOperation: pauseTransferOperation, resumeTransferOperation: resumeTransferOperation, - main: (args) => { + main: args => { // Run the command-line program cli.help().strict().parse(args).argv; // eslint-disable-line }, @@ -348,14 +348,14 @@ cli .command( 'jobs [args]', 'Run a job command.', - (yargs) => { + yargs => { yargs .demand(2) .command( 'create