From ad9bb7d7180e56bd1a86ed838ea46bc3ce3a1b13 Mon Sep 17 00:00:00 2001 From: Thomas Bouldin Date: Tue, 12 Dec 2017 12:06:18 -0800 Subject: [PATCH 01/16] Add eslint files; still need to add an npm script & fix errors --- assistant-say-number/functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ bigquery-import/functions/.eslintrc.json | 125 ++++++++++++++++++ child-count/functions/.eslintrc.json | 125 ++++++++++++++++++ convert-images/functions/.eslintrc.json | 125 ++++++++++++++++++ coupon-on-purchase/functions/.eslintrc.json | 125 ++++++++++++++++++ .../email-notifier/functions/.eslintrc.json | 125 ++++++++++++++++++ .../jira-issue/functions/.eslintrc.json | 125 ++++++++++++++++++ .../slack-notifier/functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ developer-motivator/functions/.eslintrc.json | 125 ++++++++++++++++++ email-confirmation/functions/.eslintrc.json | 125 ++++++++++++++++++ es2017-transpile/functions/.eslintrc.json | 125 ++++++++++++++++++ exif-images/functions/.eslintrc.json | 125 ++++++++++++++++++ fcm-notifications/functions/.eslintrc.json | 125 ++++++++++++++++++ ffmpeg-convert-audio/functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ fulltext-search/functions/.eslintrc.json | 125 ++++++++++++++++++ generate-thumbnail/functions/.eslintrc.json | 125 ++++++++++++++++++ github-to-slack/functions/.eslintrc.json | 125 ++++++++++++++++++ google-sheet-sync/functions/.eslintrc.json | 125 ++++++++++++++++++ image-maker/functions/.eslintrc.json | 125 ++++++++++++++++++ image-sharp/functions/.eslintrc.json | 125 ++++++++++++++++++ instagram-auth/functions/.eslintrc.json | 125 ++++++++++++++++++ isomorphic-react-app/functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ limit-children/functions/.eslintrc.json | 125 ++++++++++++++++++ line-auth/functions/.eslintrc.json | 125 ++++++++++++++++++ linkedin-auth/functions/.eslintrc.json | 125 ++++++++++++++++++ message-translation/functions/.eslintrc.json | 125 ++++++++++++++++++ minimal-webhook/functions/.eslintrc.json | 125 ++++++++++++++++++ moderate-images/functions/.eslintrc.json | 125 ++++++++++++++++++ .../src/functions/.eslintrc.json | 125 ++++++++++++++++++ presence-firestore/functions/.eslintrc.json | 125 ++++++++++++++++++ quickstarts/big-ben/functions/.eslintrc.json | 125 ++++++++++++++++++ .../email-users/functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ .../thumbnails/functions/.eslintrc.json | 125 ++++++++++++++++++ .../time-server/functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ .../uppercase/functions/.eslintrc.json | 125 ++++++++++++++++++ spotify-auth/functions/.eslintrc.json | 125 ++++++++++++++++++ stripe/functions/.eslintrc.json | 125 ++++++++++++++++++ survey-app-update/functions/.eslintrc.json | 125 ++++++++++++++++++ template-handlebars/functions/.eslintrc.json | 125 ++++++++++++++++++ text-moderation/functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ url-shortener/functions/.eslintrc.json | 125 ++++++++++++++++++ .../functions/.eslintrc.json | 125 ++++++++++++++++++ 51 files changed, 6375 insertions(+) create mode 100644 assistant-say-number/functions/.eslintrc.json create mode 100644 authenticated-json-api/functions/.eslintrc.json create mode 100644 authorized-https-endpoint/functions/.eslintrc.json create mode 100644 bigquery-import/functions/.eslintrc.json create mode 100644 child-count/functions/.eslintrc.json create mode 100644 convert-images/functions/.eslintrc.json create mode 100644 coupon-on-purchase/functions/.eslintrc.json create mode 100644 crashlytics-integration/email-notifier/functions/.eslintrc.json create mode 100644 crashlytics-integration/jira-issue/functions/.eslintrc.json create mode 100644 crashlytics-integration/slack-notifier/functions/.eslintrc.json create mode 100644 delete-old-child-nodes/functions/.eslintrc.json create mode 100644 delete-unused-accounts-cron/functions/.eslintrc.json create mode 100644 developer-motivator/functions/.eslintrc.json create mode 100644 email-confirmation/functions/.eslintrc.json create mode 100644 es2017-transpile/functions/.eslintrc.json create mode 100644 exif-images/functions/.eslintrc.json create mode 100644 fcm-notifications/functions/.eslintrc.json create mode 100644 ffmpeg-convert-audio/functions/.eslintrc.json create mode 100644 fulltext-search-firestore/functions/.eslintrc.json create mode 100644 fulltext-search/functions/.eslintrc.json create mode 100644 generate-thumbnail/functions/.eslintrc.json create mode 100644 github-to-slack/functions/.eslintrc.json create mode 100644 google-sheet-sync/functions/.eslintrc.json create mode 100644 image-maker/functions/.eslintrc.json create mode 100644 image-sharp/functions/.eslintrc.json create mode 100644 instagram-auth/functions/.eslintrc.json create mode 100644 isomorphic-react-app/functions/.eslintrc.json create mode 100644 lastmodified-tracking/functions/.eslintrc.json create mode 100644 limit-children/functions/.eslintrc.json create mode 100644 line-auth/functions/.eslintrc.json create mode 100644 linkedin-auth/functions/.eslintrc.json create mode 100644 message-translation/functions/.eslintrc.json create mode 100644 minimal-webhook/functions/.eslintrc.json create mode 100644 moderate-images/functions/.eslintrc.json create mode 100644 nextjs-with-firebase-hosting/src/functions/.eslintrc.json create mode 100644 presence-firestore/functions/.eslintrc.json create mode 100644 quickstarts/big-ben/functions/.eslintrc.json create mode 100644 quickstarts/email-users/functions/.eslintrc.json create mode 100644 quickstarts/pubsub-helloworld/functions/.eslintrc.json create mode 100644 quickstarts/thumbnails/functions/.eslintrc.json create mode 100644 quickstarts/time-server/functions/.eslintrc.json create mode 100644 quickstarts/uppercase-firestore/functions/.eslintrc.json create mode 100644 quickstarts/uppercase/functions/.eslintrc.json create mode 100644 spotify-auth/functions/.eslintrc.json create mode 100644 stripe/functions/.eslintrc.json create mode 100644 survey-app-update/functions/.eslintrc.json create mode 100644 template-handlebars/functions/.eslintrc.json create mode 100644 text-moderation/functions/.eslintrc.json create mode 100644 typescript-getting-started/functions/.eslintrc.json create mode 100644 url-shortener/functions/.eslintrc.json create mode 100644 username-password-auth/functions/.eslintrc.json diff --git a/assistant-say-number/functions/.eslintrc.json b/assistant-say-number/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/assistant-say-number/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/authenticated-json-api/functions/.eslintrc.json b/authenticated-json-api/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/authenticated-json-api/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/authorized-https-endpoint/functions/.eslintrc.json b/authorized-https-endpoint/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/authorized-https-endpoint/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/bigquery-import/functions/.eslintrc.json b/bigquery-import/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/bigquery-import/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/child-count/functions/.eslintrc.json b/child-count/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/child-count/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/convert-images/functions/.eslintrc.json b/convert-images/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/convert-images/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/coupon-on-purchase/functions/.eslintrc.json b/coupon-on-purchase/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/coupon-on-purchase/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/crashlytics-integration/email-notifier/functions/.eslintrc.json b/crashlytics-integration/email-notifier/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/crashlytics-integration/email-notifier/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/crashlytics-integration/jira-issue/functions/.eslintrc.json b/crashlytics-integration/jira-issue/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/crashlytics-integration/jira-issue/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/crashlytics-integration/slack-notifier/functions/.eslintrc.json b/crashlytics-integration/slack-notifier/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/crashlytics-integration/slack-notifier/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/delete-old-child-nodes/functions/.eslintrc.json b/delete-old-child-nodes/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/delete-old-child-nodes/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/delete-unused-accounts-cron/functions/.eslintrc.json b/delete-unused-accounts-cron/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/delete-unused-accounts-cron/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/developer-motivator/functions/.eslintrc.json b/developer-motivator/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/developer-motivator/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/email-confirmation/functions/.eslintrc.json b/email-confirmation/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/email-confirmation/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/es2017-transpile/functions/.eslintrc.json b/es2017-transpile/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/es2017-transpile/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/exif-images/functions/.eslintrc.json b/exif-images/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/exif-images/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/fcm-notifications/functions/.eslintrc.json b/fcm-notifications/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/fcm-notifications/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/ffmpeg-convert-audio/functions/.eslintrc.json b/ffmpeg-convert-audio/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/ffmpeg-convert-audio/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/fulltext-search-firestore/functions/.eslintrc.json b/fulltext-search-firestore/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/fulltext-search-firestore/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/fulltext-search/functions/.eslintrc.json b/fulltext-search/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/fulltext-search/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/generate-thumbnail/functions/.eslintrc.json b/generate-thumbnail/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/generate-thumbnail/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/github-to-slack/functions/.eslintrc.json b/github-to-slack/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/github-to-slack/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/google-sheet-sync/functions/.eslintrc.json b/google-sheet-sync/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/google-sheet-sync/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/image-maker/functions/.eslintrc.json b/image-maker/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/image-maker/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/image-sharp/functions/.eslintrc.json b/image-sharp/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/image-sharp/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/instagram-auth/functions/.eslintrc.json b/instagram-auth/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/instagram-auth/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/isomorphic-react-app/functions/.eslintrc.json b/isomorphic-react-app/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/isomorphic-react-app/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/lastmodified-tracking/functions/.eslintrc.json b/lastmodified-tracking/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/lastmodified-tracking/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/limit-children/functions/.eslintrc.json b/limit-children/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/limit-children/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/line-auth/functions/.eslintrc.json b/line-auth/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/line-auth/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/linkedin-auth/functions/.eslintrc.json b/linkedin-auth/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/linkedin-auth/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/message-translation/functions/.eslintrc.json b/message-translation/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/message-translation/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/minimal-webhook/functions/.eslintrc.json b/minimal-webhook/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/minimal-webhook/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/moderate-images/functions/.eslintrc.json b/moderate-images/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/moderate-images/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/nextjs-with-firebase-hosting/src/functions/.eslintrc.json b/nextjs-with-firebase-hosting/src/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/nextjs-with-firebase-hosting/src/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/presence-firestore/functions/.eslintrc.json b/presence-firestore/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/presence-firestore/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/quickstarts/big-ben/functions/.eslintrc.json b/quickstarts/big-ben/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/quickstarts/big-ben/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/quickstarts/email-users/functions/.eslintrc.json b/quickstarts/email-users/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/quickstarts/email-users/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/quickstarts/pubsub-helloworld/functions/.eslintrc.json b/quickstarts/pubsub-helloworld/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/quickstarts/pubsub-helloworld/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/quickstarts/thumbnails/functions/.eslintrc.json b/quickstarts/thumbnails/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/quickstarts/thumbnails/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/quickstarts/time-server/functions/.eslintrc.json b/quickstarts/time-server/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/quickstarts/time-server/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/quickstarts/uppercase-firestore/functions/.eslintrc.json b/quickstarts/uppercase-firestore/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/quickstarts/uppercase-firestore/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/quickstarts/uppercase/functions/.eslintrc.json b/quickstarts/uppercase/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/quickstarts/uppercase/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/spotify-auth/functions/.eslintrc.json b/spotify-auth/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/spotify-auth/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/stripe/functions/.eslintrc.json b/stripe/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/stripe/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/survey-app-update/functions/.eslintrc.json b/survey-app-update/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/survey-app-update/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/template-handlebars/functions/.eslintrc.json b/template-handlebars/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/template-handlebars/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/text-moderation/functions/.eslintrc.json b/text-moderation/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/text-moderation/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/typescript-getting-started/functions/.eslintrc.json b/typescript-getting-started/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/typescript-getting-started/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/url-shortener/functions/.eslintrc.json b/url-shortener/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/url-shortener/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} diff --git a/username-password-auth/functions/.eslintrc.json b/username-password-auth/functions/.eslintrc.json new file mode 100644 index 0000000000..eb4c93169b --- /dev/null +++ b/username-password-auth/functions/.eslintrc.json @@ -0,0 +1,125 @@ +{ + "parserOptions": { + // Required for certain syntax usages + "ecmaVersion": 6 + }, + "plugins": [ + "promise" + ], + "extends": "eslint:recommended", + "rules": { + // Removed rule "disallow the use of console" from recommended eslint rules + "no-console": "off", + + // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules + "no-regex-spaces": "off", + + // Removed rule "disallow the use of debugger" from recommended eslint rules + "no-debugger": "off", + + // Removed rule "disallow unused variables" from recommended eslint rules + "no-unused-vars": "off", + + // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules + "no-mixed-spaces-and-tabs": "off", + + // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules + "no-undef": "off", + + // Warn against template literal placeholder syntax in regular strings + "no-template-curly-in-string": 1, + + // Warn if return statements do not either always or never specify values + "consistent-return": 1, + + // Warn if no return statements in callbacks of array methods + "array-callback-return": 1, + + // Requre the use of === and !== + "eqeqeq": 2, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + // Disallow the use of alert, confirm, and prompt + "no-alert": 2, + + // Disallow the use of arguments.caller or arguments.callee + "no-caller": 2, + + // Disallow null comparisons without type-checking operators + "no-eq-null": 2, + + // Disallow the use of eval() + "no-eval": 2, + + // Warn against extending native types + "no-extend-native": 1, + + // Warn against unnecessary calls to .bind() + "no-extra-bind": 1, + + // Warn against unnecessary labels + "no-extra-label": 1, + + // Disallow leading or trailing decimal points in numeric literals + "no-floating-decimal": 2, + + // Warn against shorthand type conversions + "no-implicit-coercion": 1, + + // Warn against function declarations and expressions inside loop statements + "no-loop-func": 1, + + // Disallow new operators with the Function object + "no-new-func": 2, + + // Warn against new operators with the String, Number, and Boolean objects + "no-new-wrappers": 1, + + // Disallow throwing literals as exceptions + "no-throw-literal": 2, + + // Require using Error objects as Promise rejection reasons + "prefer-promise-reject-errors": 2, + + // Enforce “for” loop update clause moving the counter in the right direction + "for-direction": 2, + + // Enforce return statements in getters + "getter-return": 2, + + // Disallow await inside of loops + "no-await-in-loop": 2, + + // Disallow comparing against -0 + "no-compare-neg-zero": 2, + + // Warn against catch clause parameters from shadowing variables in the outer scope + "no-catch-shadow": 1, + + // Disallow identifiers from shadowing restricted names + "no-shadow-restricted-names": 2, + + // Enforce return statements in callbacks of array methods + "callback-return": 2, + + // Require error handling in callbacks + "handle-callback-err": 2, + + // Warn against string concatenation with __dirname and __filename + "no-path-concat": 1, + + // Prefer using arrow functions for callbacks + "prefer-arrow-callback": 1, + + // Return inside each then() to create readable and reusable Promise chains. + "promise/always-return": 2, + + //Enforces the use of catch() on un-returned promises + "promise/catch-or-return": 2, + + // Warn against nested then() or catch() statements + "promise/no-nesting": 1 + } +} From 40299c3463cfa893ea35236a5934a3077acebf11 Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Thu, 4 Jan 2018 14:03:06 -0800 Subject: [PATCH 02/16] fixed eslint errors first pass --- .DS_Store | Bin 0 -> 6148 bytes authenticated-json-api/functions/index.js | 26 ++-- authorized-https-endpoint/functions/index.js | 2 +- child-count/functions/index.js | 15 ++- convert-images/functions/index.js | 27 +++-- coupon-on-purchase/functions/index.js | 16 +-- .../email-notifier/functions/index.js | 6 +- .../jira-issue/functions/index.js | 8 +- .../slack-notifier/functions/index.js | 4 +- .../functions/index.js | 72 +++++------ eslint_results.txt | 113 ++++++++++++++++++ exif-images/functions/index.js | 45 ++++--- fcm-notifications/functions/index.js | 20 ++-- ffmpeg-convert-audio/functions/index.js | 57 ++++----- fulltext-search-firestore/functions/index.js | 56 ++++----- github-to-slack/functions/index.js | 28 ++--- google-sheet-sync/functions/index.js | 22 ++-- image-sharp/functions/index.js | 32 ++--- instagram-auth/functions/index.js | 48 ++++---- isomorphic-react-app/functions/index.js | 22 ++-- limit-children/functions/index.js | 7 +- line-auth/functions/index.js | 49 ++++---- linkedin-auth/functions/index.js | 40 +++---- message-translation/functions/index.js | 28 ++--- minimal-webhook/functions/index.js | 8 +- moderate-images/functions/index.js | 25 ++-- paypal/functions/index.js | 56 ++++----- presence-firestore/functions/index.js | 4 +- quickstarts/email-users/functions/index.js | 18 +-- quickstarts/thumbnails/functions/index.js | 12 +- .../uppercase-firestore/functions/index.js | 8 +- quickstarts/uppercase/functions/index.js | 8 +- spotify-auth/functions/index.js | 31 ++--- stripe/functions/index.js | 34 +++--- survey-app-update/functions/index.js | 3 +- template-handlebars/functions/firebaseUser.js | 25 ++-- template-handlebars/functions/index.js | 2 +- text-moderation/functions/index.js | 17 +-- url-shortener/functions/index.js | 12 +- username-password-auth/functions/index.js | 19 +-- 40 files changed, 575 insertions(+), 450 deletions(-) create mode 100644 .DS_Store create mode 100644 eslint_results.txt diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..899c45fa6d2b3955d39163984f5663b4b7794b88 GIT binary patch literal 6148 zcmeHK%Sr=55Ukc5B3^RLaelyqe=vmj1^EF5LlnXaVm$B3@AA{EejtWTE`k@ShVGi_ z>6&Hhu)PhyR)@!1U;$uGcf^N>srkA4#4ajhL^|)d!2=F>!_)g_Qhhq%+$-$yi~-x9 z{MTXsGVJo^(^O@pfE17dQa}nwfnO-#y_Yt>PE?cvQa}oPE8yRUMtAImV`6+d7-9q< z&X^A4I%WxC^8~RMj)~0BEUCn#T8$W%bmm*t^};bR>986;te$K&p;$bf_qQmA^+ZJ} zAO(&UxXkUs`~MyN%=~{$(oPCUfq$id&DNXsimz0?b@FoFYa9KZ?lqruH?D)i5bc;4 i?U);H$IB?ny5?)1_rftT=*$P5sGkAXMJ5IQT7fT!ixnUM literal 0 HcmV?d00001 diff --git a/authenticated-json-api/functions/index.js b/authenticated-json-api/functions/index.js index 7e9f4e5bd7..155f0ee035 100644 --- a/authenticated-json-api/functions/index.js +++ b/authenticated-json-api/functions/index.js @@ -14,17 +14,17 @@ * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const admin = require('firebase-admin'); -const Language = require('@google-cloud/language'); -const express = require('express'); + const functions = require('firebase-functions'); + const admin = require('firebase-admin'); + const Language = require('@google-cloud/language'); + const express = require('express'); -const app = express(); -const language = new Language({projectId: process.env.GCLOUD_PROJECT}); + const app = express(); + const language = new Language({projectId: process.env.GCLOUD_PROJECT}); -admin.initializeApp(functions.config().firebase); + admin.initializeApp(functions.config().firebase); // Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header. // The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this: @@ -38,7 +38,7 @@ const authenticate = (req, res, next) => { const idToken = req.headers.authorization.split('Bearer ')[1]; admin.auth().verifyIdToken(idToken).then(decodedIdToken => { req.user = decodedIdToken; - next(); + return next(); }).catch(error => { res.status(403).send('Unauthorized'); }); @@ -60,7 +60,7 @@ app.post('/messages', (req, res) => { return snapshot.ref.once('value'); }).then(snapshot => { const val = snapshot.val(); - res.status(201).json({message: val.message, category: val.category}); + return res.status(201).json({message: val.message, category: val.category}); }).catch(error => { console.log('Error detecting sentiment or saving message', error.message); res.sendStatus(500); @@ -80,7 +80,7 @@ app.get('/messages', (req, res) => { return res.status(404).json({errorCode: 404, errorMessage: `category '${category}' not found`}); } - query.once('value').then(snapshot => { + return query.once('value').then(snapshot => { var messages = []; snapshot.forEach(childSnapshot => { messages.push({key: childSnapshot.key, message: childSnapshot.val().message}); @@ -101,9 +101,9 @@ app.get('/message/:messageId', (req, res) => { if (snapshot.val() !== null) { // Cache details in the browser for 5 minutes res.set('Cache-Control', 'private, max-age=300'); - res.status(200).json(snapshot.val()); + return res.status(200).json(snapshot.val()); } else { - res.status(404).json({errorCode: 404, errorMessage: `message '${messageId}' not found`}); + return res.status(404).json({errorCode: 404, errorMessage: `message '${messageId}' not found`}); } }).catch(error => { console.log('Error getting message details', messageId, error.message); diff --git a/authorized-https-endpoint/functions/index.js b/authorized-https-endpoint/functions/index.js index e2d0cbaebf..d21be63035 100644 --- a/authorized-https-endpoint/functions/index.js +++ b/authorized-https-endpoint/functions/index.js @@ -53,7 +53,7 @@ const validateFirebaseIdToken = (req, res, next) => { admin.auth().verifyIdToken(idToken).then(decodedIdToken => { console.log('ID Token correctly decoded', decodedIdToken); req.user = decodedIdToken; - next(); + return next(); }).catch(error => { console.error('Error while verifying Firebase ID token:', error); res.status(403).send('Unauthorized'); diff --git a/child-count/functions/index.js b/child-count/functions/index.js index 62d96cc4de..2b95c4a4b5 100644 --- a/child-count/functions/index.js +++ b/child-count/functions/index.js @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const admin = require('firebase-admin'); -admin.initializeApp(functions.config().firebase); + const functions = require('firebase-functions'); + const admin = require('firebase-admin'); + admin.initializeApp(functions.config().firebase); // Keeps track of the length of the 'likes' child list in a separate property. exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(event => { @@ -33,8 +33,10 @@ exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid} else if (!event.data.exists() && event.data.previous.exists()) { return (current || 0) - 1; } + // What to do in other cases? + return null; }).then(() => { - console.log('Counter updated.'); + return console.log('Counter updated.'); }); }); @@ -47,6 +49,7 @@ exports.recountlikes = functions.database.ref('/posts/{postid}/likes_count').onW // Return the promise from counterRef.set() so our function // waits for this async event to complete before it exits. return collectionRef.once('value') - .then(messagesData => counterRef.set(messagesData.numChildren())); + .then(messagesData => counterRef.set(messagesData.numChildren())); } + return null; }); diff --git a/convert-images/functions/index.js b/convert-images/functions/index.js index 0e16f9e875..86e3d156e3 100644 --- a/convert-images/functions/index.js +++ b/convert-images/functions/index.js @@ -13,15 +13,15 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const mkdirp = require('mkdirp-promise'); -const gcs = require('@google-cloud/storage')(); -const spawn = require('child-process-promise').spawn; -const path = require('path'); -const os = require('os'); -const fs = require('fs'); + const functions = require('firebase-functions'); + const mkdirp = require('mkdirp-promise'); + const gcs = require('@google-cloud/storage')(); + const spawn = require('child-process-promise').spawn; + const path = require('path'); + const os = require('os'); + const fs = require('fs'); // File extension for the created JPEG files. const JPEG_EXTENSION = '.jpg'; @@ -30,7 +30,7 @@ const JPEG_EXTENSION = '.jpg'; * When an image is uploaded in the Storage bucket it is converted to JPEG automatically using * ImageMagick. */ -exports.imageToJPG = functions.storage.object().onChange(event => { + exports.imageToJPG = functions.storage.object().onChange(event => { const object = event.data; const filePath = object.name; const baseFileName = path.basename(filePath, path.extname(filePath)); @@ -43,19 +43,19 @@ exports.imageToJPG = functions.storage.object().onChange(event => { // Exit if this is triggered on a file that is not an image. if (!object.contentType.startsWith('image/')) { console.log('This is not an image.'); - return; + return null; } // Exit if the image is already a JPEG. if (object.contentType.startsWith('image/jpeg')) { console.log('Already a JPEG.'); - return; + return null; } // Exit if this is a move or deletion event. if (object.resourceState === 'not_exists') { console.log('This is a deletion event.'); - return; + return null; } const bucket = gcs.bucket(object.bucket); @@ -65,7 +65,7 @@ exports.imageToJPG = functions.storage.object().onChange(event => { return bucket.file(filePath).download({destination: tempLocalFile}); }).then(() => { console.log('The file has been downloaded to', - tempLocalFile); + tempLocalFile); // Convert the image to JPEG using ImageMagick. return spawn('convert', [tempLocalFile, tempLocalJPEGFile]); }).then(() => { @@ -77,5 +77,6 @@ exports.imageToJPG = functions.storage.object().onChange(event => { // Once the image has been converted delete the local files to free up disk space. fs.unlinkSync(tempLocalJPEGFile); fs.unlinkSync(tempLocalFile); + return; }); }); diff --git a/coupon-on-purchase/functions/index.js b/coupon-on-purchase/functions/index.js index b716a7c9b3..d789477c2c 100644 --- a/coupon-on-purchase/functions/index.js +++ b/coupon-on-purchase/functions/index.js @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const admin = require('firebase-admin'); -admin.initializeApp(functions.config().firebase); + const functions = require('firebase-functions'); + const admin = require('firebase-admin'); + admin.initializeApp(functions.config().firebase); // [START all] /** @@ -47,7 +47,7 @@ exports.sendCouponOnPurchase = functions.analytics.event('in_app_purchase').onLo * @param {string} uid The UID of the user. * @param {string} userLanguage The user language in language-country format. */ -function sendCouponViaFCM(uid, userLanguage) { + function sendCouponViaFCM(uid, userLanguage) { // Fetching all the user's device tokens. return getDeviceTokens(uid).then(tokens => { if (tokens.length > 0) { @@ -72,6 +72,7 @@ function sendCouponViaFCM(uid, userLanguage) { // Send notifications to all tokens. return admin.messaging().sendToDevice(tokens, payload); } + return null; }); } @@ -81,7 +82,7 @@ function sendCouponViaFCM(uid, userLanguage) { * @param {string} uid The UID of the user. * @param {string} userLanguage The user language in language-country format. */ -function sendHighValueCouponViaFCM(uid, userLanguage) { + function sendHighValueCouponViaFCM(uid, userLanguage) { // Fetching all the user's device tokens. return getDeviceTokens(uid).then(tokens => { if (tokens.length > 0) { @@ -106,6 +107,7 @@ function sendHighValueCouponViaFCM(uid, userLanguage) { // Send notifications to all tokens. return admin.messaging().sendToDevice(tokens, payload); } + return null; }); } @@ -114,7 +116,7 @@ function sendHighValueCouponViaFCM(uid, userLanguage) { * * @param {string} uid The UID of the user. */ -function getDeviceTokens(uid) { + function getDeviceTokens(uid) { return admin.database().ref(`/users/${uid}/tokens`).once('value').then(snap => { if (snap.exists()) { return Object.keys(snap.val()); diff --git a/crashlytics-integration/email-notifier/functions/index.js b/crashlytics-integration/email-notifier/functions/index.js index 68981c9da0..f99654d92a 100644 --- a/crashlytics-integration/email-notifier/functions/index.js +++ b/crashlytics-integration/email-notifier/functions/index.js @@ -47,7 +47,7 @@ exports.sendOnNewIssue = functions.crashlytics.issue().onNewDetected(event => { }; return sendgridMail.send(emailDetails).then(() => { - console.log('Successfully sent new issue email'); + return console.log('Successfully sent new issue email'); }).catch(error => { console.error(error.toString()); }); @@ -81,7 +81,7 @@ exports.sendOnRegressedIssue = functions.crashlytics.issue().onRegressed(event = }; return sendgridMail.send(emailDetails).then(() => { - console.log('Successfully sent regressed issue email'); + return console.log('Successfully sent regressed issue email'); }).catch(error => { console.error(error.toString()); }); @@ -117,7 +117,7 @@ exports.sendOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert(even }; return sendgridMail.send(emailDetails).then(() => { - console.log('Successfully sent velocity alert email'); + return console.log('Successfully sent velocity alert email'); }).catch(error => { console.error(error.toString()); }); diff --git a/crashlytics-integration/jira-issue/functions/index.js b/crashlytics-integration/jira-issue/functions/index.js index 2d5371f15a..ed04c2032f 100644 --- a/crashlytics-integration/jira-issue/functions/index.js +++ b/crashlytics-integration/jira-issue/functions/index.js @@ -46,7 +46,7 @@ const calculateIssuePriority = eventType => { // of the url fragments const parseUrl = url => { // input url format: https://yourdomain.atlassian.net/projects/XX - const matches = url.match(/(https?:\/\/)(.+?)(\/.+)?\/(projects|browse)\/([\w\-]+)/); + const matches = url.match(/(https?:\/\/)(.+?)(\/.+)?\/(projects|browse)\/([\w-]+)/); if (matches && matches.length === 6) { return {protocol: matches[1], domain: matches[2], contextPath: matches[3] || '', projectKey: matches[5]}; } else { @@ -113,7 +113,7 @@ exports.createNewIssue = functions.crashlytics.issue().onNewDetected(event => { `version ${latestAppVersion}`; const priority = calculateIssuePriority(); return createJiraIssue(summary, description, priority).then(() => { - console.log(`Created issue ${issueId} in Jira successfully`); + return console.log(`Created issue ${issueId} in Jira successfully`); }); }); @@ -134,7 +134,7 @@ exports.createRegressedIssue = functions.crashlytics.issue().onRegressed(event = `${new Date(resolvedTime).toString()}`; const priority = calculateIssuePriority('regressed'); return createJiraIssue(summary, description, priority).then(() => { - console.log(`Created issue ${issueId} in Jira successfully`); + return console.log(`Created issue ${issueId} in Jira successfully`); }); }); @@ -155,6 +155,6 @@ exports.createVelocityAlert = functions.crashlytics.issue().onVelocityAlert(even `${parseFloat(crashPercentage).toFixed(2)}% of all sessions to crash.`; const priority = calculateIssuePriority('velocityAlert'); return createJiraIssue(summary, description, priority).then(() => { - console.log(`Created issue ${issueId} in Jira successfully`); + return console.log(`Created issue ${issueId} in Jira successfully`); }); }); diff --git a/crashlytics-integration/slack-notifier/functions/index.js b/crashlytics-integration/slack-notifier/functions/index.js index a09460ee81..8331245e38 100644 --- a/crashlytics-integration/slack-notifier/functions/index.js +++ b/crashlytics-integration/slack-notifier/functions/index.js @@ -45,7 +45,7 @@ exports.postOnNewIssue = functions.crashlytics.issue().onNewDetected(event => { `in ${appName}, version ${latestAppVersion} on ${appPlatform}`; return notifySlack(slackMessage).then(() => { - console.log(`Posted new issue ${issueId} successfully to Slack`); + return console.log(`Posted new issue ${issueId} successfully to Slack`); }); }); @@ -64,7 +64,7 @@ exports.postOnRegressedIssue = functions.crashlytics.issue().onRegressed(event = `resolved at ${new Date(resolvedTime).toString()}`; return notifySlack(slackMessage).then(() => { - console.log(`Posted regressed issue ${issueId} successfully to Slack`); + return console.log(`Posted regressed issue ${issueId} successfully to Slack`); }); }); diff --git a/delete-unused-accounts-cron/functions/index.js b/delete-unused-accounts-cron/functions/index.js index d8c156d531..b80bbd2864 100644 --- a/delete-unused-accounts-cron/functions/index.js +++ b/delete-unused-accounts-cron/functions/index.js @@ -13,15 +13,15 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const admin = require('firebase-admin'); -admin.initializeApp(functions.config().firebase); -const rp = require('request-promise'); -const promisePool = require('es6-promise-pool'); -const PromisePool = promisePool.PromisePool; -const secureCompare = require('secure-compare'); + const functions = require('firebase-functions'); + const admin = require('firebase-admin'); + admin.initializeApp(functions.config().firebase); + const rp = require('request-promise'); + const promisePool = require('es6-promise-pool'); + const PromisePool = promisePool.PromisePool; + const secureCompare = require('secure-compare'); // Maximum concurrent account deletions. const MAX_CONCURRENT = 3; @@ -30,49 +30,49 @@ const MAX_CONCURRENT = 3; * The request needs to be authorized by passing a 'key' query parameter in the URL. This key must * match a key set as an environment variable using `firebase functions:config:set cron.key="YOUR_KEY"`. */ -exports.accountcleanup = functions.https.onRequest((req, res) => { + exports.accountcleanup = functions.https.onRequest((req, res) => { const key = req.query.key; // Exit if the keys don't match if (!secureCompare(key, functions.config().cron.key)) { console.log('The key provided in the request does not match the key set in the environment. Check that', key, - 'matches the cron.key attribute in `firebase env:get`'); + 'matches the cron.key attribute in `firebase env:get`'); res.status(403).send('Security key does not match. Make sure your "key" URL query parameter matches the ' + - 'cron.key environment variable.'); - return; + 'cron.key environment variable.'); + return null; } // Fetch all user details. - getUsers().then(users => { + return getUsers(); +}).then(users => { // Find users that have not signed in in the last 30 days. const inactiveUsers = users.filter( - user => parseInt(user.lastLoginAt, 10) < Date.now() - 30 * 24 * 60 * 60 * 1000); + user => parseInt(user.lastLoginAt, 10) < Date.now() - 30 * 24 * 60 * 60 * 1000); // Use a pool so that we delete maximum `MAX_CONCURRENT` users in parallel. const promisePool = new PromisePool(() => { if (inactiveUsers.length > 0) { const userToDelete = inactiveUsers.pop(); - // Delete the inactive user. - return admin.auth().deleteUser(userToDelete.localId).then(() => { - console.log('Deleted user account', userToDelete.localId, 'because of inactivity'); - }).catch(error => { - console.error('Deletion of inactive user account', userToDelete.localId, 'failed:', error); - }); + return admin.auth().deleteUser(userToDelete.localId); } + return reject(); }, MAX_CONCURRENT); - promisePool.start().then(() => { - console.log('User cleanup finished'); - res.send('User cleanup finished'); - }); + return promisePool.start(); + }).then(() => { + return console.log('Deleted user account', userToDelete.localId, 'because of inactivity'); + }).catch(error => { + console.error('Deletion of inactive user account', userToDelete.localId, 'failed:', error); + }).then(() => { + console.log('User cleanup finished'); + return res.send('User cleanup finished'); }); -}); /** * Returns the list of all users with their ID and lastLogin timestamp. */ -function getUsers(userIds = [], nextPageToken, accessToken) { + function getUsers(userIds = [], nextPageToken, accessToken) { return getAccessToken(accessToken).then(accessToken => { const options = { method: 'POST', @@ -84,22 +84,22 @@ function getUsers(userIds = [], nextPageToken, accessToken) { json: true }; - return rp(options).then(resp => { - if (!resp.users) { - return userIds; - } - if (resp.nextPageToken) { - return getUsers(userIds.concat(resp.users), resp.nextPageToken, accessToken); - } - return userIds.concat(resp.users); - }); + return rp(options) + }).then(resp => { + if (!resp.users) { + return userIds; + } + if (resp.nextPageToken) { + return getUsers(userIds.concat(resp.users), resp.nextPageToken, accessToken); + } + return userIds.concat(resp.users); }); } /** * Returns an access token using the Google Cloud metadata server. */ -function getAccessToken(accessToken) { + function getAccessToken(accessToken) { // If we have an accessToken in cache to re-use we pass it directly. if (accessToken) { return Promise.resolve(accessToken); diff --git a/eslint_results.txt b/eslint_results.txt new file mode 100644 index 0000000000..9889cf9341 --- /dev/null +++ b/eslint_results.txt @@ -0,0 +1,113 @@ +=== /Users/tinaliang/functions-samples/assistant-say-number/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/authenticated-json-api/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/authorized-https-endpoint/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/bigquery-import/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/child-count/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/convert-images/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/coupon-on-purchase/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/crashlytics-integration/email-notifier/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/crashlytics-integration/jira-issue/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/crashlytics-integration/slack-notifier/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/delete-old-child-nodes/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/delete-unused-accounts-cron/functions === + +/Users/tinaliang/functions-samples/delete-unused-accounts-cron/functions/index.js + 47:9 error Each then() should return a value or throw promise/always-return + 53:44 warning Expected to return a value at the end of arrow function consistent-return + 58:16 warning Avoid nesting promises promise/no-nesting + 58:16 warning Avoid nesting promises promise/no-nesting + 66:5 error Expected catch() or return promise/catch-or-return + 66:5 warning Avoid nesting promises promise/no-nesting + +✖ 6 problems (2 errors, 4 warnings) + +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/developer-motivator/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/email-confirmation/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/es2017-transpile/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/exif-images/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/fcm-notifications/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/ffmpeg-convert-audio/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/fulltext-search-firestore/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/fulltext-search/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/generate-thumbnail/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/github-to-slack/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/google-sheet-sync/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/image-maker/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/image-sharp/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/instagram-auth/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/isomorphic-react-app/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/lastmodified-tracking/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/limit-children/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/line-auth/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/linkedin-auth/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/message-translation/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/minimal-webhook/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/moderate-images/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/nextjs-with-firebase-hosting/src/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/presence-firestore/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/quickstarts/big-ben/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/quickstarts/email-users/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/quickstarts/pubsub-helloworld/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/quickstarts/thumbnails/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/quickstarts/time-server/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/quickstarts/uppercase-firestore/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/quickstarts/uppercase/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/spotify-auth/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/stripe/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/survey-app-update/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/template-handlebars/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/text-moderation/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/typescript-getting-started/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/url-shortener/functions === +/Users/tinaliang/functions-samples +=== /Users/tinaliang/functions-samples/username-password-auth/functions === +/Users/tinaliang/functions-samples diff --git a/exif-images/functions/index.js b/exif-images/functions/index.js index 86506574f0..b72d66ad0d 100644 --- a/exif-images/functions/index.js +++ b/exif-images/functions/index.js @@ -13,24 +13,24 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const fs = require('fs'); -const crypto = require('crypto'); -const path = require('path'); -const os = require('os'); + const functions = require('firebase-functions'); + const fs = require('fs'); + const crypto = require('crypto'); + const path = require('path'); + const os = require('os'); -const admin = require('firebase-admin'); -admin.initializeApp(functions.config().firebase); -const gcs = require('@google-cloud/storage')(); -const spawn = require('child-process-promise').spawn; + const admin = require('firebase-admin'); + admin.initializeApp(functions.config().firebase); + const gcs = require('@google-cloud/storage')(); + const spawn = require('child-process-promise').spawn; /** * When an image is uploaded in the Storage bucket the information and metadata of the image (the * output of ImageMagick's `identify -verbose`) is saved in the Realtime Database. */ -exports.metadata = functions.storage.object().onChange(event => { + exports.metadata = functions.storage.object().onChange(event => { const object = event.data; const filePath = object.name; @@ -41,38 +41,37 @@ exports.metadata = functions.storage.object().onChange(event => { // Exit if this is triggered on a file that is not an image. if (!object.contentType.startsWith('image/')) { console.log('This is not an image.'); - return; + return null; } // Exit if this is a move or deletion event. if (object.resourceState === 'not_exists') { console.log('This is a deletion event.'); - return; + return null; } // Download file from bucket. const bucket = gcs.bucket(object.bucket); return bucket.file(filePath).download({destination: tempLocalFile}).then(() => { // Get Metadata from image. - return spawn('identify', ['-verbose', tempLocalFile], { capture: [ 'stdout', 'stderr' ]}).then(result => { - const metadata = imageMagickOutputToObject(result.stdout); - // Save metadata to realtime datastore. - return admin.database().ref(makeKeyFirebaseCompatible(filePath)).set(metadata).then(() => { - console.log('Wrote to:', filePath, 'data:', metadata); - }); - }); + var result = spawn('identify', ['-verbose', tempLocalFile], { capture: [ 'stdout', 'stderr' ]}) + const metadata = imageMagickOutputToObject(result.stdout); + // Save metadata to realtime datastore. + return admin.database().ref(makeKeyFirebaseCompatible(filePath)).set(metadata) + }).then(() => { + return console.log('Wrote to:', filePath, 'data:', metadata); }).then(() => { // Cleanup temp directory after metadata is extracted // Remove the file from temp directory fs.unlinkSync(tempLocalFile); - console.log('cleanup successful!'); + return console.log('cleanup successful!'); }); }); /** * Convert the output of ImageMagick's `identify -verbose` command to a JavaScript Object. */ -function imageMagickOutputToObject(output) { + function imageMagickOutputToObject(output) { let previousLineIndent = 0; const lines = output.match(/[^\r\n]+/g); lines.shift(); // Remove First line @@ -103,6 +102,6 @@ function imageMagickOutputToObject(output) { * Makes sure the given string does not contain characters that can't be used as Firebase * Realtime Database keys such as '.' and replaces them by '*'. */ -function makeKeyFirebaseCompatible(key) { + function makeKeyFirebaseCompatible(key) { return key.replace(/\./g, '*'); } diff --git a/fcm-notifications/functions/index.js b/fcm-notifications/functions/index.js index 205e8be54e..c9c88f0636 100644 --- a/fcm-notifications/functions/index.js +++ b/fcm-notifications/functions/index.js @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const admin = require('firebase-admin'); -admin.initializeApp(functions.config().firebase); + const functions = require('firebase-functions'); + const admin = require('firebase-admin'); + admin.initializeApp(functions.config().firebase); /** * Triggers when a user gets a new follower and sends a notification. @@ -25,7 +25,7 @@ admin.initializeApp(functions.config().firebase); * Followers add a flag to `/followers/{followedUid}/{followerUid}`. * Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`. */ -exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => { + exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => { const followerUid = event.params.followerUid; const followedUid = event.params.followedUid; // If un-follow we exit the function. @@ -64,7 +64,8 @@ exports.sendFollowerNotification = functions.database.ref('/followers/{followedU const tokens = Object.keys(tokensSnapshot.val()); // Send notifications to all tokens. - return admin.messaging().sendToDevice(tokens, payload).then(response => { + return admin.messaging().sendToDevice(tokens, payload) + }).then(response => { // For each message check if there was an error. const tokensToRemove = []; response.results.forEach((result, index) => { @@ -73,12 +74,11 @@ exports.sendFollowerNotification = functions.database.ref('/followers/{followedU console.error('Failure sending notification to', tokens[index], error); // Cleanup the tokens who are not registered anymore. if (error.code === 'messaging/invalid-registration-token' || - error.code === 'messaging/registration-token-not-registered') { + error.code === 'messaging/registration-token-not-registered') { tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove()); - } } - }); + } + }); return Promise.all(tokensToRemove); }); - }); }); diff --git a/ffmpeg-convert-audio/functions/index.js b/ffmpeg-convert-audio/functions/index.js index 9feb513e12..3892e790eb 100644 --- a/ffmpeg-convert-audio/functions/index.js +++ b/ffmpeg-convert-audio/functions/index.js @@ -13,21 +13,21 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const gcs = require('@google-cloud/storage')(); -const path = require('path'); -const os = require('os'); -const fs = require('fs'); -const ffmpeg = require('fluent-ffmpeg'); -const ffmpeg_static = require('ffmpeg-static'); + const functions = require('firebase-functions'); + const gcs = require('@google-cloud/storage')(); + const path = require('path'); + const os = require('os'); + const fs = require('fs'); + const ffmpeg = require('fluent-ffmpeg'); + const ffmpeg_static = require('ffmpeg-static'); /** * When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using * node-fluent-ffmpeg. */ -exports.generateMonoAudio = functions.storage.object().onChange(event => { + exports.generateMonoAudio = functions.storage.object().onChange(event => { const object = event.data; // The Storage object. const fileBucket = object.bucket; // The Storage bucket that contains the file. @@ -39,7 +39,7 @@ exports.generateMonoAudio = functions.storage.object().onChange(event => { // Exit if this is triggered on a file that is not an audio. if (!contentType.startsWith('audio/')) { console.log('This is not an audio.'); - return; + return null; } // Get the file name. @@ -47,20 +47,20 @@ exports.generateMonoAudio = functions.storage.object().onChange(event => { // Exit if the audio is already converted. if (fileName.endsWith('_output.flac')) { console.log('Already a converted audio.'); - return; + return null; } // Exit if this is a move or deletion event. if (resourceState === 'not_exists') { console.log('This is a deletion event.'); - return; + return null; } // Exit if file exists but is not new and is only being triggered // because of a metadata change. if (resourceState === 'exists' && metageneration > 1) { console.log('This is a metadata change event.'); - return; + return null; } // Download file from bucket. @@ -77,27 +77,28 @@ exports.generateMonoAudio = functions.storage.object().onChange(event => { console.log('Audio downloaded locally to', tempFilePath); // Convert the audio to mono channel using FFMPEG. const command = ffmpeg(tempFilePath) - .setFfmpegPath(ffmpeg_static.path) - .audioChannels(1) - .audioFrequency(16000) - .format('flac') - .on('error', (err) => { - console.log('An error occurred: ' + err.message); - }) - .on('end', () => { - console.log('Output audio created at', targetTempFilePath); + .setFfmpegPath(ffmpeg_static.path) + .audioChannels(1) + .audioFrequency(16000) + .format('flac') + .on('error', (err) => { + console.log('An error occurred: ' + err.message); + }) + .on('end', () => { + console.log('Output audio created at', targetTempFilePath); // Uploading the audio. - return bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}).then(() => { - console.log('Output audio uploaded to', targetStorageFilePath); + return bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}) + }) + .save(targetTempFilePath); + return null; + }).then(() => { + console.log('Output audio uploaded to', targetStorageFilePath); // Once the audio has been uploaded delete the local file to free up disk space. fs.unlinkSync(tempFilePath); fs.unlinkSync(targetTempFilePath); - console.log('Temporary files removed.', targetTempFilePath); + return console.log('Temporary files removed.', targetTempFilePath); }); - }) - .save(targetTempFilePath); - }); }); diff --git a/fulltext-search-firestore/functions/index.js b/fulltext-search-firestore/functions/index.js index 1457b93952..52bc58dcf9 100644 --- a/fulltext-search-firestore/functions/index.js +++ b/fulltext-search-firestore/functions/index.js @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const functions = require('firebase-functions'); -const algoliasearch = require('algoliasearch'); + const functions = require('firebase-functions'); + const algoliasearch = require('algoliasearch'); // [START init_algolia] // Initialize Algolia, requires installing Algolia dependencies: @@ -52,37 +52,37 @@ function getFirebaseUser(req, res, next) { console.log('Check if request is authorized with Firebase ID token'); if (!req.headers.authorization - || !req.headers.authorization.startsWith('Bearer ')) { + || !req.headers.authorization.startsWith('Bearer ')) { console.error( 'No Firebase ID token was passed as a Bearer token in the Authorization header.', 'Make sure you authorize your request by providing the following HTTP header:', 'Authorization: Bearer ' - ); - res.status(403).send('Unauthorized'); - return; - } - - let idToken; - if ( - req.headers.authorization && - req.headers.authorization.startsWith('Bearer ') + ); + res.status(403).send('Unauthorized'); + return; +} + +let idToken; +if ( + req.headers.authorization && + req.headers.authorization.startsWith('Bearer ') ) { - console.log('Found 'Authorization' header'); - idToken = req.headers.authorization.split('Bearer ')[1]; - } - - admin - .auth() - .verifyIdToken(idToken) - .then(decodedIdToken => { - console.log('ID Token correctly decoded', decodedIdToken); - req.user = decodedIdToken; - next(); - }) - .catch(error => { - console.error('Error while verifying Firebase ID token:', error); - res.status(403).send('Unauthorized'); - }); + console.log('Found \'Authorization\' header'); +idToken = req.headers.authorization.split('Bearer ')[1]; +} + +admin +.auth() +.verifyIdToken(idToken) +.then(decodedIdToken => { + console.log('ID Token correctly decoded', decodedIdToken); + req.user = decodedIdToken; + return next(); +}) +.catch(error => { + console.error('Error while verifying Firebase ID token:', error); + return res.status(403).send('Unauthorized'); +}); } // [END get_firebase_user] diff --git a/github-to-slack/functions/index.js b/github-to-slack/functions/index.js index 9b241541fb..eb177fb586 100644 --- a/github-to-slack/functions/index.js +++ b/github-to-slack/functions/index.js @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const rp = require('request-promise'); -const crypto = require('crypto'); -const secureCompare = require('secure-compare'); + const functions = require('firebase-functions'); + const rp = require('request-promise'); + const crypto = require('crypto'); + const secureCompare = require('secure-compare'); /** * Webhook that will be called each time there is a new GitHub commit and will post a message to * Slack. */ -exports.githubWebhook = functions.https.onRequest((req, res) => { + exports.githubWebhook = functions.https.onRequest((req, res) => { const cipher = 'sha1'; const signature = req.headers['x-hub-signature']; @@ -33,26 +33,26 @@ exports.githubWebhook = functions.https.onRequest((req, res) => { // The JSON body is automatically parsed by Cloud Functions so we re-stringify it. .update(JSON.stringify(req.body, null, 0)) .digest('hex'); - const expectedSignature = `${cipher}=${hmac}`; + const expectedSignature = `${cipher}=${hmac}`; // Check that the body of the request has been signed with the GitHub Secret. if (secureCompare(signature, expectedSignature)) { postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => { - res.end(); + return res.end(); }).catch(error => { console.error(error); - res.status(500).send('Something went wrong while posting the message to Slack.'); + return res.status(500).send('Something went wrong while posting the message to Slack.'); }); - } else { - console.error('x-hub-signature', signature, 'did not match', expectedSignature); - res.status(403).send('Your x-hub-signature\'s bad and you should feel bad!'); - } + } + console.error('x-hub-signature', signature, 'did not match', expectedSignature); + return res.status(403).send('Your x-hub-signature\'s bad and you should feel bad!'); + }); /** * Post a message to Slack about the new GitHub commit. */ -function postToSlack(url, commits, repo) { + function postToSlack(url, commits, repo) { return rp({ method: 'POST', // TODO: Configure the `slack.webhook_url` Google Cloud environment variables. diff --git a/google-sheet-sync/functions/index.js b/google-sheet-sync/functions/index.js index 8100035665..f05bd0f090 100644 --- a/google-sheet-sync/functions/index.js +++ b/google-sheet-sync/functions/index.js @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; // Sample trigger function that copies new Firebase data to a Google Sheet @@ -56,7 +56,7 @@ exports.authgoogleapi = functions.https.onRequest((req, res) => scope: SCOPES, prompt: 'consent' })) -); + ); // setup for OauthCallback const DB_TOKEN_PATH = '/api_tokens'; @@ -69,11 +69,11 @@ exports.oauthcallback = functions.https.onRequest((req, res) => { // Now tokens contains an access_token and an optional refresh_token. Save them. if (err) { res.status(400).send(err); - return; + return null; } - db.ref(DB_TOKEN_PATH).set(tokens).then( - () => res.status(200).send('App successfully configured with new Credentials. ' + - 'You can now close this page.')); + return db.ref(DB_TOKEN_PATH).set(tokens).then( + () => res.status(200).send('App successfully configured with new Credentials. ' + + 'You can now close this page.')); }); }); @@ -90,23 +90,23 @@ exports.appendrecordtospreadsheet = functions.database.ref(`${CONFIG_DATA_PATH}/ values: [[newRecord.firstColumn, newRecord.secondColumn, newRecord.thirdColumn]] } }); -}); + }); // accepts an append request, returns a Promise to append it, enriching it with auth function appendPromise(requestWithoutAuth) { return new Promise((resolve, reject) => { - getAuthorizedClient().then(client => { + return getAuthorizedClient().then(client => { const sheets = google.sheets('v4'); const request = requestWithoutAuth; request.auth = client; - sheets.spreadsheets.values.append(request, (err, response) => { + return sheets.spreadsheets.values.append(request, (err, response) => { if (err) { console.log(`The API returned an error: ${err}`); - return reject(); + return err; } return resolve(response); }); - }).catch(() => reject()); + }).catch((err) => reject(err)); }); } diff --git a/image-sharp/functions/index.js b/image-sharp/functions/index.js index 4986ef7ea8..c635a4af9b 100644 --- a/image-sharp/functions/index.js +++ b/image-sharp/functions/index.js @@ -13,21 +13,21 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const gcs = require('@google-cloud/storage')(); -const path = require('path'); -const sharp = require('sharp'); + const functions = require('firebase-functions'); + const gcs = require('@google-cloud/storage')(); + const path = require('path'); + const sharp = require('sharp'); -const THUMB_MAX_WIDTH = 200; -const THUMB_MAX_HEIGHT = 200; + const THUMB_MAX_WIDTH = 200; + const THUMB_MAX_HEIGHT = 200; /** * When an image is uploaded in the Storage bucket We generate a thumbnail automatically using * Sharp. */ -exports.generateThumbnail = functions.storage.object().onChange(event => { + exports.generateThumbnail = functions.storage.object().onChange(event => { const object = event.data; // The Storage object. const fileBucket = object.bucket; // The Storage bucket that contains the file. @@ -39,7 +39,7 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { // Exit if this is triggered on a file that is not an image. if (!contentType.startsWith('image/')) { console.log('This is not an image.'); - return; + return null; } // Get the file name. @@ -47,20 +47,20 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { // Exit if the image is already a thumbnail. if (fileName.startsWith('thumb_')) { console.log('Already a Thumbnail.'); - return; + return null; } // Exit if this is a move or deletion event. if (resourceState === 'not_exists') { console.log('This is a deletion event.'); - return; + return null; } // Exit if file exists but is not new and is only being triggered // because of a metadata change. if (resourceState === 'exists' && metageneration > 1) { console.log('This is a metadata change event.'); - return; + return null; } // Download file from bucket. @@ -78,15 +78,15 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { // Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream const pipeline = sharp(); pipeline - .resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT) - .max() - .pipe(thumbnailUploadStream); + .resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT) + .max() + .pipe(thumbnailUploadStream); bucket.file(filePath).createReadStream().pipe(pipeline); const streamAsPromise = new Promise((resolve, reject) => thumbnailUploadStream.on('finish', resolve).on('error', reject)); return streamAsPromise.then(() => { - console.log('Thumbnail created successfully'); + return console.log('Thumbnail created successfully'); }); }); diff --git a/instagram-auth/functions/index.js b/instagram-auth/functions/index.js index 612cd10c27..0cfcbe074e 100644 --- a/instagram-auth/functions/index.js +++ b/instagram-auth/functions/index.js @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const cookieParser = require('cookie-parser'); -const crypto = require('crypto'); + const functions = require('firebase-functions'); + const cookieParser = require('cookie-parser'); + const crypto = require('crypto'); // Firebase Setup const admin = require('firebase-admin'); @@ -33,7 +33,7 @@ const OAUTH_SCOPES = 'basic'; /** * Creates a configured simple-oauth2 client for Instagram. */ -function instagramOAuth2Client() { + function instagramOAuth2Client() { // Instagram OAuth 2 setup // TODO: Configure the `instagram.client_id` and `instagram.client_secret` Google Cloud environment variables. const credentials = { @@ -53,7 +53,7 @@ function instagramOAuth2Client() { * Redirects the User to the Instagram authentication consent screen. Also the 'state' cookie is set for later state * verification. */ -exports.redirect = functions.https.onRequest((req, res) => { + exports.redirect = functions.https.onRequest((req, res) => { const oauth2 = instagramOAuth2Client(); cookieParser()(req, res, () => { @@ -76,11 +76,11 @@ exports.redirect = functions.https.onRequest((req, res) => { * The Firebase custom auth token, display name, photo URL and Instagram acces token are sent back in a JSONP callback * function with function name defined by the 'callback' query parameter. */ -exports.token = functions.https.onRequest((req, res) => { + exports.token = functions.https.onRequest((req, res) => { const oauth2 = instagramOAuth2Client(); try { - cookieParser()(req, res, () => { + return cookieParser()(req, res, () => { console.log('Received verification state:', req.cookies.state); console.log('Received state:', req.query.state); if (!req.cookies.state) { @@ -92,8 +92,9 @@ exports.token = functions.https.onRequest((req, res) => { oauth2.authorizationCode.getToken({ code: req.query.code, redirect_uri: OAUTH_REDIRECT_URI - }).then(results => { - console.log('Auth code exchange result received:', results); + }) + }).then(results => { + console.log('Auth code exchange result received:', results); // We have an Instagram access token and the user identity now. const accessToken = results.access_token; @@ -102,16 +103,15 @@ exports.token = functions.https.onRequest((req, res) => { const userName = results.user.full_name; // Create a Firebase account and get the Custom Auth Token. - createFirebaseAccount(instagramUserID, userName, profilePic, accessToken).then(firebaseToken => { + return createFirebaseAccount(instagramUserID, userName, profilePic, accessToken) + }).then(firebaseToken => { // Serve an HTML page that signs the user in and updates the user profile. - res.jsonp({token: firebaseToken}); + return res.jsonp({token: firebaseToken}); }); - }); - }); - } catch (error) { - return res.jsonp({error: error.toString}); - } -}); + } catch (error) { + return res.jsonp({error: error.toString}); + } + }); /** * Creates a Firebase account with the given user profile and returns a custom auth token allowing @@ -120,13 +120,13 @@ exports.token = functions.https.onRequest((req, res) => { * * @returns {Promise} The Firebase custom auth token in a promise. */ -function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) { + function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) { // The UID we'll assign to the user. const uid = `instagram:${instagramID}`; // Save the access token tot he Firebase Realtime Database. const databaseTask = admin.database().ref(`/instagramAccessToken/${uid}`) - .set(accessToken); + .set(accessToken); // Create or update the user account. const userCreationTask = admin.auth().updateUser(uid, { @@ -147,9 +147,9 @@ function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) // Wait for all async task to complete then generate and return a custom auth token. return Promise.all([userCreationTask, databaseTask]).then(() => { // Create a Firebase custom auth token. - return admin.auth().createCustomToken(uid).then((token) => { - console.log('Created Custom token for UID "', uid, '" Token:', token); - return token; - }); + return admin.auth().createCustomToken(uid) + }).then((token) => { + console.log('Created Custom token for UID "', uid, '" Token:', token); + return token; }); } diff --git a/isomorphic-react-app/functions/index.js b/isomorphic-react-app/functions/index.js index 885ddef30c..3bf78a517c 100644 --- a/isomorphic-react-app/functions/index.js +++ b/isomorphic-react-app/functions/index.js @@ -14,11 +14,11 @@ * limitations under the License. */ -const functions = require('firebase-functions'); -const firebase = require('firebase'); -const app = require('express')(); -const React = require('react'); -const ReactDOMServer = require('react-dom/server'); + const functions = require('firebase-functions'); + const firebase = require('firebase'); + const app = require('express')(); + const React = require('react'); + const ReactDOMServer = require('react-dom/server'); // React App const ServerApp = React.createFactory(require('./build/server.bundle.js').default); @@ -37,8 +37,8 @@ const renderApplication = (url, res, initialState) => { res.send(templatedHtml); }; -app.get('/favicon.ico', function(req, res) { - res.send(204); +app.get('/favicon.ico', (req, res) => { + return res.send(204); }); app.get('/:userId?', (req, res) => { @@ -46,13 +46,13 @@ app.get('/:userId?', (req, res) => { if (req.params.userId) { // client is requesting user-details page with userId // load the data for that employee and its direct reports - database.getEmployeeById(req.params.userId).then(resp => { - renderApplication(req.url, res, resp); + return database.getEmployeeById(req.params.userId).then(resp => { + return renderApplication(req.url, res, resp); }); } else { // index page. load data for all employees - database.getAllEmployees().then(resp => { - renderApplication(req.url, res, resp); + return database.getAllEmployees().then(resp => { + return renderApplication(req.url, res, resp); }); } }); diff --git a/limit-children/functions/index.js b/limit-children/functions/index.js index 444265dc99..82ff1b32c4 100644 --- a/limit-children/functions/index.js +++ b/limit-children/functions/index.js @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); + const functions = require('firebase-functions'); // Max number of lines of the chat history. const MAX_LOG_COUNT = 5; @@ -28,7 +28,7 @@ exports.truncate = functions.database.ref('/chat/{messageid}').onWrite(event => if (snapshot.numChildren() >= MAX_LOG_COUNT) { let childCount = 0; const updates = {}; - snapshot.forEach(function(child) { + snapshot.forEach((child) => { if (++childCount <= snapshot.numChildren() - MAX_LOG_COUNT) { updates[child.key] = null; } @@ -36,5 +36,6 @@ exports.truncate = functions.database.ref('/chat/{messageid}').onWrite(event => // Update the parent. This effectively removes the extra children. return parentRef.update(updates); } + return null; }); }); diff --git a/line-auth/functions/index.js b/line-auth/functions/index.js index 0ad331d3ed..a1a7434ffc 100644 --- a/line-auth/functions/index.js +++ b/line-auth/functions/index.js @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; // Modules imports const functions = require('firebase-functions'); @@ -44,7 +44,7 @@ function generateLineApiRequest(apiEndpoint, lineAccessToken) { * * @returns {Promise} The Firebase user record in a promise. */ -function getFirebaseUser(lineMid, lineAccessToken) { + function getFirebaseUser(lineMid, lineAccessToken) { // Generate Firebase user's uid based on LINE's mid const firebaseUid = `line:${lineMid}`; @@ -54,11 +54,15 @@ function getFirebaseUser(lineMid, lineAccessToken) { return admin.auth().getUser(firebaseUid).catch(error => { // If user does not exist, fetch LINE profile and create a Firebase new user with it if (error.code === 'auth/user-not-found') { - return rp(getProfileOptions).then(response => { + return rp(getProfileOptions); + } + // If error other than auth/user-not-found occurred, fail the whole login process + throw error; + }).then(response => { // Parse user profile from LINE's get user profile API response const displayName = response.displayName; const photoURL = response.pictureUrl; - + console.log('Create new Firebase user for LINE user mid = "', lineMid,'"'); // Create a new Firebase user with LINE profile and return it return admin.auth().createUser({ @@ -67,10 +71,6 @@ function getFirebaseUser(lineMid, lineAccessToken) { photoURL: photoURL }); }); - } - // If error other than auth/user-not-found occurred, fail the whole login process - throw error; - }); } /** @@ -85,19 +85,19 @@ function getFirebaseUser(lineMid, lineAccessToken) { * * @returns {Promise} The Firebase custom auth token in a promise. */ -function verifyLineToken(lineAccessToken) { + function verifyLineToken(lineAccessToken) { // Send request to LINE server for access token verification const verifyTokenOptions = generateLineApiRequest('https://api.line.me/v1/oauth/verify', lineAccessToken); // STEP 1: Verify with LINE server that a LINE access token is valid return rp(verifyTokenOptions) - .then(response => { + .then(response => { // Verify the token’s channelId match with my channelId to prevent spoof attack // As LINE's Get user profiles API response doesn't include channelID, // you must not skip this step to make sure that the LINE access token is indeed // issued for your channel. //TODO: consider !== here - if (response.channelId != functions.config().line.channelid) { + if (response.channelId !== functions.config().line.channelid) { return Promise.reject(new Error('LINE channel ID mismatched')); } @@ -105,13 +105,14 @@ function verifyLineToken(lineAccessToken) { const lineMid = response.mid; return getFirebaseUser(lineMid, lineAccessToken); }) - .then(userRecord => { + .then(userRecord => { // STEP 3: Generate Firebase Custom Auth Token - return admin.auth().createCustomToken(userRecord.uid).then(token => { - console.log('Created Custom token for UID "', userRecord.uid, '" Token:', token); - return token; - }); - }); + return admin.auth().createCustomToken(userRecord.uid); + }) + .then(token => { + console.log('Created Custom token for UID "', userRecord.uid, '" Token:', token); + return token; + }); } // Verify LINE token and exchange for Firebase Custom Auth token @@ -126,13 +127,13 @@ exports.verifyToken = functions.https.onRequest((req, res) => { const reqToken = req.body.token; // Verify LINE access token with LINE server then generate Firebase Custom Auth token - verifyLineToken(reqToken) - .then(customAuthToken => { - const ret = { - firebase_token: customAuthToken - }; - return res.status(200).send(ret); - }).catch(err => { + return verifyLineToken(reqToken) + .then(customAuthToken => { + const ret = { + firebase_token: customAuthToken + }; + return res.status(200).send(ret); + }).catch(err => { // If LINE access token verification failed, return error response to client const ret = { error_message: 'Authentication error: Cannot verify access token.' diff --git a/linkedin-auth/functions/index.js b/linkedin-auth/functions/index.js index 339d95b47f..3b530c321b 100644 --- a/linkedin-auth/functions/index.js +++ b/linkedin-auth/functions/index.js @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const cookieParser = require('cookie-parser'); -const crypto = require('crypto'); + const functions = require('firebase-functions'); + const cookieParser = require('cookie-parser'); + const crypto = require('crypto'); // Firebase Setup const admin = require('firebase-admin'); @@ -32,20 +32,20 @@ const OAUTH_SCOPES = ['r_basicprofile', 'r_emailaddress']; /** * Creates a configured LinkedIn API Client instance. */ -function linkedInClient() { + function linkedInClient() { // LinkedIn OAuth 2 setup // TODO: Configure the `linkedin.client_id` and `linkedin.client_secret` Google Cloud environment variables. return require('node-linkedin')( - functions.config().linkedin.client_id, - functions.config().linkedin.client_secret, - `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`); + functions.config().linkedin.client_id, + functions.config().linkedin.client_secret, + `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`); } /** * Redirects the User to the LinkedIn authentication consent screen. ALso the 'state' cookie is set for later state * verification. */ -exports.redirect = functions.https.onRequest((req, res) => { + exports.redirect = functions.https.onRequest((req, res) => { const Linkedin = linkedInClient(); cookieParser()(req, res, () => { @@ -62,11 +62,11 @@ exports.redirect = functions.https.onRequest((req, res) => { * The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the * 'callback' query parameter. */ -exports.token = functions.https.onRequest((req, res) => { + exports.token = functions.https.onRequest((req, res) => { const Linkedin = linkedInClient(); try { - cookieParser()(req, res, () => { + return cookieParser()(req, res, () => { if (!req.cookies.state) { throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.'); } @@ -94,10 +94,10 @@ exports.token = functions.https.onRequest((req, res) => { const email = userResults.emailAddress; // Create a Firebase account and get the Custom Auth Token. - createFirebaseAccount(linkedInUserID, userName, profilePic, email, accessToken).then( - firebaseToken => { + return createFirebaseAccount(linkedInUserID, userName, profilePic, email, accessToken).then( + firebaseToken => { // Serve an HTML page that signs the user in and updates the user profile. - res.jsonp({token: firebaseToken}); + return res.jsonp({token: firebaseToken}); }); }); }); @@ -114,13 +114,13 @@ exports.token = functions.https.onRequest((req, res) => { * * @returns {Promise} The Firebase custom auth token in a promise. */ -function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessToken) { + function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessToken) { // The UID we'll assign to the user. const uid = `linkedin:${linkedinID}`; // Save the access token tot he Firebase Realtime Database. const databaseTask = admin.database().ref(`/linkedInAccessToken/${uid}`) - .set(accessToken); + .set(accessToken); // Create or update the user account. const userCreationTask = admin.auth().updateUser(uid, { @@ -145,9 +145,9 @@ function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessT // Wait for all async task to complete then generate and return a custom auth token. return Promise.all([userCreationTask, databaseTask]).then(() => { // Create a Firebase custom auth token. - return admin.auth().createCustomToken(uid).then((token) => { - console.log('Created Custom token for UID "', uid, '" Token:', token); - return token; - }); + return admin.auth().createCustomToken(uid) + }).then((token) => { + console.log('Created Custom token for UID "', uid, '" Token:', token); + return token; }); } diff --git a/message-translation/functions/index.js b/message-translation/functions/index.js index 9be750b742..53095a3efa 100644 --- a/message-translation/functions/index.js +++ b/message-translation/functions/index.js @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const admin = require('firebase-admin'); -admin.initializeApp(functions.config().firebase); -const request = require('request-promise'); + const functions = require('firebase-functions'); + const admin = require('firebase-admin'); + admin.initializeApp(functions.config().firebase); + const request = require('request-promise'); // List of output languages. const LANGUAGES = ['en', 'es', 'de', 'fr', 'sv', 'ga', 'it', 'jp']; @@ -27,7 +27,7 @@ const LANGUAGES = ['en', 'es', 'de', 'fr', 'sv', 'ga', 'it', 'jp']; exports.translate = functions.database.ref('/messages/{languageID}/{messageID}').onWrite(event => { const snapshot = event.data; if (snapshot.val().translated) { - return; + return null; } const promises = []; for (let i = 0; i < LANGUAGES.length; i++) { @@ -48,12 +48,12 @@ function createTranslationPromise(source, target, snapshot) { const key = snapshot.key; const message = snapshot.val().message; return request(createTranslateUrl(source, target, message), {resolveWithFullResponse: true}).then( - response => { - if (response.statusCode === 200) { - const data = JSON.parse(response.body).data; - return admin.database().ref(`/messages/${target}/${key}`) - .set({message: data.translations[0].translatedText, translated: true}); - } - throw response.body; - }); + response => { + if (response.statusCode === 200) { + const data = JSON.parse(response.body).data; + return admin.database().ref(`/messages/${target}/${key}`) + .set({message: data.translations[0].translatedText, translated: true}); + } + throw response.body; + }); } diff --git a/minimal-webhook/functions/index.js b/minimal-webhook/functions/index.js index 844506833f..505e12a956 100644 --- a/minimal-webhook/functions/index.js +++ b/minimal-webhook/functions/index.js @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const request = require('request-promise'); + const functions = require('firebase-functions'); + const request = require('request-promise'); // This is the URL that we will callback and send the content of the updated data node. // As an example we're using a Request Bin from http://requestb.in @@ -36,6 +36,6 @@ exports.webhook = functions.database.ref('/hooks/{hookId}').onWrite(event => { if (response.statusCode >= 400) { throw new Error(`HTTP Error: ${response.statusCode}`); } - console.log('SUCCESS! Posted', event.data.ref); + return console.log('SUCCESS! Posted', event.data.ref); }); }); diff --git a/moderate-images/functions/index.js b/moderate-images/functions/index.js index 21ad975dab..f7b1425c9a 100644 --- a/moderate-images/functions/index.js +++ b/moderate-images/functions/index.js @@ -13,22 +13,22 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const mkdirp = require('mkdirp-promise'); -const gcs = require('@google-cloud/storage')(); -const vision = require('@google-cloud/vision')(); -const spawn = require('child-process-promise').spawn; -const path = require('path'); -const os = require('os'); -const fs = require('fs'); + const functions = require('firebase-functions'); + const mkdirp = require('mkdirp-promise'); + const gcs = require('@google-cloud/storage')(); + const vision = require('@google-cloud/vision')(); + const spawn = require('child-process-promise').spawn; + const path = require('path'); + const os = require('os'); + const fs = require('fs'); /** * When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision * API and if it is we blur it using ImageMagick. */ -exports.blurOffensiveImages = functions.storage.object().onChange(event => { + exports.blurOffensiveImages = functions.storage.object().onChange(event => { const object = event.data; const file = gcs.bucket(object.bucket).file(object.name); @@ -45,13 +45,14 @@ exports.blurOffensiveImages = functions.storage.object().onChange(event => { if (safeSearch.adult || safeSearch.violence) { return blurImage(object.name, object.bucket, object.metadata); } + return null; }); }); /** * Blurs the given image located in the given bucket using ImageMagick. */ -function blurImage(filePath, bucketName, metadata) { + function blurImage(filePath, bucketName, metadata) { const tempLocalFile = path.join(os.tmpdir(), filePath); const tempLocalDir = path.dirname(tempLocalFile); const bucket = gcs.bucket(bucketName); @@ -75,6 +76,6 @@ function blurImage(filePath, bucketName, metadata) { }).then(() => { console.log('Blurred image uploaded to Storage at', filePath); fs.unlinkSync(tempLocalFile); - console.log('Deleted local file', filePath); + return console.log('Deleted local file', filePath); }); } diff --git a/paypal/functions/index.js b/paypal/functions/index.js index 53f0734579..bf137b24b6 100644 --- a/paypal/functions/index.js +++ b/paypal/functions/index.js @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); + const functions = require('firebase-functions'); // CORS Express middleware to enable CORS Requests. const cors = require('cors')({origin: true}); const paypal = require('paypal-rest-sdk'); @@ -33,22 +33,22 @@ paypal.configure({ * Set up the payment information object * Initialize the payment and redirect the user to the PayPal payment page */ -exports.pay = functions.https.onRequest((req, res) => { + exports.pay = functions.https.onRequest((req, res) => { // 1.Set up a payment information object, Nuild PayPal payment request const payReq = JSON.stringify({ - intent: 'sale', - payer: { - payment_method: 'paypal' + intent: 'sale', + payer: { + payment_method: 'paypal' + }, + redirect_urls: { + return_url: `${req.protocol}://${req.get('host')}/process`, + cancel_url: `${req.protocol}://${req.get('host')}/cancel` + }, + transactions: [{ + amount: { + total: req.body.price, + currency: 'USD' }, - redirect_urls: { - return_url: `${req.protocol}://${req.get('host')}/process`, - cancel_url: `${req.protocol}://${req.get('host')}/cancel` - }, - transactions: [{ - amount: { - total: req.body.price, - currency: 'USD' - }, // This is the payment transaction description. Maximum length: 127 description: req.body.uid, // req.body.id // reference_id string .Optional. The merchant-provided ID for the purchase unit. Maximum length: 256. @@ -57,14 +57,14 @@ exports.pay = functions.https.onRequest((req, res) => { // soft_descriptor: req.body.uid // "invoice_number": req.body.uid,A }] - }); + }); // 2.Initialize the payment and redirect the user. paypal.payment.create(payReq, (error, payment) => { - const links = {}; - if (error) { - console.error(error); - res.status('500').end(); - } else { + const links = {}; + if (error) { + console.error(error); + res.status('500').end(); + } else { // Capture HATEOAS links payment.links.forEach((linkObj) => { links[linkObj.rel] = { @@ -78,13 +78,13 @@ exports.pay = functions.https.onRequest((req, res) => { console.info(links.approval_url.href); // res.json({"approval_url":links.approval_url.href}); res.redirect(302, links.approval_url.href); - } else { + } else { console.error('no redirect URI present'); res.status('500').end(); + } } - } - }); -}); + }); + }); // 3.Complete the payment. Use the payer and payment IDs provided in the query string following the redirect. exports.process = functions.https.onRequest((req, res) => { @@ -92,7 +92,7 @@ exports.process = functions.https.onRequest((req, res) => { const payerId = { payer_id: req.query.PayerID }; - paypal.payment.execute(paymentId, payerId, (error, payment) => { + return paypal.payment.execute(paymentId, payerId, (error, payment) => { if (error) { console.error(error); res.redirect(`${req.protocol}://${req.get('host')}/error`); // replace with your url page error @@ -108,7 +108,7 @@ exports.process = functions.https.onRequest((req, res) => { 'paid': true, // 'description': description, 'date': date - }).then(r => console.info('promise: ', r)); + }) res.redirect(`${req.protocol}://${req.get('host')}/success`); // replace with your url, page success } else { console.warn('payment.state: not approved ?'); @@ -116,5 +116,5 @@ exports.process = functions.https.onRequest((req, res) => { res.redirect(`https://console.firebase.google.com/project/${process.env.GCLOUD_PROJECT}/functions/logs?search=&severity=DEBUG`); } } - }); + }).then(r => console.info('promise: ', r)); }); diff --git a/presence-firestore/functions/index.js b/presence-firestore/functions/index.js index e4be40116e..ab0c6a8afe 100644 --- a/presence-firestore/functions/index.js +++ b/presence-firestore/functions/index.js @@ -28,7 +28,7 @@ const firestore = admin.firestore(); // Create a new function which is triggered on changes to /status/{uid} // Note: This is a Realtime Database trigger, *not* Cloud Firestore. exports.onUserStatusChanged = functions.database - .ref('/status/{uid}').onUpdate(event => { +.ref('/status/{uid}').onUpdate(event => { // Get the data written to Realtime Database const eventStatus = event.data.val(); @@ -45,7 +45,7 @@ exports.onUserStatusChanged = functions.database console.log(status, eventStatus); // If the current timestamp for this data is newer than // the data that triggered this event, we exit this function. - if (status.last_changed > eventStatus.last_changed) return; + if (status.last_changed > eventStatus.last_changed) return null; // Otherwise, we convert the last_changed field to a Date eventStatus.last_changed = new Date(eventStatus.last_changed); diff --git a/quickstarts/email-users/functions/index.js b/quickstarts/email-users/functions/index.js index caa14c289d..2b647c0ecf 100644 --- a/quickstarts/email-users/functions/index.js +++ b/quickstarts/email-users/functions/index.js @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const nodemailer = require('nodemailer'); + const functions = require('firebase-functions'); + const nodemailer = require('nodemailer'); // Configure the email transport using the default SMTP transport and a GMail account. // For Gmail, enable these: // 1. https://www.google.com/settings/security/lesssecureapps @@ -62,12 +62,12 @@ exports.sendWelcomeEmail = functions.auth.user().onCreate(event => { // [START onDeleteTrigger] exports.sendByeEmail = functions.auth.user().onDelete(event => { // [END onDeleteTrigger] - const user = event.data; +const user = event.data; - const email = user.email; - const displayName = user.displayName; +const email = user.email; +const displayName = user.displayName; - return sendGoodbyEmail(email, displayName); +return sendGoodbyEmail(email, displayName); }); // [END sendByeEmail] @@ -82,7 +82,7 @@ function sendWelcomeEmail(email, displayName) { mailOptions.subject = `Welcome to ${APP_NAME}!`; mailOptions.text = `Hey ${displayName || ''}! Welcome to ${APP_NAME}. I hope you will enjoy our service.`; return mailTransport.sendMail(mailOptions).then(() => { - console.log('New welcome email sent to:', email); + return console.log('New welcome email sent to:', email); }); } @@ -97,6 +97,6 @@ function sendGoodbyEmail(email, displayName) { mailOptions.subject = `Bye!`; mailOptions.text = `Hey ${displayName || ''}!, We confirm that we have deleted your ${APP_NAME} account.`; return mailTransport.sendMail(mailOptions).then(() => { - console.log('Account deletion confirmation email sent to:', email); + return console.log('Account deletion confirmation email sent to:', email); }); } diff --git a/quickstarts/thumbnails/functions/index.js b/quickstarts/thumbnails/functions/index.js index 7d269fc64f..77791e43e0 100644 --- a/quickstarts/thumbnails/functions/index.js +++ b/quickstarts/thumbnails/functions/index.js @@ -13,7 +13,7 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; // [START import] const functions = require('firebase-functions'); @@ -46,7 +46,7 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { // Exit if this is triggered on a file that is not an image. if (!contentType.startsWith('image/')) { console.log('This is not an image.'); - return; + return null; } // Get the file name. @@ -54,20 +54,20 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { // Exit if the image is already a thumbnail. if (fileName.startsWith('thumb_')) { console.log('Already a Thumbnail.'); - return; + return null; } // Exit if this is a move or deletion event. if (resourceState === 'not_exists') { console.log('This is a deletion event.'); - return; + return null; } // Exit if file exists but is not new and is only being triggered // because of a metadata change. if (resourceState === 'exists' && metageneration > 1) { console.log('This is a metadata change event.'); - return; + return null; } // [END stopConditions] @@ -90,7 +90,7 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { // Uploading the thumbnail. return bucket.upload(tempFilePath, { destination: thumbFilePath, metadata: metadata }); // Once the thumbnail has been uploaded delete the local file to free up disk space. - }).then(() => fs.unlinkSync(tempFilePath)); +}).then(() => fs.unlinkSync(tempFilePath)); // [END thumbnailGeneration] }); // [END generateThumbnail] diff --git a/quickstarts/uppercase-firestore/functions/index.js b/quickstarts/uppercase-firestore/functions/index.js index 95a075fee4..a106bbdb2f 100644 --- a/quickstarts/uppercase-firestore/functions/index.js +++ b/quickstarts/uppercase-firestore/functions/index.js @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; // [START all] // [START import] @@ -35,9 +35,9 @@ exports.addMessage = functions.https.onRequest((req, res) => { const original = req.query.text; // [START adminSdkAdd] // Push the new message into the Realtime Database using the Firebase Admin SDK. - admin.firestore().collection('messages').add({original: original}).then(writeResult => { + return admin.firestore().collection('messages').add({original: original}).then(writeResult => { // Send back a message that we've succesfully written the message - res.json({result: `Message with ID: ${writeResult.id} added.`}); + return res.json({result: `Message with ID: ${writeResult.id} added.`}); }); // [END adminSdkAdd] }); @@ -48,7 +48,7 @@ exports.addMessage = functions.https.onRequest((req, res) => { // uppercase version of the message to /messages/:documentId/uppercase // [START makeUppercaseTrigger] exports.makeUppercase = functions.firestore.document('/messages/{documentId}') - .onCreate(event => { +.onCreate(event => { // [END makeUppercaseTrigger] // [START makeUppercaseBody] diff --git a/quickstarts/uppercase/functions/index.js b/quickstarts/uppercase/functions/index.js index 94ad65d291..0c0b89e3d8 100644 --- a/quickstarts/uppercase/functions/index.js +++ b/quickstarts/uppercase/functions/index.js @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; // [START all] // [START import] @@ -35,9 +35,9 @@ exports.addMessage = functions.https.onRequest((req, res) => { const original = req.query.text; // [START adminSdkPush] // Push the new message into the Realtime Database using the Firebase Admin SDK. - admin.database().ref('/messages').push({original: original}).then(snapshot => { + return admin.database().ref('/messages').push({original: original}).then(snapshot => { // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console. - res.redirect(303, snapshot.ref); + return res.redirect(303, snapshot.ref); }); // [END adminSdkPush] }); @@ -48,7 +48,7 @@ exports.addMessage = functions.https.onRequest((req, res) => { // uppercase version of the message to /messages/:pushId/uppercase // [START makeUppercaseTrigger] exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') - .onWrite(event => { +.onWrite(event => { // [END makeUppercaseTrigger] // [START makeUppercaseBody] // Grab the current value of what was written to the Realtime Database. diff --git a/spotify-auth/functions/index.js b/spotify-auth/functions/index.js index 25a6c45ed2..2a536e0266 100644 --- a/spotify-auth/functions/index.js +++ b/spotify-auth/functions/index.js @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const cookieParser = require('cookie-parser'); -const crypto = require('crypto'); + const functions = require('firebase-functions'); + const cookieParser = require('cookie-parser'); + const crypto = require('crypto'); // Firebase Setup const admin = require('firebase-admin'); @@ -43,7 +43,7 @@ const OAUTH_SCOPES = ['user-read-email']; * Redirects the User to the Spotify authentication consent screen. Also the 'state' cookie is set for later state * verification. */ -exports.redirect = functions.https.onRequest((req, res) => { + exports.redirect = functions.https.onRequest((req, res) => { cookieParser()(req, res, () => { const state = req.cookies.state || crypto.randomBytes(20).toString('hex'); console.log('Setting verification state:', state); @@ -59,7 +59,7 @@ exports.redirect = functions.https.onRequest((req, res) => { * The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the * 'callback' query parameter. */ -exports.token = functions.https.onRequest((req, res) => { + exports.token = functions.https.onRequest((req, res) => { try { cookieParser()(req, res, () => { console.log('Received verification state:', req.cookies.state); @@ -90,10 +90,10 @@ exports.token = functions.https.onRequest((req, res) => { const email = userResults.body['email']; // Create a Firebase account and get the Custom Auth Token. - createFirebaseAccount(spotifyUserID, userName, profilePic, email, accessToken).then( - firebaseToken => { + return createFirebaseAccount(spotifyUserID, userName, profilePic, email, accessToken).then( + firebaseToken => { // Serve an HTML page that signs the user in and updates the user profile. - res.jsonp({token: firebaseToken}); + return res.jsonp({token: firebaseToken}); }); }); }); @@ -101,6 +101,7 @@ exports.token = functions.https.onRequest((req, res) => { } catch (error) { return res.jsonp({error: error.toString}); } + return null; }); /** @@ -110,13 +111,13 @@ exports.token = functions.https.onRequest((req, res) => { * * @returns {Promise} The Firebase custom auth token in a promise. */ -function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessToken) { + function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessToken) { // The UID we'll assign to the user. const uid = `spotify:${spotifyID}`; // Save the access token to the Firebase Realtime Database. const databaseTask = admin.database().ref(`/spotifyAccessToken/${uid}`) - .set(accessToken); + .set(accessToken); // Create or update the user account. const userCreationTask = admin.auth().updateUser(uid, { @@ -141,9 +142,9 @@ function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessTo // Wait for all async tasks to complete, then generate and return a custom auth token. return Promise.all([userCreationTask, databaseTask]).then(() => { // Create a Firebase custom auth token. - return admin.auth().createCustomToken(uid).then((token) => { - console.log('Created Custom token for UID "', uid, '" Token:', token); - return token; - }); + return admin.auth().createCustomToken(uid) + }).then((token) => { + console.log('Created Custom token for UID "', uid, '" Token:', token); + return token; }); } diff --git a/stripe/functions/index.js b/stripe/functions/index.js index 6af9e2c1a5..81a616d67d 100644 --- a/stripe/functions/index.js +++ b/stripe/functions/index.js @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'), - admin = require('firebase-admin'), - logging = require('@google-cloud/logging')(); + const functions = require('firebase-functions'), + admin = require('firebase-admin'), + logging = require('@google-cloud/logging')(); -admin.initializeApp(functions.config().firebase); + admin.initializeApp(functions.config().firebase); -const stripe = require('stripe')(functions.config().stripe.token), - currency = functions.config().stripe.currency || 'USD'; + const stripe = require('stripe')(functions.config().stripe.token), + currency = functions.config().stripe.currency || 'USD'; // [START chargecustomer] // Charge the Stripe customer whenever an amount is written to the Realtime database @@ -47,12 +47,12 @@ exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/ }, error => { // We want to capture errors and render them in a user-friendly way, while // still logging an exception with Stackdriver - return event.data.adminRef.child('error').set(userFacingMessage(error)).then(() => { - return reportError(error, {user: event.params.userId}); - }); + return event.data.adminRef.child('error').set(userFacingMessage(error)) } - ); -}); + ).then(() => { + return reportError(error, {user: event.params.userId}); + }); + }); // [END chargecustomer]] // When a user is created, register them with Stripe @@ -74,11 +74,11 @@ exports.addPaymentSource = functions.database.ref('/stripe_customers/{userId}/so }).then(customer => { return stripe.customers.createSource(customer, {source}); }).then(response => { - return event.data.adminRef.parent.set(response); - }, error => { - return event.data.adminRef.parent.child('error').set(userFacingMessage(error)).then(() => { - return reportError(error, {user: event.params.userId}); - }); + return event.data.adminRef.parent.set(response); + }, error => { + return event.data.adminRef.parent.child('error').set(userFacingMessage(error)) + }).then(() => { + return reportError(error, {user: event.params.userId}); }); }); diff --git a/survey-app-update/functions/index.js b/survey-app-update/functions/index.js index a9d8c12513..7883deb536 100644 --- a/survey-app-update/functions/index.js +++ b/survey-app-update/functions/index.js @@ -49,6 +49,7 @@ exports.sendAppUpdateSurvey = functions.analytics.event('app_update').onLog(even return sendSurveyEmail(email, name); }); } + return null; }); /** @@ -65,6 +66,6 @@ function sendSurveyEmail(email, name) { }; return mailTransport.sendMail(mailOptions).then(() => { - console.log('Upgrade App Survey email sent to:', email); + return console.log('Upgrade App Survey email sent to:', email); }); } diff --git a/template-handlebars/functions/firebaseUser.js b/template-handlebars/functions/firebaseUser.js index 494f1a64f0..1566e408c4 100644 --- a/template-handlebars/functions/firebaseUser.js +++ b/template-handlebars/functions/firebaseUser.js @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const admin = require('firebase-admin'); -const cookieParser = require('cookie-parser')(); + const admin = require('firebase-admin'); + const cookieParser = require('cookie-parser')(); // Express middleware that checks if a Firebase ID Tokens is passed in the `Authorization` HTTP // header or the `__session` cookie and decodes it. @@ -26,27 +26,26 @@ const cookieParser = require('cookie-parser')(); const validateFirebaseIdToken = (req, res, next) => { console.log('Check if request is authorized with Firebase ID token'); - getIdTokenFromRequest(req, res).then(idToken => { + return getIdTokenFromRequest(req, res).then(idToken => { if (idToken) { - addDecodedIdTokenToRequest(idToken, req).then(() => { - next(); - }); - } else { - next(); + return addDecodedIdTokenToRequest(idToken, req); } + return next(); + }).then(() => { + return next(); }); }; /** * Returns a Promise with the Firebase ID Token if found in the Authorization or the __session cookie. */ -function getIdTokenFromRequest(req, res) { + function getIdTokenFromRequest(req, res) { if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) { console.log('Found "Authorization" header'); // Read the ID Token from the Authorization header. return Promise.resolve(req.headers.authorization.split('Bearer ')[1]); } - return new Promise(function(resolve) { + return new Promise((resolve, reject) => { cookieParser(req, res, () => { if (req.cookies && req.cookies.__session) { console.log('Found "__session" cookie'); @@ -62,10 +61,10 @@ function getIdTokenFromRequest(req, res) { /** * Returns a Promise with the Decoded ID Token and adds it to req.user. */ -function addDecodedIdTokenToRequest(idToken, req) { + function addDecodedIdTokenToRequest(idToken, req) { return admin.auth().verifyIdToken(idToken).then(decodedIdToken => { - console.log('ID Token correctly decoded', decodedIdToken); req.user = decodedIdToken; + return console.log('ID Token correctly decoded', decodedIdToken); }).catch(error => { console.error('Error while verifying Firebase ID token:', error); }); diff --git a/template-handlebars/functions/index.js b/template-handlebars/functions/index.js index ef2bab6384..3e62de9860 100644 --- a/template-handlebars/functions/index.js +++ b/template-handlebars/functions/index.js @@ -29,7 +29,7 @@ app.use(firebaseUser.validateFirebaseIdToken); app.get('/', (req, res) => { console.log('Signed-in user:', req.user); - res.render('user', { + return res.render('user', { user: req.user }); }); diff --git a/text-moderation/functions/index.js b/text-moderation/functions/index.js index 3446ae2ae7..92579944a2 100644 --- a/text-moderation/functions/index.js +++ b/text-moderation/functions/index.js @@ -13,19 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const capitalizeSentence = require('capitalize-sentence'); -const Filter = require('bad-words'); -const badWordsFilter = new Filter(); + const functions = require('firebase-functions'); + const capitalizeSentence = require('capitalize-sentence'); + const Filter = require('bad-words'); + const badWordsFilter = new Filter(); // Moderates messages by lowering all uppercase messages and removing swearwords. exports.moderator = functions.database - .ref('/messages/{messageId}').onWrite(event => { - const message = event.data.val(); +.ref('/messages/{messageId}').onWrite(event => { + const message = event.data.val(); - if (message && !message.sanitized) { + if (message && !message.sanitized) { // Retrieved the message values. console.log('Retrieved message content: ', message); @@ -40,6 +40,7 @@ exports.moderator = functions.database moderated: message.text !== moderatedMessage }); } + return null; }); // Moderates the given message if appropriate. diff --git a/url-shortener/functions/index.js b/url-shortener/functions/index.js index dfe0ffc433..c4d5a371d0 100644 --- a/url-shortener/functions/index.js +++ b/url-shortener/functions/index.js @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); -const admin = require('firebase-admin'); -admin.initializeApp(functions.config().firebase); -const request = require('request-promise'); + const functions = require('firebase-functions'); + const admin = require('firebase-admin'); + admin.initializeApp(functions.config().firebase); + const request = require('request-promise'); // Shorten URL exports.shortenUrl = functions.database.ref('/links/{linkID}').onWrite(event => { const snapshot = event.data; if (typeof snapshot.val() !== 'string') { - return; + return null; } return createShortenerPromise(snapshot); }); diff --git a/username-password-auth/functions/index.js b/username-password-auth/functions/index.js index 89c4fd3106..0f28dad253 100644 --- a/username-password-auth/functions/index.js +++ b/username-password-auth/functions/index.js @@ -13,9 +13,9 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ -'use strict'; + 'use strict'; -const functions = require('firebase-functions'); + const functions = require('firebase-functions'); // CORS Express middleware to enable CORS Requests. const cors = require('cors')({ @@ -42,7 +42,7 @@ const basicAuthRequest = require('request'); * If the request method is unsupported (not POST) return a 403 response. * If an error occurs log the details and return a 500 response. */ -exports.auth = functions.https.onRequest((req, res) => { + exports.auth = functions.https.onRequest((req, res) => { const handleError = (username, error) => { console.error({ User: username @@ -82,16 +82,16 @@ exports.auth = functions.https.onRequest((req, res) => { } // TODO(DEVELOPER): In production you'll need to update the `authenticate` function so that it authenticates with your own credentials system. - authenticate(username, password).then(valid => { + return authenticate(username, password).then(valid => { if (!valid) { return handleResponse(username, 401); // Invalid username/password } // On success return the Firebase Custom Auth Token. - return admin.auth().createCustomToken(username).then(firebaseToken => { - return handleResponse(username, 200, { - token: firebaseToken - }); + return admin.auth().createCustomToken(username) + }).then(firebaseToken => { + return handleResponse(username, 200, { + token: firebaseToken }); }).catch(error => { return handleError(username, error); @@ -100,6 +100,7 @@ exports.auth = functions.https.onRequest((req, res) => { } catch (error) { return handleError(username, error); } + return null; }); /** @@ -107,7 +108,7 @@ exports.auth = functions.https.onRequest((req, res) => { * TODO(DEVELOPER): In production you'll need to update this function so that it authenticates with your own credentials system. * @returns {Promise} success or failure. */ -function authenticate(username, password) { + function authenticate(username, password) { // For the purpose of this example use httpbin (https://httpbin.org) and send a basic authentication request. // (Only a password of `Testing123` will succeed) From be7da308f0395a9e59edb1edbb3fc841323a6b5c Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Mon, 8 Jan 2018 15:43:08 -0800 Subject: [PATCH 03/16] fixed spacing, coding issues up to line-auth function sample --- authenticated-json-api/functions/index.js | 25 ++-- child-count/functions/index.js | 31 ++--- convert-images/functions/index.js | 21 ++-- coupon-on-purchase/functions/index.js | 14 +-- .../functions/index.js | 22 ++-- eslint_results.txt | 113 ----------------- exif-images/functions/index.js | 31 ++--- fcm-notifications/functions/index.js | 36 +++--- ffmpeg-convert-audio/functions/index.js | 84 +++++++------ fulltext-search-firestore/functions/index.js | 54 ++++---- github-to-slack/functions/index.js | 80 ++++++------ google-sheet-sync/functions/index.js | 54 ++++---- image-sharp/functions/index.js | 57 ++++----- instagram-auth/functions/index.js | 106 ++++++++-------- line-auth/functions/index.js | 116 +++++++++--------- 15 files changed, 365 insertions(+), 479 deletions(-) delete mode 100644 eslint_results.txt diff --git a/authenticated-json-api/functions/index.js b/authenticated-json-api/functions/index.js index 155f0ee035..54b793e7bf 100644 --- a/authenticated-json-api/functions/index.js +++ b/authenticated-json-api/functions/index.js @@ -14,17 +14,17 @@ * limitations under the License. */ - 'use strict'; +'use strict'; - const functions = require('firebase-functions'); - const admin = require('firebase-admin'); - const Language = require('@google-cloud/language'); - const express = require('express'); +const functions = require('firebase-functions'); +const admin = require('firebase-admin'); +const Language = require('@google-cloud/language'); +const express = require('express'); - const app = express(); - const language = new Language({projectId: process.env.GCLOUD_PROJECT}); +const app = express(); +const language = new Language({projectId: process.env.GCLOUD_PROJECT}); - admin.initializeApp(functions.config().firebase); +admin.initializeApp(functions.config().firebase); // Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header. // The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this: @@ -98,13 +98,10 @@ app.get('/messages', (req, res) => { app.get('/message/:messageId', (req, res) => { const messageId = req.params.messageId; admin.database().ref(`/users/${req.user.uid}/messages/${messageId}`).once('value').then(snapshot => { - if (snapshot.val() !== null) { - // Cache details in the browser for 5 minutes - res.set('Cache-Control', 'private, max-age=300'); - return res.status(200).json(snapshot.val()); - } else { - return res.status(404).json({errorCode: 404, errorMessage: `message '${messageId}' not found`}); + if (snapshot.val() === null) { + return res.status(404).json({errorCode: 404, errorMessage: `message '${messageId}' not found`}); } + return res.set('Cache-Control', 'private, max-age=300'); }).catch(error => { console.log('Error getting message details', messageId, error.message); res.sendStatus(500); diff --git a/child-count/functions/index.js b/child-count/functions/index.js index 2b95c4a4b5..a32701e00a 100644 --- a/child-count/functions/index.js +++ b/child-count/functions/index.js @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - 'use strict'; +'use strict'; - const functions = require('firebase-functions'); - const admin = require('firebase-admin'); +const functions = require('firebase-functions'); +const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); // Keeps track of the length of the 'likes' child list in a separate property. @@ -24,19 +24,22 @@ exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid} const collectionRef = event.data.ref.parent; const countRef = collectionRef.parent.child('likes_count'); + let increment; + if (event.data.exists() && !event.data.previous.exists()) { + increment = 1; + } + else if (!event.data.exists() && event.data.previous.exists()) { + increment = -1; + } else { + return null; + } + // Return the promise from countRef.transaction() so our function // waits for this async event to complete before it exits. return countRef.transaction(current => { - if (event.data.exists() && !event.data.previous.exists()) { - return (current || 0) + 1; - } - else if (!event.data.exists() && event.data.previous.exists()) { - return (current || 0) - 1; - } - // What to do in other cases? - return null; - }).then(() => { - return console.log('Counter updated.'); + (current || 0) + increment; +}).then(() => { + return console.log('Counter updated.'); }); }); @@ -49,7 +52,7 @@ exports.recountlikes = functions.database.ref('/posts/{postid}/likes_count').onW // Return the promise from counterRef.set() so our function // waits for this async event to complete before it exits. return collectionRef.once('value') - .then(messagesData => counterRef.set(messagesData.numChildren())); + .then(messagesData => counterRef.set(messagesData.numChildren())); } return null; }); diff --git a/convert-images/functions/index.js b/convert-images/functions/index.js index 86e3d156e3..c0917caa8e 100644 --- a/convert-images/functions/index.js +++ b/convert-images/functions/index.js @@ -13,15 +13,15 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ - 'use strict'; +'use strict'; - const functions = require('firebase-functions'); - const mkdirp = require('mkdirp-promise'); - const gcs = require('@google-cloud/storage')(); - const spawn = require('child-process-promise').spawn; - const path = require('path'); - const os = require('os'); - const fs = require('fs'); +const functions = require('firebase-functions'); +const mkdirp = require('mkdirp-promise'); +const gcs = require('@google-cloud/storage')(); +const spawn = require('child-process-promise').spawn; +const path = require('path'); +const os = require('os'); +const fs = require('fs'); // File extension for the created JPEG files. const JPEG_EXTENSION = '.jpg'; @@ -30,7 +30,7 @@ const JPEG_EXTENSION = '.jpg'; * When an image is uploaded in the Storage bucket it is converted to JPEG automatically using * ImageMagick. */ - exports.imageToJPG = functions.storage.object().onChange(event => { +exports.imageToJPG = functions.storage.object().onChange(event => { const object = event.data; const filePath = object.name; const baseFileName = path.basename(filePath, path.extname(filePath)); @@ -64,8 +64,7 @@ const JPEG_EXTENSION = '.jpg'; // Download file from bucket. return bucket.file(filePath).download({destination: tempLocalFile}); }).then(() => { - console.log('The file has been downloaded to', - tempLocalFile); + console.log('The file has been downloaded to', tempLocalFile); // Convert the image to JPEG using ImageMagick. return spawn('convert', [tempLocalFile, tempLocalJPEGFile]); }).then(() => { diff --git a/coupon-on-purchase/functions/index.js b/coupon-on-purchase/functions/index.js index d789477c2c..cc4c59b52e 100644 --- a/coupon-on-purchase/functions/index.js +++ b/coupon-on-purchase/functions/index.js @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - 'use strict'; +'use strict'; - const functions = require('firebase-functions'); - const admin = require('firebase-admin'); - admin.initializeApp(functions.config().firebase); +const functions = require('firebase-functions'); +const admin = require('firebase-admin'); +admin.initializeApp(functions.config().firebase); // [START all] /** @@ -47,7 +47,7 @@ exports.sendCouponOnPurchase = functions.analytics.event('in_app_purchase').onLo * @param {string} uid The UID of the user. * @param {string} userLanguage The user language in language-country format. */ - function sendCouponViaFCM(uid, userLanguage) { +function sendCouponViaFCM(uid, userLanguage) { // Fetching all the user's device tokens. return getDeviceTokens(uid).then(tokens => { if (tokens.length > 0) { @@ -82,7 +82,7 @@ exports.sendCouponOnPurchase = functions.analytics.event('in_app_purchase').onLo * @param {string} uid The UID of the user. * @param {string} userLanguage The user language in language-country format. */ - function sendHighValueCouponViaFCM(uid, userLanguage) { +function sendHighValueCouponViaFCM(uid, userLanguage) { // Fetching all the user's device tokens. return getDeviceTokens(uid).then(tokens => { if (tokens.length > 0) { @@ -116,7 +116,7 @@ exports.sendCouponOnPurchase = functions.analytics.event('in_app_purchase').onLo * * @param {string} uid The UID of the user. */ - function getDeviceTokens(uid) { +function getDeviceTokens(uid) { return admin.database().ref(`/users/${uid}/tokens`).once('value').then(snap => { if (snap.exists()) { return Object.keys(snap.val()); diff --git a/delete-unused-accounts-cron/functions/index.js b/delete-unused-accounts-cron/functions/index.js index b80bbd2864..a80962182e 100644 --- a/delete-unused-accounts-cron/functions/index.js +++ b/delete-unused-accounts-cron/functions/index.js @@ -13,15 +13,15 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ - 'use strict'; +'use strict'; - const functions = require('firebase-functions'); - const admin = require('firebase-admin'); - admin.initializeApp(functions.config().firebase); - const rp = require('request-promise'); - const promisePool = require('es6-promise-pool'); - const PromisePool = promisePool.PromisePool; - const secureCompare = require('secure-compare'); +const functions = require('firebase-functions'); +const admin = require('firebase-admin'); +admin.initializeApp(functions.config().firebase); +const rp = require('request-promise'); +const promisePool = require('es6-promise-pool'); +const PromisePool = promisePool.PromisePool; +const secureCompare = require('secure-compare'); // Maximum concurrent account deletions. const MAX_CONCURRENT = 3; @@ -30,7 +30,7 @@ const MAX_CONCURRENT = 3; * The request needs to be authorized by passing a 'key' query parameter in the URL. This key must * match a key set as an environment variable using `firebase functions:config:set cron.key="YOUR_KEY"`. */ - exports.accountcleanup = functions.https.onRequest((req, res) => { +exports.accountcleanup = functions.https.onRequest((req, res) => { const key = req.query.key; // Exit if the keys don't match @@ -72,7 +72,7 @@ const MAX_CONCURRENT = 3; /** * Returns the list of all users with their ID and lastLogin timestamp. */ - function getUsers(userIds = [], nextPageToken, accessToken) { +function getUsers(userIds = [], nextPageToken, accessToken) { return getAccessToken(accessToken).then(accessToken => { const options = { method: 'POST', @@ -99,7 +99,7 @@ const MAX_CONCURRENT = 3; /** * Returns an access token using the Google Cloud metadata server. */ - function getAccessToken(accessToken) { +function getAccessToken(accessToken) { // If we have an accessToken in cache to re-use we pass it directly. if (accessToken) { return Promise.resolve(accessToken); diff --git a/eslint_results.txt b/eslint_results.txt deleted file mode 100644 index 9889cf9341..0000000000 --- a/eslint_results.txt +++ /dev/null @@ -1,113 +0,0 @@ -=== /Users/tinaliang/functions-samples/assistant-say-number/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/authenticated-json-api/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/authorized-https-endpoint/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/bigquery-import/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/child-count/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/convert-images/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/coupon-on-purchase/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/crashlytics-integration/email-notifier/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/crashlytics-integration/jira-issue/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/crashlytics-integration/slack-notifier/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/delete-old-child-nodes/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/delete-unused-accounts-cron/functions === - -/Users/tinaliang/functions-samples/delete-unused-accounts-cron/functions/index.js - 47:9 error Each then() should return a value or throw promise/always-return - 53:44 warning Expected to return a value at the end of arrow function consistent-return - 58:16 warning Avoid nesting promises promise/no-nesting - 58:16 warning Avoid nesting promises promise/no-nesting - 66:5 error Expected catch() or return promise/catch-or-return - 66:5 warning Avoid nesting promises promise/no-nesting - -✖ 6 problems (2 errors, 4 warnings) - -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/developer-motivator/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/email-confirmation/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/es2017-transpile/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/exif-images/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/fcm-notifications/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/ffmpeg-convert-audio/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/fulltext-search-firestore/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/fulltext-search/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/generate-thumbnail/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/github-to-slack/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/google-sheet-sync/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/image-maker/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/image-sharp/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/instagram-auth/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/isomorphic-react-app/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/lastmodified-tracking/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/limit-children/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/line-auth/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/linkedin-auth/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/message-translation/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/minimal-webhook/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/moderate-images/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/nextjs-with-firebase-hosting/src/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/presence-firestore/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/quickstarts/big-ben/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/quickstarts/email-users/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/quickstarts/pubsub-helloworld/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/quickstarts/thumbnails/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/quickstarts/time-server/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/quickstarts/uppercase-firestore/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/quickstarts/uppercase/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/spotify-auth/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/stripe/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/survey-app-update/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/template-handlebars/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/text-moderation/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/typescript-getting-started/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/url-shortener/functions === -/Users/tinaliang/functions-samples -=== /Users/tinaliang/functions-samples/username-password-auth/functions === -/Users/tinaliang/functions-samples diff --git a/exif-images/functions/index.js b/exif-images/functions/index.js index b72d66ad0d..5f56f0dc45 100644 --- a/exif-images/functions/index.js +++ b/exif-images/functions/index.js @@ -13,24 +13,24 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ - 'use strict'; +'use strict'; - const functions = require('firebase-functions'); - const fs = require('fs'); - const crypto = require('crypto'); - const path = require('path'); - const os = require('os'); +const functions = require('firebase-functions'); +const fs = require('fs'); +const crypto = require('crypto'); +const path = require('path'); +const os = require('os'); - const admin = require('firebase-admin'); - admin.initializeApp(functions.config().firebase); - const gcs = require('@google-cloud/storage')(); - const spawn = require('child-process-promise').spawn; +const admin = require('firebase-admin'); +admin.initializeApp(functions.config().firebase); +const gcs = require('@google-cloud/storage')(); +const spawn = require('child-process-promise').spawn; /** * When an image is uploaded in the Storage bucket the information and metadata of the image (the * output of ImageMagick's `identify -verbose`) is saved in the Realtime Database. */ - exports.metadata = functions.storage.object().onChange(event => { +exports.metadata = functions.storage.object().onChange(event => { const object = event.data; const filePath = object.name; @@ -54,8 +54,9 @@ const bucket = gcs.bucket(object.bucket); return bucket.file(filePath).download({destination: tempLocalFile}).then(() => { // Get Metadata from image. - var result = spawn('identify', ['-verbose', tempLocalFile], { capture: [ 'stdout', 'stderr' ]}) - const metadata = imageMagickOutputToObject(result.stdout); + return spawn('identify', ['-verbose', tempLocalFile], { capture: [ 'stdout', 'stderr' ]}) + }).then(() => { + const metadata = imageMagickOutputToObject(result.stdout); // Save metadata to realtime datastore. return admin.database().ref(makeKeyFirebaseCompatible(filePath)).set(metadata) }).then(() => { @@ -71,7 +72,7 @@ /** * Convert the output of ImageMagick's `identify -verbose` command to a JavaScript Object. */ - function imageMagickOutputToObject(output) { +function imageMagickOutputToObject(output) { let previousLineIndent = 0; const lines = output.match(/[^\r\n]+/g); lines.shift(); // Remove First line @@ -102,6 +103,6 @@ * Makes sure the given string does not contain characters that can't be used as Firebase * Realtime Database keys such as '.' and replaces them by '*'. */ - function makeKeyFirebaseCompatible(key) { +function makeKeyFirebaseCompatible(key) { return key.replace(/\./g, '*'); } diff --git a/fcm-notifications/functions/index.js b/fcm-notifications/functions/index.js index c9c88f0636..65a9bf3c62 100644 --- a/fcm-notifications/functions/index.js +++ b/fcm-notifications/functions/index.js @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - 'use strict'; +'use strict'; - const functions = require('firebase-functions'); - const admin = require('firebase-admin'); - admin.initializeApp(functions.config().firebase); +const functions = require('firebase-functions'); +const admin = require('firebase-admin'); +admin.initializeApp(functions.config().firebase); /** * Triggers when a user gets a new follower and sends a notification. @@ -25,7 +25,7 @@ * Followers add a flag to `/followers/{followedUid}/{followerUid}`. * Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`. */ - exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => { +exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => { const followerUid = event.params.followerUid; const followedUid = event.params.followedUid; // If un-follow we exit the function. @@ -64,21 +64,21 @@ const tokens = Object.keys(tokensSnapshot.val()); // Send notifications to all tokens. - return admin.messaging().sendToDevice(tokens, payload) + return admin.messaging().sendToDevice(tokens, payload); }).then(response => { - // For each message check if there was an error. - const tokensToRemove = []; - response.results.forEach((result, index) => { - const error = result.error; - if (error) { - console.error('Failure sending notification to', tokens[index], error); - // Cleanup the tokens who are not registered anymore. - if (error.code === 'messaging/invalid-registration-token' || - error.code === 'messaging/registration-token-not-registered') { - tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove()); + // For each message check if there was an error. + const tokensToRemove = []; + response.results.forEach((result, index) => { + const error = result.error; + if (error) { + console.error('Failure sending notification to', tokens[index], error); + // Cleanup the tokens who are not registered anymore. + if (error.code === 'messaging/invalid-registration-token' || + error.code === 'messaging/registration-token-not-registered') { + tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove()); } } }); - return Promise.all(tokensToRemove); - }); + return Promise.all(tokensToRemove); + }); }); diff --git a/ffmpeg-convert-audio/functions/index.js b/ffmpeg-convert-audio/functions/index.js index 3892e790eb..23d0eedfee 100644 --- a/ffmpeg-convert-audio/functions/index.js +++ b/ffmpeg-convert-audio/functions/index.js @@ -13,21 +13,42 @@ * See the License for t`he specific language governing permissions and * limitations under the License. */ - 'use strict'; +'use strict'; - const functions = require('firebase-functions'); - const gcs = require('@google-cloud/storage')(); - const path = require('path'); - const os = require('os'); - const fs = require('fs'); - const ffmpeg = require('fluent-ffmpeg'); - const ffmpeg_static = require('ffmpeg-static'); +const functions = require('firebase-functions'); +const gcs = require('@google-cloud/storage')(); +const path = require('path'); +const os = require('os'); +const fs = require('fs'); +const ffmpeg = require('fluent-ffmpeg'); +const ffmpeg_static = require('ffmpeg-static'); + +/** + * Utility method to convert audio to mono channel using FFMPEG. +*/ +function reencodeAsync(tempFilePath, targetTempFilePath) { + return new Promise((resolve, reject) => { + const command = ffmpeg(tempFilePath) + .setFfmpegPath(ffmpeg_static.path) + .audioChannels(1) + .audioFrequency(16000) + .format('flac') + .on('error', (err) => { + console.log('An error occurred: ' + err.message); + reject(); + }) + .on('end', () => { + console.log('Output audio created at', targetTempFilePath); + }) + .save(targetTempFilePath); + }); +} /** * When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using * node-fluent-ffmpeg. */ - exports.generateMonoAudio = functions.storage.object().onChange(event => { +exports.generateMonoAudio = functions.storage.object().onChange(event => { const object = event.data; // The Storage object. const fileBucket = object.bucket; // The Storage bucket that contains the file. @@ -70,35 +91,20 @@ const targetTempFileName = fileName.replace(/\.[^/.]+$/, "") + '_output.flac'; const targetTempFilePath = path.join(os.tmpdir(), targetTempFileName); const targetStorageFilePath = path.join(path.dirname(filePath), targetTempFileName); - - return bucket.file(filePath).download({ - destination: tempFilePath - }).then(() => { - console.log('Audio downloaded locally to', tempFilePath); - // Convert the audio to mono channel using FFMPEG. - const command = ffmpeg(tempFilePath) - .setFfmpegPath(ffmpeg_static.path) - .audioChannels(1) - .audioFrequency(16000) - .format('flac') - .on('error', (err) => { - console.log('An error occurred: ' + err.message); - }) - .on('end', () => { - console.log('Output audio created at', targetTempFilePath); - - // Uploading the audio. - return bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}) - }) - .save(targetTempFilePath); - return null; - }).then(() => { - console.log('Output audio uploaded to', targetStorageFilePath); - - // Once the audio has been uploaded delete the local file to free up disk space. - fs.unlinkSync(tempFilePath); - fs.unlinkSync(targetTempFilePath); - return console.log('Temporary files removed.', targetTempFilePath); - }); + return bucket.file(filePath) + .download({destination: tempFilePath}) + .then(() => { + console.log('Audio downloaded locally to', tempFilePath); + reencodeAsync(tempFilePath, targetTempFilePath) + }).then(() => { + bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}) + }).then(() => { + console.log('Output audio uploaded to', targetStorageFilePath); + // Once the audio has been uploaded delete the local file to free up disk space. + fs.unlinkSync(tempFilePath); + fs.unlinkSync(targetTempFilePath); + }).then(() => { + return console.log('Temporary files removed.', targetTempFilePath); + }); }); diff --git a/fulltext-search-firestore/functions/index.js b/fulltext-search-firestore/functions/index.js index 52bc58dcf9..2df2b7966a 100644 --- a/fulltext-search-firestore/functions/index.js +++ b/fulltext-search-firestore/functions/index.js @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - const functions = require('firebase-functions'); - const algoliasearch = require('algoliasearch'); +const functions = require('firebase-functions'); +const algoliasearch = require('algoliasearch'); // [START init_algolia] // Initialize Algolia, requires installing Algolia dependencies: @@ -51,38 +51,32 @@ admin.initializeApp(functions.config().firebase); function getFirebaseUser(req, res, next) { console.log('Check if request is authorized with Firebase ID token'); - if (!req.headers.authorization - || !req.headers.authorization.startsWith('Bearer ')) { + if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) { console.error( 'No Firebase ID token was passed as a Bearer token in the Authorization header.', 'Make sure you authorize your request by providing the following HTTP header:', 'Authorization: Bearer ' ); - res.status(403).send('Unauthorized'); - return; -} - -let idToken; -if ( - req.headers.authorization && - req.headers.authorization.startsWith('Bearer ') - ) { - console.log('Found \'Authorization\' header'); -idToken = req.headers.authorization.split('Bearer ')[1]; -} - -admin -.auth() -.verifyIdToken(idToken) -.then(decodedIdToken => { - console.log('ID Token correctly decoded', decodedIdToken); - req.user = decodedIdToken; - return next(); -}) -.catch(error => { - console.error('Error while verifying Firebase ID token:', error); - return res.status(403).send('Unauthorized'); -}); + return res.sendStatus(403); + } + + let idToken; + if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) { + console.log('Found \'Authorization\' header'); + idToken = req.headers.authorization.split('Bearer ')[1]; + } + + admin + .auth() + .verifyIdToken(idToken) + .then(decodedIdToken => { + console.log('ID Token correctly decoded', decodedIdToken); + req.user = decodedIdToken; + return next(); + }).catch(error => { + console.error('Error while verifying Firebase ID token:', error); + return res.status(403).send('Unauthorized'); + }); } // [END get_firebase_user] @@ -101,7 +95,7 @@ app.use(require('cors')({ origin: true })); // https://gist.github.com/abehaskins/832d6f8665454d0cd99ef08c229afb42 app.use(getFirebaseUser); -// Add a route handler to the app to generate the secured key +// Add a route handler to the app to generate the secured key app.get('/', (req, res) => { // Create the params object as described in the Algolia documentation: // https://www.algolia.com/doc/guides/security/api-keys/#generating-api-keys diff --git a/github-to-slack/functions/index.js b/github-to-slack/functions/index.js index eb177fb586..5d40acd7de 100644 --- a/github-to-slack/functions/index.js +++ b/github-to-slack/functions/index.js @@ -1,58 +1,56 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const rp = require('request-promise'); - const crypto = require('crypto'); - const secureCompare = require('secure-compare'); +const functions = require('firebase-functions'); +const rp = require('request-promise'); +const crypto = require('crypto'); +const secureCompare = require('secure-compare'); /** - * Webhook that will be called each time there is a new GitHub commit and will post a message to - * Slack. - */ - exports.githubWebhook = functions.https.onRequest((req, res) => { +* Webhook that will be called each time there is a new GitHub commit and will post a message to +* Slack. +*/ +exports.githubWebhook = functions.https.onRequest((req, res) => { const cipher = 'sha1'; const signature = req.headers['x-hub-signature']; // TODO: Configure the `github.secret` Google Cloud environment variables. const hmac = crypto.createHmac(cipher, functions.config().github.secret) - // The JSON body is automatically parsed by Cloud Functions so we re-stringify it. - .update(JSON.stringify(req.body, null, 0)) - .digest('hex'); - const expectedSignature = `${cipher}=${hmac}`; + .update(req.body) + .digest('hex'); + const expectedSignature = `${cipher}=${hmac}`; // Check that the body of the request has been signed with the GitHub Secret. - if (secureCompare(signature, expectedSignature)) { - postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => { - return res.end(); - }).catch(error => { - console.error(error); - return res.status(500).send('Something went wrong while posting the message to Slack.'); - }); - } - console.error('x-hub-signature', signature, 'did not match', expectedSignature); - return res.status(403).send('Your x-hub-signature\'s bad and you should feel bad!'); - + if (!secureCompare(signature, expectedSignature)) { + console.error('x-hub-signature', signature, 'did not match', expectedSignature); + return res.status(403).send('Your x-hub-signature\'s bad and you should feel bad!'); + } + return postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => { + return res.end(); + }).catch(error => { + console.error(error); + return res.status(500).send('Something went wrong while posting the message to Slack.'); + }); }); /** - * Post a message to Slack about the new GitHub commit. - */ - function postToSlack(url, commits, repo) { +* Post a message to Slack about the new GitHub commit. +*/ +function postToSlack(url, commits, repo) { return rp({ method: 'POST', // TODO: Configure the `slack.webhook_url` Google Cloud environment variables. diff --git a/google-sheet-sync/functions/index.js b/google-sheet-sync/functions/index.js index f05bd0f090..8b1c49865f 100644 --- a/google-sheet-sync/functions/index.js +++ b/google-sheet-sync/functions/index.js @@ -1,19 +1,19 @@ /** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2017 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; // Sample trigger function that copies new Firebase data to a Google Sheet @@ -26,8 +26,8 @@ admin.initializeApp(functions.config().firebase); const db = admin.database(); // TODO: Use firebase functions:config:set to configure your googleapi object: -// googleapi.client_id = Google API client ID, -// googleapi.client_secret = client secret, and +// googleapi.client_id = Google API client ID, +// googleapi.client_secret = client secret, and // googleapi.sheet_id = Google Sheet id (long string in middle of sheet URL) const CONFIG_CLIENT_ID = functions.config().googleapi.client_id; const CONFIG_CLIENT_SECRET = functions.config().googleapi.client_secret; @@ -56,7 +56,7 @@ exports.authgoogleapi = functions.https.onRequest((req, res) => scope: SCOPES, prompt: 'consent' })) - ); +); // setup for OauthCallback const DB_TOKEN_PATH = '/api_tokens'; @@ -68,12 +68,13 @@ exports.oauthcallback = functions.https.onRequest((req, res) => { functionsOauthClient.getToken(code, (err, tokens) => { // Now tokens contains an access_token and an optional refresh_token. Save them. if (err) { - res.status(400).send(err); - return null; + return res.status(400).send(err); } - return db.ref(DB_TOKEN_PATH).set(tokens).then( - () => res.status(200).send('App successfully configured with new Credentials. ' + - 'You can now close this page.')); + return db.ref(DB_TOKEN_PATH).set(tokens) + .then(() => { + return res.status(200).send('App successfully configured with new Credentials. ' + + 'You can now close this page.'); + }); }); }); @@ -90,7 +91,8 @@ exports.appendrecordtospreadsheet = functions.database.ref(`${CONFIG_DATA_PATH}/ values: [[newRecord.firstColumn, newRecord.secondColumn, newRecord.thirdColumn]] } }); - }); + } +); // accepts an append request, returns a Promise to append it, enriching it with auth function appendPromise(requestWithoutAuth) { @@ -102,11 +104,11 @@ function appendPromise(requestWithoutAuth) { return sheets.spreadsheets.values.append(request, (err, response) => { if (err) { console.log(`The API returned an error: ${err}`); - return err; + return reject(err); } return resolve(response); }); - }).catch((err) => reject(err)); + }); }); } diff --git a/image-sharp/functions/index.js b/image-sharp/functions/index.js index c635a4af9b..1a71b252eb 100644 --- a/image-sharp/functions/index.js +++ b/image-sharp/functions/index.js @@ -1,33 +1,33 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for t`he specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for t`he specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const gcs = require('@google-cloud/storage')(); - const path = require('path'); - const sharp = require('sharp'); +const functions = require('firebase-functions'); +const gcs = require('@google-cloud/storage')(); +const path = require('path'); +const sharp = require('sharp'); - const THUMB_MAX_WIDTH = 200; - const THUMB_MAX_HEIGHT = 200; +const THUMB_MAX_WIDTH = 200; +const THUMB_MAX_HEIGHT = 200; /** - * When an image is uploaded in the Storage bucket We generate a thumbnail automatically using - * Sharp. - */ - exports.generateThumbnail = functions.storage.object().onChange(event => { +* When an image is uploaded in the Storage bucket We generate a thumbnail automatically using +* Sharp. +*/ +exports.generateThumbnail = functions.storage.object().onChange(event => { const object = event.data; // The Storage object. const fileBucket = object.bucket; // The Storage bucket that contains the file. @@ -78,14 +78,15 @@ // Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream const pipeline = sharp(); pipeline - .resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT) - .max() - .pipe(thumbnailUploadStream); + .resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT) + .max() + .pipe(thumbnailUploadStream); bucket.file(filePath).createReadStream().pipe(pipeline); const streamAsPromise = new Promise((resolve, reject) => thumbnailUploadStream.on('finish', resolve).on('error', reject)); + return streamAsPromise.then(() => { return console.log('Thumbnail created successfully'); }); diff --git a/instagram-auth/functions/index.js b/instagram-auth/functions/index.js index 0cfcbe074e..9b07b5112d 100644 --- a/instagram-auth/functions/index.js +++ b/instagram-auth/functions/index.js @@ -1,23 +1,23 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const cookieParser = require('cookie-parser'); - const crypto = require('crypto'); +const functions = require('firebase-functions'); +const cookieParser = require('cookie-parser'); +const crypto = require('crypto'); // Firebase Setup const admin = require('firebase-admin'); @@ -31,9 +31,9 @@ const OAUTH_REDIRECT_URI = `https://${process.env.GCLOUD_PROJECT}.firebaseapp.co const OAUTH_SCOPES = 'basic'; /** - * Creates a configured simple-oauth2 client for Instagram. - */ - function instagramOAuth2Client() { +* Creates a configured simple-oauth2 client for Instagram. +*/ +function instagramOAuth2Client() { // Instagram OAuth 2 setup // TODO: Configure the `instagram.client_id` and `instagram.client_secret` Google Cloud environment variables. const credentials = { @@ -50,10 +50,10 @@ const OAUTH_SCOPES = 'basic'; } /** - * Redirects the User to the Instagram authentication consent screen. Also the 'state' cookie is set for later state - * verification. - */ - exports.redirect = functions.https.onRequest((req, res) => { +* Redirects the User to the Instagram authentication consent screen. Also the 'state' cookie is set for later state +* verification. +*/ +exports.redirect = functions.https.onRequest((req, res) => { const oauth2 = instagramOAuth2Client(); cookieParser()(req, res, () => { @@ -71,12 +71,12 @@ const OAUTH_SCOPES = 'basic'; }); /** - * Exchanges a given Instagram auth code passed in the 'code' URL query parameter for a Firebase auth token. - * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. - * The Firebase custom auth token, display name, photo URL and Instagram acces token are sent back in a JSONP callback - * function with function name defined by the 'callback' query parameter. - */ - exports.token = functions.https.onRequest((req, res) => { +* Exchanges a given Instagram auth code passed in the 'code' URL query parameter for a Firebase auth token. +* The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. +* The Firebase custom auth token, display name, photo URL and Instagram acces token are sent back in a JSONP callback +* function with function name defined by the 'callback' query parameter. +*/ +exports.token = functions.https.onRequest((req, res) => { const oauth2 = instagramOAuth2Client(); try { @@ -96,31 +96,31 @@ const OAUTH_SCOPES = 'basic'; }).then(results => { console.log('Auth code exchange result received:', results); - // We have an Instagram access token and the user identity now. - const accessToken = results.access_token; - const instagramUserID = results.user.id; - const profilePic = results.user.profile_picture; - const userName = results.user.full_name; + // We have an Instagram access token and the user identity now. + const accessToken = results.access_token; + const instagramUserID = results.user.id; + const profilePic = results.user.profile_picture; + const userName = results.user.full_name; - // Create a Firebase account and get the Custom Auth Token. - return createFirebaseAccount(instagramUserID, userName, profilePic, accessToken) - }).then(firebaseToken => { - // Serve an HTML page that signs the user in and updates the user profile. - return res.jsonp({token: firebaseToken}); - }); - } catch (error) { - return res.jsonp({error: error.toString}); - } - }); + // Create a Firebase account and get the Custom Auth Token. + return createFirebaseAccount(instagramUserID, userName, profilePic, accessToken) + }).then(firebaseToken => { + // Serve an HTML page that signs the user in and updates the user profile. + return res.jsonp({token: firebaseToken}); + }); + } catch (error) { + return res.jsonp({error: error.toString}); + } +}); /** - * Creates a Firebase account with the given user profile and returns a custom auth token allowing - * signing-in this account. - * Also saves the accessToken to the datastore at /instagramAccessToken/$uid - * - * @returns {Promise} The Firebase custom auth token in a promise. - */ - function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) { +* Creates a Firebase account with the given user profile and returns a custom auth token allowing +* signing-in this account. +* Also saves the accessToken to the datastore at /instagramAccessToken/$uid +* +* @returns {Promise} The Firebase custom auth token in a promise. +*/ +function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) { // The UID we'll assign to the user. const uid = `instagram:${instagramID}`; diff --git a/line-auth/functions/index.js b/line-auth/functions/index.js index a1a7434ffc..8069b9ea7b 100644 --- a/line-auth/functions/index.js +++ b/line-auth/functions/index.js @@ -1,19 +1,19 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; // Modules imports const functions = require('firebase-functions'); @@ -39,12 +39,12 @@ function generateLineApiRequest(apiEndpoint, lineAccessToken) { } /** - * Look up Firebase user based on LINE's mid. If the Firebase user does not exist, - + fetch LINE profile and create a new Firebase user with it. - * - * @returns {Promise} The Firebase user record in a promise. - */ - function getFirebaseUser(lineMid, lineAccessToken) { +* Look up Firebase user based on LINE's mid. If the Firebase user does not exist, ++ fetch LINE profile and create a new Firebase user with it. +* +* @returns {Promise} The Firebase user record in a promise. +*/ +function getFirebaseUser(lineMid, lineAccessToken) { // Generate Firebase user's uid based on LINE's mid const firebaseUid = `line:${lineMid}`; @@ -57,41 +57,41 @@ function generateLineApiRequest(apiEndpoint, lineAccessToken) { return rp(getProfileOptions); } // If error other than auth/user-not-found occurred, fail the whole login process - throw error; + return Promise.reject(error); }).then(response => { - // Parse user profile from LINE's get user profile API response - const displayName = response.displayName; - const photoURL = response.pictureUrl; + // Parse user profile from LINE's get user profile API response + const displayName = response.displayName; + const photoURL = response.pictureUrl; - console.log('Create new Firebase user for LINE user mid = "', lineMid,'"'); - // Create a new Firebase user with LINE profile and return it - return admin.auth().createUser({ - uid: firebaseUid, - displayName: displayName, - photoURL: photoURL - }); - }); + console.log('Create new Firebase user for LINE user mid = "', lineMid,'"'); + // Create a new Firebase user with LINE profile and return it + return admin.auth().createUser({ + uid: firebaseUid, + displayName: displayName, + photoURL: photoURL + }); + }); } /** - * Verify LINE access token and return a custom auth token allowing signing-in - * the corresponding Firebase account. - * - * Here are the steps involved: - * 1. Verify with LINE server that a LINE access token is valid - * 2. Check if a Firebase user corresponding to the LINE user already existed. - * If not, fetch user profile from LINE and generate a corresponding Firebase user. - * 3. Return a custom auth token allowing signing-in the Firebase account. - * - * @returns {Promise} The Firebase custom auth token in a promise. - */ - function verifyLineToken(lineAccessToken) { +* Verify LINE access token and return a custom auth token allowing signing-in +* the corresponding Firebase account. +* +* Here are the steps involved: +* 1. Verify with LINE server that a LINE access token is valid +* 2. Check if a Firebase user corresponding to the LINE user already existed. +* If not, fetch user profile from LINE and generate a corresponding Firebase user. +* 3. Return a custom auth token allowing signing-in the Firebase account. +* +* @returns {Promise} The Firebase custom auth token in a promise. +*/ +function verifyLineToken(lineAccessToken) { // Send request to LINE server for access token verification const verifyTokenOptions = generateLineApiRequest('https://api.line.me/v1/oauth/verify', lineAccessToken); // STEP 1: Verify with LINE server that a LINE access token is valid return rp(verifyTokenOptions) - .then(response => { + .then(response => { // Verify the token’s channelId match with my channelId to prevent spoof attack // As LINE's Get user profiles API response doesn't include channelID, // you must not skip this step to make sure that the LINE access token is indeed @@ -104,15 +104,13 @@ function generateLineApiRequest(apiEndpoint, lineAccessToken) { // STEP 2: Access token validation succeeded, so look up the corresponding Firebase user const lineMid = response.mid; return getFirebaseUser(lineMid, lineAccessToken); - }) - .then(userRecord => { + }).then(userRecord => { // STEP 3: Generate Firebase Custom Auth Token return admin.auth().createCustomToken(userRecord.uid); - }) - .then(token => { - console.log('Created Custom token for UID "', userRecord.uid, '" Token:', token); - return token; - }); + }).then(token => { + console.log('Created Custom token for UID "', userRecord.uid, '" Token:', token); + return token; + }); } // Verify LINE token and exchange for Firebase Custom Auth token @@ -128,12 +126,12 @@ exports.verifyToken = functions.https.onRequest((req, res) => { // Verify LINE access token with LINE server then generate Firebase Custom Auth token return verifyLineToken(reqToken) - .then(customAuthToken => { - const ret = { - firebase_token: customAuthToken - }; - return res.status(200).send(ret); - }).catch(err => { + .then(customAuthToken => { + const ret = { + firebase_token: customAuthToken + }; + return res.status(200).send(ret); + }).catch(err => { // If LINE access token verification failed, return error response to client const ret = { error_message: 'Authentication error: Cannot verify access token.' From 2a532353805d0988309da6ec1b34a01444147f10 Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Mon, 8 Jan 2018 16:01:44 -0800 Subject: [PATCH 04/16] fixed spacing errors from isomorphic-react-app function sample onwards --- isomorphic-react-app/functions/index.js | 38 ++--- limit-children/functions/index.js | 4 +- linkedin-auth/functions/index.js | 85 ++++++----- message-translation/functions/index.js | 38 ++--- minimal-webhook/functions/index.js | 34 ++--- moderate-images/functions/index.js | 60 ++++---- paypal/functions/index.js | 138 +++++++++--------- presence-firestore/functions/index.js | 81 +++++----- quickstarts/email-users/functions/index.js | 54 +++---- quickstarts/thumbnails/functions/index.js | 42 +++--- .../uppercase-firestore/functions/index.js | 61 ++++---- quickstarts/uppercase/functions/index.js | 61 ++++---- spotify-auth/functions/index.js | 78 +++++----- stripe/functions/index.js | 66 ++++----- template-handlebars/functions/firebaseUser.js | 46 +++--- text-moderation/functions/index.js | 67 +++++---- url-shortener/functions/index.js | 38 ++--- username-password-auth/functions/index.js | 58 ++++---- 18 files changed, 522 insertions(+), 527 deletions(-) diff --git a/isomorphic-react-app/functions/index.js b/isomorphic-react-app/functions/index.js index 3bf78a517c..98230c1de5 100644 --- a/isomorphic-react-app/functions/index.js +++ b/isomorphic-react-app/functions/index.js @@ -1,24 +1,24 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ - const functions = require('firebase-functions'); - const firebase = require('firebase'); - const app = require('express')(); - const React = require('react'); - const ReactDOMServer = require('react-dom/server'); +const functions = require('firebase-functions'); +const firebase = require('firebase'); +const app = require('express')(); +const React = require('react'); +const ReactDOMServer = require('react-dom/server'); // React App const ServerApp = React.createFactory(require('./build/server.bundle.js').default); diff --git a/limit-children/functions/index.js b/limit-children/functions/index.js index 82ff1b32c4..058f210c52 100644 --- a/limit-children/functions/index.js +++ b/limit-children/functions/index.js @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - 'use strict'; +'use strict'; - const functions = require('firebase-functions'); +const functions = require('firebase-functions'); // Max number of lines of the chat history. const MAX_LOG_COUNT = 5; diff --git a/linkedin-auth/functions/index.js b/linkedin-auth/functions/index.js index 3b530c321b..73c0621e7b 100644 --- a/linkedin-auth/functions/index.js +++ b/linkedin-auth/functions/index.js @@ -1,23 +1,23 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const cookieParser = require('cookie-parser'); - const crypto = require('crypto'); +const functions = require('firebase-functions'); +const cookieParser = require('cookie-parser'); +const crypto = require('crypto'); // Firebase Setup const admin = require('firebase-admin'); @@ -30,9 +30,9 @@ admin.initializeApp({ const OAUTH_SCOPES = ['r_basicprofile', 'r_emailaddress']; /** - * Creates a configured LinkedIn API Client instance. - */ - function linkedInClient() { +* Creates a configured LinkedIn API Client instance. +*/ +function linkedInClient() { // LinkedIn OAuth 2 setup // TODO: Configure the `linkedin.client_id` and `linkedin.client_secret` Google Cloud environment variables. return require('node-linkedin')( @@ -42,10 +42,10 @@ const OAUTH_SCOPES = ['r_basicprofile', 'r_emailaddress']; } /** - * Redirects the User to the LinkedIn authentication consent screen. ALso the 'state' cookie is set for later state - * verification. - */ - exports.redirect = functions.https.onRequest((req, res) => { +* Redirects the User to the LinkedIn authentication consent screen. ALso the 'state' cookie is set for later state +* verification. +*/ +exports.redirect = functions.https.onRequest((req, res) => { const Linkedin = linkedInClient(); cookieParser()(req, res, () => { @@ -57,12 +57,12 @@ const OAUTH_SCOPES = ['r_basicprofile', 'r_emailaddress']; }); /** - * Exchanges a given LinkedIn auth code passed in the 'code' URL query parameter for a Firebase auth token. - * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. - * The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the - * 'callback' query parameter. - */ - exports.token = functions.https.onRequest((req, res) => { +* Exchanges a given LinkedIn auth code passed in the 'code' URL query parameter for a Firebase auth token. +* The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. +* The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the +* 'callback' query parameter. +*/ +exports.token = functions.https.onRequest((req, res) => { const Linkedin = linkedInClient(); try { @@ -96,9 +96,9 @@ const OAUTH_SCOPES = ['r_basicprofile', 'r_emailaddress']; // Create a Firebase account and get the Custom Auth Token. return createFirebaseAccount(linkedInUserID, userName, profilePic, email, accessToken).then( firebaseToken => { - // Serve an HTML page that signs the user in and updates the user profile. - return res.jsonp({token: firebaseToken}); - }); + // Serve an HTML page that signs the user in and updates the user profile. + return res.jsonp({token: firebaseToken}); + }); }); }); }); @@ -108,19 +108,18 @@ const OAUTH_SCOPES = ['r_basicprofile', 'r_emailaddress']; }); /** - * Creates a Firebase account with the given user profile and returns a custom auth token allowing - * signing-in this account. - * Also saves the accessToken to the datastore at /linkedInAccessToken/$uid - * - * @returns {Promise} The Firebase custom auth token in a promise. - */ - function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessToken) { +* Creates a Firebase account with the given user profile and returns a custom auth token allowing +* signing-in this account. +* Also saves the accessToken to the datastore at /linkedInAccessToken/$uid +* +* @returns {Promise} The Firebase custom auth token in a promise. +*/ +function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessToken) { // The UID we'll assign to the user. const uid = `linkedin:${linkedinID}`; // Save the access token tot he Firebase Realtime Database. - const databaseTask = admin.database().ref(`/linkedInAccessToken/${uid}`) - .set(accessToken); + const databaseTask = admin.database().ref(`/linkedInAccessToken/${uid}`).set(accessToken); // Create or update the user account. const userCreationTask = admin.auth().updateUser(uid, { diff --git a/message-translation/functions/index.js b/message-translation/functions/index.js index 53095a3efa..8722ee2f11 100644 --- a/message-translation/functions/index.js +++ b/message-translation/functions/index.js @@ -1,24 +1,24 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const admin = require('firebase-admin'); - admin.initializeApp(functions.config().firebase); - const request = require('request-promise'); +const functions = require('firebase-functions'); +const admin = require('firebase-admin'); +admin.initializeApp(functions.config().firebase); +const request = require('request-promise'); // List of output languages. const LANGUAGES = ['en', 'es', 'de', 'fr', 'sv', 'ga', 'it', 'jp']; diff --git a/minimal-webhook/functions/index.js b/minimal-webhook/functions/index.js index 505e12a956..559eb21116 100644 --- a/minimal-webhook/functions/index.js +++ b/minimal-webhook/functions/index.js @@ -1,22 +1,22 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const request = require('request-promise'); +const functions = require('firebase-functions'); +const request = require('request-promise'); // This is the URL that we will callback and send the content of the updated data node. // As an example we're using a Request Bin from http://requestb.in diff --git a/moderate-images/functions/index.js b/moderate-images/functions/index.js index f7b1425c9a..7725ba896b 100644 --- a/moderate-images/functions/index.js +++ b/moderate-images/functions/index.js @@ -1,34 +1,34 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for t`he specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for t`he specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const mkdirp = require('mkdirp-promise'); - const gcs = require('@google-cloud/storage')(); - const vision = require('@google-cloud/vision')(); - const spawn = require('child-process-promise').spawn; - const path = require('path'); - const os = require('os'); - const fs = require('fs'); +const functions = require('firebase-functions'); +const mkdirp = require('mkdirp-promise'); +const gcs = require('@google-cloud/storage')(); +const vision = require('@google-cloud/vision')(); +const spawn = require('child-process-promise').spawn; +const path = require('path'); +const os = require('os'); +const fs = require('fs'); /** - * When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision - * API and if it is we blur it using ImageMagick. - */ - exports.blurOffensiveImages = functions.storage.object().onChange(event => { +* When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision +* API and if it is we blur it using ImageMagick. +*/ +exports.blurOffensiveImages = functions.storage.object().onChange(event => { const object = event.data; const file = gcs.bucket(object.bucket).file(object.name); @@ -50,9 +50,9 @@ }); /** - * Blurs the given image located in the given bucket using ImageMagick. - */ - function blurImage(filePath, bucketName, metadata) { +* Blurs the given image located in the given bucket using ImageMagick. +*/ +function blurImage(filePath, bucketName, metadata) { const tempLocalFile = path.join(os.tmpdir(), filePath); const tempLocalDir = path.dirname(tempLocalFile); const bucket = gcs.bucket(bucketName); diff --git a/paypal/functions/index.js b/paypal/functions/index.js index bf137b24b6..9b6cfc2e35 100644 --- a/paypal/functions/index.js +++ b/paypal/functions/index.js @@ -1,21 +1,21 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); +const functions = require('firebase-functions'); // CORS Express middleware to enable CORS Requests. const cors = require('cors')({origin: true}); const paypal = require('paypal-rest-sdk'); @@ -25,66 +25,66 @@ admin.initializeApp(functions.config().firebase); // Configure your environment paypal.configure({ mode: 'sandbox', // sandbox or live - client_id: functions.config().paypal.client_id, // run: firebase functions:config:set paypal.client_id="yourPaypalClientID" + client_id: functions.config().paypal.client_id, // run: firebase functions:config:set paypal.client_id="yourPaypalClientID" client_secret: functions.config().paypal.client_secret // run: firebase functions:config:set paypal.client_secret="yourPaypalClientSecret" }); /** - * Expected in the body the amount - * Set up the payment information object - * Initialize the payment and redirect the user to the PayPal payment page - */ - exports.pay = functions.https.onRequest((req, res) => { - // 1.Set up a payment information object, Nuild PayPal payment request - const payReq = JSON.stringify({ - intent: 'sale', - payer: { - payment_method: 'paypal' +* Expected in the body the amount +* Set up the payment information object +* Initialize the payment and redirect the user to the PayPal payment page +*/ +exports.pay = functions.https.onRequest((req, res) => { + // 1.Set up a payment information object, Nuild PayPal payment request + const payReq = JSON.stringify({ + intent: 'sale', + payer: { + payment_method: 'paypal' + }, + redirect_urls: { + return_url: `${req.protocol}://${req.get('host')}/process`, + cancel_url: `${req.protocol}://${req.get('host')}/cancel` + }, + transactions: [{ + amount: { + total: req.body.price, + currency: 'USD' }, - redirect_urls: { - return_url: `${req.protocol}://${req.get('host')}/process`, - cancel_url: `${req.protocol}://${req.get('host')}/cancel` - }, - transactions: [{ - amount: { - total: req.body.price, - currency: 'USD' - }, - // This is the payment transaction description. Maximum length: 127 - description: req.body.uid, // req.body.id - // reference_id string .Optional. The merchant-provided ID for the purchase unit. Maximum length: 256. - // reference_id: req.body.uid, - custom: req.body.uid, - // soft_descriptor: req.body.uid - // "invoice_number": req.body.uid,A - }] + // This is the payment transaction description. Maximum length: 127 + description: req.body.uid, // req.body.id + // reference_id string .Optional. The merchant-provided ID for the purchase unit. Maximum length: 256. + // reference_id: req.body.uid, + custom: req.body.uid, + // soft_descriptor: req.body.uid + // "invoice_number": req.body.uid,A + }] + }); + // 2.Initialize the payment and redirect the user. + paypal.payment.create(payReq, (error, payment) => { + const links = {}; + if (error) { + console.error(error); + res.status('500').end(); + } else { + // Capture HATEOAS links + payment.links.forEach((linkObj) => { + links[linkObj.rel] = { + href: linkObj.href, + method: linkObj.method + }; }); - // 2.Initialize the payment and redirect the user. - paypal.payment.create(payReq, (error, payment) => { - const links = {}; - if (error) { - console.error(error); - res.status('500').end(); + // If redirect url present, redirect user + if (links.hasOwnProperty('approval_url')) { + // REDIRECT USER TO links['approval_url'].href + console.info(links.approval_url.href); + // res.json({"approval_url":links.approval_url.href}); + res.redirect(302, links.approval_url.href); } else { - // Capture HATEOAS links - payment.links.forEach((linkObj) => { - links[linkObj.rel] = { - href: linkObj.href, - method: linkObj.method - }; - }); - // If redirect url present, redirect user - if (links.hasOwnProperty('approval_url')) { - // REDIRECT USER TO links['approval_url'].href - console.info(links.approval_url.href); - // res.json({"approval_url":links.approval_url.href}); - res.redirect(302, links.approval_url.href); - } else { - console.error('no redirect URI present'); - res.status('500').end(); - } - } - }); + console.error('no redirect URI present'); + res.status('500').end(); + } + } }); +}); // 3.Complete the payment. Use the payer and payment IDs provided in the query string following the redirect. exports.process = functions.https.onRequest((req, res) => { diff --git a/presence-firestore/functions/index.js b/presence-firestore/functions/index.js index ab0c6a8afe..060fcc23eb 100644 --- a/presence-firestore/functions/index.js +++ b/presence-firestore/functions/index.js @@ -1,18 +1,18 @@ /** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the 'License'); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an 'AS IS' BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +* Copyright 2017 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the 'License'); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an 'AS IS' BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ // [START presence_sync_function] const functions = require('firebase-functions'); @@ -27,31 +27,30 @@ const firestore = admin.firestore(); // Create a new function which is triggered on changes to /status/{uid} // Note: This is a Realtime Database trigger, *not* Cloud Firestore. -exports.onUserStatusChanged = functions.database -.ref('/status/{uid}').onUpdate(event => { - // Get the data written to Realtime Database - const eventStatus = event.data.val(); - - // Then use other event data to create a reference to the - // corresponding Firestore document. - const userStatusFirestoreRef = firestore.doc(`status/${event.params.uid}`); - - // It is likely that the Realtime Database change that triggered - // this event has already been overwritten by a fast change in - // online / offline status, so we'll re-read the current data - // and compare the timestamps. - return event.data.ref.once('value').then(statusSnapshot => { - const status = statusSnapshot.val(); - console.log(status, eventStatus); - // If the current timestamp for this data is newer than - // the data that triggered this event, we exit this function. - if (status.last_changed > eventStatus.last_changed) return null; - - // Otherwise, we convert the last_changed field to a Date - eventStatus.last_changed = new Date(eventStatus.last_changed); - - // ... and write it to Firestore. - return userStatusFirestoreRef.set(eventStatus); - }); - }); +exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate(event => { + // Get the data written to Realtime Database + const eventStatus = event.data.val(); + + // Then use other event data to create a reference to the + // corresponding Firestore document. + const userStatusFirestoreRef = firestore.doc(`status/${event.params.uid}`); + + // It is likely that the Realtime Database change that triggered + // this event has already been overwritten by a fast change in + // online / offline status, so we'll re-read the current data + // and compare the timestamps. + return event.data.ref.once('value').then(statusSnapshot => { + const status = statusSnapshot.val(); + console.log(status, eventStatus); + // If the current timestamp for this data is newer than + // the data that triggered this event, we exit this function. + if (status.last_changed > eventStatus.last_changed) return null; + + // Otherwise, we convert the last_changed field to a Date + eventStatus.last_changed = new Date(eventStatus.last_changed); + + // ... and write it to Firestore. + return userStatusFirestoreRef.set(eventStatus); + }); +}); // [END presence_sync_function] diff --git a/quickstarts/email-users/functions/index.js b/quickstarts/email-users/functions/index.js index 2b647c0ecf..4445ed68ad 100644 --- a/quickstarts/email-users/functions/index.js +++ b/quickstarts/email-users/functions/index.js @@ -1,22 +1,22 @@ /** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2015 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const nodemailer = require('nodemailer'); +const functions = require('firebase-functions'); +const nodemailer = require('nodemailer'); // Configure the email transport using the default SMTP transport and a GMail account. // For Gmail, enable these: // 1. https://www.google.com/settings/security/lesssecureapps @@ -39,11 +39,11 @@ const APP_NAME = 'Cloud Storage for Firebase quickstart'; // [START sendWelcomeEmail] /** - * Sends a welcome email to new user. - */ +* Sends a welcome email to new user. +*/ // [START onCreateTrigger] exports.sendWelcomeEmail = functions.auth.user().onCreate(event => { -// [END onCreateTrigger] + // [END onCreateTrigger] // [START eventAttributes] const user = event.data; // The Firebase user. @@ -57,17 +57,17 @@ exports.sendWelcomeEmail = functions.auth.user().onCreate(event => { // [START sendByeEmail] /** - * Send an account deleted email confirmation to users who delete their accounts. - */ +* Send an account deleted email confirmation to users who delete their accounts. +*/ // [START onDeleteTrigger] exports.sendByeEmail = functions.auth.user().onDelete(event => { -// [END onDeleteTrigger] -const user = event.data; + // [END onDeleteTrigger] + const user = event.data; -const email = user.email; -const displayName = user.displayName; + const email = user.email; + const displayName = user.displayName; -return sendGoodbyEmail(email, displayName); + return sendGoodbyEmail(email, displayName); }); // [END sendByeEmail] diff --git a/quickstarts/thumbnails/functions/index.js b/quickstarts/thumbnails/functions/index.js index 77791e43e0..28d5a3886c 100644 --- a/quickstarts/thumbnails/functions/index.js +++ b/quickstarts/thumbnails/functions/index.js @@ -1,19 +1,19 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for t`he specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for t`he specific language governing permissions and +* limitations under the License. +*/ +'use strict'; // [START import] const functions = require('firebase-functions'); @@ -26,12 +26,12 @@ const fs = require('fs'); // [START generateThumbnail] /** - * When an image is uploaded in the Storage bucket We generate a thumbnail automatically using - * ImageMagick. - */ +* When an image is uploaded in the Storage bucket We generate a thumbnail automatically using +* ImageMagick. +*/ // [START generateThumbnailTrigger] exports.generateThumbnail = functions.storage.object().onChange(event => { -// [END generateThumbnailTrigger] + // [END generateThumbnailTrigger] // [START eventAttributes] const object = event.data; // The Storage object. @@ -89,8 +89,8 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); // Uploading the thumbnail. return bucket.upload(tempFilePath, { destination: thumbFilePath, metadata: metadata }); - // Once the thumbnail has been uploaded delete the local file to free up disk space. -}).then(() => fs.unlinkSync(tempFilePath)); + // Once the thumbnail has been uploaded delete the local file to free up disk space. + }).then(() => fs.unlinkSync(tempFilePath)); // [END thumbnailGeneration] }); // [END generateThumbnail] diff --git a/quickstarts/uppercase-firestore/functions/index.js b/quickstarts/uppercase-firestore/functions/index.js index a106bbdb2f..99658ee726 100644 --- a/quickstarts/uppercase-firestore/functions/index.js +++ b/quickstarts/uppercase-firestore/functions/index.js @@ -1,26 +1,26 @@ /** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the 'License'); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an 'AS IS' BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2017 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the 'License'); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an 'AS IS' BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; // [START all] // [START import] // The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers. const functions = require('firebase-functions'); -// The Firebase Admin SDK to access the Firebase Realtime Database. +// The Firebase Admin SDK to access the Firebase Realtime Database. const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); // [END import] @@ -30,7 +30,7 @@ admin.initializeApp(functions.config().firebase); // Realtime Database under the path /messages/:documentId/original // [START addMessageTrigger] exports.addMessage = functions.https.onRequest((req, res) => { -// [END addMessageTrigger] + // [END addMessageTrigger] // Grab the text parameter. const original = req.query.text; // [START adminSdkAdd] @@ -47,20 +47,19 @@ exports.addMessage = functions.https.onRequest((req, res) => { // Listens for new messages added to /messages/:documentId/original and creates an // uppercase version of the message to /messages/:documentId/uppercase // [START makeUppercaseTrigger] -exports.makeUppercase = functions.firestore.document('/messages/{documentId}') -.onCreate(event => { -// [END makeUppercaseTrigger] - // [START makeUppercaseBody] +exports.makeUppercase = functions.firestore.document('/messages/{documentId}').onCreate(event => { + // [END makeUppercaseTrigger] + // [START makeUppercaseBody] - // Grab the current value of what was written to the Realtime Database. - const original = event.data.data().original; - console.log('Uppercasing', event.params.documentId, original); - const uppercase = original.toUpperCase(); - // You must return a Promise when performing asynchronous tasks inside a Functions such as - // writing to the Firebase Realtime Database. - // Setting an 'uppercase' sibling in the Realtime Database returns a Promise. - return event.data.ref.set({uppercase}, {merge: true}); - // [END makeUppercaseBody] - }); + // Grab the current value of what was written to the Realtime Database. + const original = event.data.data().original; + console.log('Uppercasing', event.params.documentId, original); + const uppercase = original.toUpperCase(); + // You must return a Promise when performing asynchronous tasks inside a Functions such as + // writing to the Firebase Realtime Database. + // Setting an 'uppercase' sibling in the Realtime Database returns a Promise. + return event.data.ref.set({uppercase}, {merge: true}); + // [END makeUppercaseBody] +}); // [END makeUppercase] // [END all] diff --git a/quickstarts/uppercase/functions/index.js b/quickstarts/uppercase/functions/index.js index 0c0b89e3d8..74cd077169 100644 --- a/quickstarts/uppercase/functions/index.js +++ b/quickstarts/uppercase/functions/index.js @@ -1,26 +1,26 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; // [START all] // [START import] // The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers. const functions = require('firebase-functions'); -// The Firebase Admin SDK to access the Firebase Realtime Database. +// The Firebase Admin SDK to access the Firebase Realtime Database. const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); // [END import] @@ -30,7 +30,7 @@ admin.initializeApp(functions.config().firebase); // Realtime Database under the path /messages/:pushId/original // [START addMessageTrigger] exports.addMessage = functions.https.onRequest((req, res) => { -// [END addMessageTrigger] + // [END addMessageTrigger] // Grab the text parameter. const original = req.query.text; // [START adminSdkPush] @@ -47,19 +47,18 @@ exports.addMessage = functions.https.onRequest((req, res) => { // Listens for new messages added to /messages/:pushId/original and creates an // uppercase version of the message to /messages/:pushId/uppercase // [START makeUppercaseTrigger] -exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') -.onWrite(event => { -// [END makeUppercaseTrigger] - // [START makeUppercaseBody] - // Grab the current value of what was written to the Realtime Database. - const original = event.data.val(); - console.log('Uppercasing', event.params.pushId, original); - const uppercase = original.toUpperCase(); - // You must return a Promise when performing asynchronous tasks inside a Functions such as - // writing to the Firebase Realtime Database. - // Setting an "uppercase" sibling in the Realtime Database returns a Promise. - return event.data.ref.parent.child('uppercase').set(uppercase); - // [END makeUppercaseBody] - }); +exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onWrite(event => { + // [END makeUppercaseTrigger] + // [START makeUppercaseBody] + // Grab the current value of what was written to the Realtime Database. + const original = event.data.val(); + console.log('Uppercasing', event.params.pushId, original); + const uppercase = original.toUpperCase(); + // You must return a Promise when performing asynchronous tasks inside a Functions such as + // writing to the Firebase Realtime Database. + // Setting an "uppercase" sibling in the Realtime Database returns a Promise. + return event.data.ref.parent.child('uppercase').set(uppercase); + // [END makeUppercaseBody] +}); // [END makeUppercase] // [END all] diff --git a/spotify-auth/functions/index.js b/spotify-auth/functions/index.js index 2a536e0266..95314ddfdb 100644 --- a/spotify-auth/functions/index.js +++ b/spotify-auth/functions/index.js @@ -1,23 +1,23 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const cookieParser = require('cookie-parser'); - const crypto = require('crypto'); +const functions = require('firebase-functions'); +const cookieParser = require('cookie-parser'); +const crypto = require('crypto'); // Firebase Setup const admin = require('firebase-admin'); @@ -40,10 +40,10 @@ const Spotify = new SpotifyWebApi({ const OAUTH_SCOPES = ['user-read-email']; /** - * Redirects the User to the Spotify authentication consent screen. Also the 'state' cookie is set for later state - * verification. - */ - exports.redirect = functions.https.onRequest((req, res) => { +* Redirects the User to the Spotify authentication consent screen. Also the 'state' cookie is set for later state +* verification. +*/ +exports.redirect = functions.https.onRequest((req, res) => { cookieParser()(req, res, () => { const state = req.cookies.state || crypto.randomBytes(20).toString('hex'); console.log('Setting verification state:', state); @@ -54,12 +54,12 @@ const OAUTH_SCOPES = ['user-read-email']; }); /** - * Exchanges a given Spotify auth code passed in the 'code' URL query parameter for a Firebase auth token. - * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. - * The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the - * 'callback' query parameter. - */ - exports.token = functions.https.onRequest((req, res) => { +* Exchanges a given Spotify auth code passed in the 'code' URL query parameter for a Firebase auth token. +* The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. +* The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the +* 'callback' query parameter. +*/ +exports.token = functions.https.onRequest((req, res) => { try { cookieParser()(req, res, () => { console.log('Received verification state:', req.cookies.state); @@ -76,7 +76,7 @@ const OAUTH_SCOPES = ['user-read-email']; } console.log('Received Access Token:', data.body['access_token']); Spotify.setAccessToken(data.body['access_token']); - + Spotify.getMe((error, userResults) => { if (error) { throw error; @@ -92,9 +92,9 @@ const OAUTH_SCOPES = ['user-read-email']; // Create a Firebase account and get the Custom Auth Token. return createFirebaseAccount(spotifyUserID, userName, profilePic, email, accessToken).then( firebaseToken => { - // Serve an HTML page that signs the user in and updates the user profile. - return res.jsonp({token: firebaseToken}); - }); + // Serve an HTML page that signs the user in and updates the user profile. + return res.jsonp({token: firebaseToken}); + }); }); }); }); @@ -105,13 +105,13 @@ const OAUTH_SCOPES = ['user-read-email']; }); /** - * Creates a Firebase account with the given user profile and returns a custom auth token allowing - * signing-in this account. - * Also saves the accessToken to the datastore at /spotifyAccessToken/$uid - * - * @returns {Promise} The Firebase custom auth token in a promise. - */ - function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessToken) { +* Creates a Firebase account with the given user profile and returns a custom auth token allowing +* signing-in this account. +* Also saves the accessToken to the datastore at /spotifyAccessToken/$uid +* +* @returns {Promise} The Firebase custom auth token in a promise. +*/ +function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessToken) { // The UID we'll assign to the user. const uid = `spotify:${spotifyID}`; diff --git a/stripe/functions/index.js b/stripe/functions/index.js index 81a616d67d..e10ca768f0 100644 --- a/stripe/functions/index.js +++ b/stripe/functions/index.js @@ -1,58 +1,58 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'), - admin = require('firebase-admin'), - logging = require('@google-cloud/logging')(); +const functions = require('firebase-functions'), + admin = require('firebase-admin'), + logging = require('@google-cloud/logging')(); - admin.initializeApp(functions.config().firebase); +admin.initializeApp(functions.config().firebase); - const stripe = require('stripe')(functions.config().stripe.token), - currency = functions.config().stripe.currency || 'USD'; +const stripe = require('stripe')(functions.config().stripe.token), + currency = functions.config().stripe.currency || 'USD'; // [START chargecustomer] // Charge the Stripe customer whenever an amount is written to the Realtime database exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite(event => { const val = event.data.val(); // This onWrite will trigger whenever anything is written to the path, so - // noop if the charge was deleted, errored out, or the Stripe API returned a result (id exists) + // noop if the charge was deleted, errored out, or the Stripe API returned a result (id exists) if (val === null || val.id || val.error) return null; // Look up the Stripe customer id written in createStripeCustomer return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then(snapshot => { return snapshot.val(); }).then(customer => { - // Create a charge using the pushId as the idempotency key, protecting against double charges + // Create a charge using the pushId as the idempotency key, protecting against double charges const amount = val.amount; const idempotency_key = event.params.id; let charge = {amount, currency, customer}; if (val.source !== null) charge.source = val.source; return stripe.charges.create(charge, {idempotency_key}); }).then(response => { - // If the result is successful, write it back to the database - return event.data.adminRef.set(response); - }, error => { - // We want to capture errors and render them in a user-friendly way, while - // still logging an exception with Stackdriver - return event.data.adminRef.child('error').set(userFacingMessage(error)) - } - ).then(() => { - return reportError(error, {user: event.params.userId}); - }); + // If the result is successful, write it back to the database + return event.data.adminRef.set(response); + }, error => { + // We want to capture errors and render them in a user-friendly way, while + // still logging an exception with Stackdriver + return event.data.adminRef.child('error').set(userFacingMessage(error)) + } + ).then(() => { + return reportError(error, {user: event.params.userId}); }); +}); // [END chargecustomer]] // When a user is created, register them with Stripe diff --git a/template-handlebars/functions/firebaseUser.js b/template-handlebars/functions/firebaseUser.js index 1566e408c4..c29338fc3b 100644 --- a/template-handlebars/functions/firebaseUser.js +++ b/template-handlebars/functions/firebaseUser.js @@ -1,22 +1,22 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const admin = require('firebase-admin'); - const cookieParser = require('cookie-parser')(); +const admin = require('firebase-admin'); +const cookieParser = require('cookie-parser')(); // Express middleware that checks if a Firebase ID Tokens is passed in the `Authorization` HTTP // header or the `__session` cookie and decodes it. @@ -37,9 +37,9 @@ const validateFirebaseIdToken = (req, res, next) => { }; /** - * Returns a Promise with the Firebase ID Token if found in the Authorization or the __session cookie. - */ - function getIdTokenFromRequest(req, res) { +* Returns a Promise with the Firebase ID Token if found in the Authorization or the __session cookie. +*/ +function getIdTokenFromRequest(req, res) { if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) { console.log('Found "Authorization" header'); // Read the ID Token from the Authorization header. @@ -59,9 +59,9 @@ const validateFirebaseIdToken = (req, res, next) => { } /** - * Returns a Promise with the Decoded ID Token and adds it to req.user. - */ - function addDecodedIdTokenToRequest(idToken, req) { +* Returns a Promise with the Decoded ID Token and adds it to req.user. +*/ +function addDecodedIdTokenToRequest(idToken, req) { return admin.auth().verifyIdToken(idToken).then(decodedIdToken => { req.user = decodedIdToken; return console.log('ID Token correctly decoded', decodedIdToken); diff --git a/text-moderation/functions/index.js b/text-moderation/functions/index.js index 92579944a2..5c5b195256 100644 --- a/text-moderation/functions/index.js +++ b/text-moderation/functions/index.js @@ -1,47 +1,46 @@ /** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2016 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const capitalizeSentence = require('capitalize-sentence'); - const Filter = require('bad-words'); - const badWordsFilter = new Filter(); +const functions = require('firebase-functions'); +const capitalizeSentence = require('capitalize-sentence'); +const Filter = require('bad-words'); +const badWordsFilter = new Filter(); // Moderates messages by lowering all uppercase messages and removing swearwords. -exports.moderator = functions.database -.ref('/messages/{messageId}').onWrite(event => { +exports.moderator = functions.database.ref('/messages/{messageId}').onWrite(event => { const message = event.data.val(); if (message && !message.sanitized) { - // Retrieved the message values. - console.log('Retrieved message content: ', message); + // Retrieved the message values. + console.log('Retrieved message content: ', message); - // Run moderation checks on on the message and moderate if needed. - const moderatedMessage = moderateMessage(message.text); + // Run moderation checks on on the message and moderate if needed. + const moderatedMessage = moderateMessage(message.text); - // Update the Firebase DB with checked message. - console.log('Message has been moderated. Saving to DB: ', moderatedMessage); - return event.data.adminRef.update({ - text: moderatedMessage, - sanitized: true, - moderated: message.text !== moderatedMessage - }); - } - return null; + // Update the Firebase DB with checked message. + console.log('Message has been moderated. Saving to DB: ', moderatedMessage); + return event.data.adminRef.update({ + text: moderatedMessage, + sanitized: true, + moderated: message.text !== moderatedMessage }); + } + return null; +}); // Moderates the given message if appropriate. function moderateMessage(message) { diff --git a/url-shortener/functions/index.js b/url-shortener/functions/index.js index c4d5a371d0..b16f8ff536 100644 --- a/url-shortener/functions/index.js +++ b/url-shortener/functions/index.js @@ -1,24 +1,24 @@ /** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2017 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); - const admin = require('firebase-admin'); - admin.initializeApp(functions.config().firebase); - const request = require('request-promise'); +const functions = require('firebase-functions'); +const admin = require('firebase-admin'); +admin.initializeApp(functions.config().firebase); +const request = require('request-promise'); // Shorten URL exports.shortenUrl = functions.database.ref('/links/{linkID}').onWrite(event => { diff --git a/username-password-auth/functions/index.js b/username-password-auth/functions/index.js index 0f28dad253..3222d6239b 100644 --- a/username-password-auth/functions/index.js +++ b/username-password-auth/functions/index.js @@ -1,21 +1,21 @@ /** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for t`he specific language governing permissions and - * limitations under the License. - */ - 'use strict'; +* Copyright 2017 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for t`he specific language governing permissions and +* limitations under the License. +*/ +'use strict'; - const functions = require('firebase-functions'); +const functions = require('firebase-functions'); // CORS Express middleware to enable CORS Requests. const cors = require('cors')({ @@ -35,14 +35,14 @@ const basicAuthRequest = require('request'); /** - * Authenticate the provided credentials returning a Firebase custom auth token. - * `username` and `password` values are expected in the body of the request. - * If authentication fails return a 401 response. - * If the request is badly formed return a 400 response. - * If the request method is unsupported (not POST) return a 403 response. - * If an error occurs log the details and return a 500 response. - */ - exports.auth = functions.https.onRequest((req, res) => { +* Authenticate the provided credentials returning a Firebase custom auth token. +* `username` and `password` values are expected in the body of the request. +* If authentication fails return a 401 response. +* If the request is badly formed return a 400 response. +* If the request method is unsupported (not POST) return a 403 response. +* If an error occurs log the details and return a 500 response. +*/ +exports.auth = functions.https.onRequest((req, res) => { const handleError = (username, error) => { console.error({ User: username @@ -104,11 +104,11 @@ const basicAuthRequest = require('request'); }); /** - * Authenticate the provided credentials. - * TODO(DEVELOPER): In production you'll need to update this function so that it authenticates with your own credentials system. - * @returns {Promise} success or failure. - */ - function authenticate(username, password) { +* Authenticate the provided credentials. +* TODO(DEVELOPER): In production you'll need to update this function so that it authenticates with your own credentials system. +* @returns {Promise} success or failure. +*/ +function authenticate(username, password) { // For the purpose of this example use httpbin (https://httpbin.org) and send a basic authentication request. // (Only a password of `Testing123` will succeed) From 7d4ce943f601f2debf2615729341cf805a88087a Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Tue, 6 Feb 2018 11:48:05 -0800 Subject: [PATCH 05/16] remove ds_store --- .DS_Store | Bin 6148 -> 0 bytes .git_ignore | 1 + 2 files changed, 1 insertion(+) delete mode 100644 .DS_Store create mode 100644 .git_ignore diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 899c45fa6d2b3955d39163984f5663b4b7794b88..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%Sr=55Ukc5B3^RLaelyqe=vmj1^EF5LlnXaVm$B3@AA{EejtWTE`k@ShVGi_ z>6&Hhu)PhyR)@!1U;$uGcf^N>srkA4#4ajhL^|)d!2=F>!_)g_Qhhq%+$-$yi~-x9 z{MTXsGVJo^(^O@pfE17dQa}nwfnO-#y_Yt>PE?cvQa}oPE8yRUMtAImV`6+d7-9q< z&X^A4I%WxC^8~RMj)~0BEUCn#T8$W%bmm*t^};bR>986;te$K&p;$bf_qQmA^+ZJ} zAO(&UxXkUs`~MyN%=~{$(oPCUfq$id&DNXsimz0?b@FoFYa9KZ?lqruH?D)i5bc;4 i?U);H$IB?ny5?)1_rftT=*$P5sGkAXMJ5IQT7fT!ixnUM diff --git a/.git_ignore b/.git_ignore new file mode 100644 index 0000000000..e43b0f9889 --- /dev/null +++ b/.git_ignore @@ -0,0 +1 @@ +.DS_Store From 54ee5ebb0cd29c4d63290699264594fb194a5c58 Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Tue, 6 Feb 2018 12:09:31 -0800 Subject: [PATCH 06/16] fixed file to be eslint compliant --- ffmpeg-convert-audio/functions/index.js | 110 ++++++++++++------------ 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/ffmpeg-convert-audio/functions/index.js b/ffmpeg-convert-audio/functions/index.js index d2562c690e..9ec80dd50a 100644 --- a/ffmpeg-convert-audio/functions/index.js +++ b/ffmpeg-convert-audio/functions/index.js @@ -1,18 +1,18 @@ /** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for t`he specific language governing permissions and - * limitations under the License. - */ +* Copyright 2017 Google Inc. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for t`he specific language governing permissions and +* limitations under the License. +*/ 'use strict'; const functions = require('firebase-functions'); @@ -26,41 +26,41 @@ const ffmpeg_static = require('ffmpeg-static'); function promisifyCommand(command) { return new Promise((resolve, reject) => { command - .on('end', () => { - resolve(); - }) - .on('error', error => { - reject(error); - }) - .run(); - }); - }; + .on('end', () => { + resolve(); + }) + .on('error', error => { + reject(error); + }) + .run(); + }); +} /** - * Utility method to convert audio to mono channel using FFMPEG. +* Utility method to convert audio to mono channel using FFMPEG. */ function reencodeAsync(tempFilePath, targetTempFilePath) { return new Promise((resolve, reject) => { const command = ffmpeg(tempFilePath) - .setFfmpegPath(ffmpeg_static.path) - .audioChannels(1) - .audioFrequency(16000) - .format('flac') - .on('error', (err) => { - console.log('An error occurred: ' + err.message); - reject(); - }) - .on('end', () => { - console.log('Output audio created at', targetTempFilePath); - }) - .save(targetTempFilePath); + .setFfmpegPath(ffmpeg_static.path) + .audioChannels(1) + .audioFrequency(16000) + .format('flac') + .on('error', (err) => { + console.log('An error occurred: ' + err.message); + reject(err); + }) + .on('end', () => { + console.log('Output audio created at', targetTempFilePath); + }) + .save(targetTempFilePath); }); } /** - * When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using - * node-fluent-ffmpeg. - */ +* When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using +* node-fluent-ffmpeg. +*/ exports.generateMonoAudio = functions.storage.object().onChange(event => { const object = event.data; // The Storage object. @@ -112,26 +112,26 @@ exports.generateMonoAudio = functions.storage.object().onChange(event => { // Convert the audio to mono channel using FFMPEG. let command = ffmpeg(tempFilePath) - .setFfmpegPath(ffmpeg_static.path) - .audioChannels(1) - .audioFrequency(16000) - .format('flac') - .output(targetTempFilePath); + .setFfmpegPath(ffmpeg_static.path) + .audioChannels(1) + .audioFrequency(16000) + .format('flac') + .output(targetTempFilePath); command = promisifyCommand(command); - return command.then(() => { - console.log('Output audio created at', targetTempFilePath); - // Uploading the audio. - return bucket.upload(targetTempFilePath, { destination: targetStorageFilePath }).then(() => { - console.log('Output audio uploaded to', targetStorageFilePath); + return command + }).then(() => { + console.log('Output audio created at', targetTempFilePath); + // Uploading the audio. + return bucket.upload(targetTempFilePath, { destination: targetStorageFilePath }) + }).then(() => { + console.log('Output audio uploaded to', targetStorageFilePath); - // Once the audio has been uploaded delete the local file to free up disk space. - fs.unlinkSync(tempFilePath); - fs.unlinkSync(targetTempFilePath); + // Once the audio has been uploaded delete the local file to free up disk space. + fs.unlinkSync(tempFilePath); + fs.unlinkSync(targetTempFilePath); - console.log('Temporary files removed.', targetTempFilePath); - }); - }); + return console.log('Temporary files removed.', targetTempFilePath); }); }); From 26131a41325174559b02a859e6cf778ce10bf365 Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Tue, 6 Feb 2018 12:12:44 -0800 Subject: [PATCH 07/16] removed git_ignore from remote --- .git_ignore | 1 - 1 file changed, 1 deletion(-) delete mode 100644 .git_ignore diff --git a/.git_ignore b/.git_ignore deleted file mode 100644 index e43b0f9889..0000000000 --- a/.git_ignore +++ /dev/null @@ -1 +0,0 @@ -.DS_Store From 6c6f5ba2922eed7318422317ef8b880bfffc8c33 Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Wed, 7 Feb 2018 15:13:05 -0800 Subject: [PATCH 08/16] autoformatting js files --- child-count/functions/index.js | 14 +-- coupon-on-purchase/functions/index.js | 6 +- .../email-notifier/functions/index.js | 2 +- .../jira-issue/functions/index.js | 2 +- .../slack-notifier/functions/index.js | 2 +- delete-old-child-nodes/functions/index.js | 26 +++--- .../functions/index.js | 2 +- developer-motivator/functions/index.js | 29 +++--- ffmpeg-convert-audio/functions/index.js | 38 ++++---- github-to-slack/functions/index.js | 92 +++++++++---------- google-sheet-sync/functions/index.js | 28 +++--- image-sharp/functions/index.js | 34 +++---- instagram-auth/functions/index.js | 79 ++++++++-------- isomorphic-react-app/functions/index.js | 62 ++++++------- line-auth/functions/index.js | 60 ++++++------ linkedin-auth/functions/index.js | 76 ++++++++------- message-translation/functions/index.js | 28 +++--- minimal-webhook/functions/index.js | 28 +++--- moderate-images/functions/index.js | 38 ++++---- paypal/functions/index.js | 36 ++++---- presence-firestore/functions/index.js | 28 +++--- quickstarts/email-users/functions/index.js | 8 +- quickstarts/thumbnails/functions/index.js | 45 +++++---- quickstarts/time-server/functions/index.js | 10 +- .../uppercase-firestore/functions/index.js | 30 +++--- quickstarts/uppercase/functions/index.js | 30 +++--- spotify-auth/functions/index.js | 56 +++++------ stripe/functions/index.js | 28 +++--- text-moderation/functions/index.js | 30 +++--- url-shortener/functions/index.js | 30 +++--- username-password-auth/functions/index.js | 53 ++++++----- 31 files changed, 525 insertions(+), 505 deletions(-) diff --git a/child-count/functions/index.js b/child-count/functions/index.js index a32701e00a..0c3b3f2ffa 100644 --- a/child-count/functions/index.js +++ b/child-count/functions/index.js @@ -17,14 +17,14 @@ const functions = require('firebase-functions'); const admin = require('firebase-admin'); - admin.initializeApp(functions.config().firebase); +admin.initializeApp(functions.config().firebase); // Keeps track of the length of the 'likes' child list in a separate property. exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(event => { const collectionRef = event.data.ref.parent; const countRef = collectionRef.parent.child('likes_count'); - let increment; + let increment; if (event.data.exists() && !event.data.previous.exists()) { increment = 1; } @@ -34,12 +34,12 @@ exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid} return null; } - // Return the promise from countRef.transaction() so our function + // Return the promise from countRef.transaction() so our function // waits for this async event to complete before it exits. return countRef.transaction(current => { (current || 0) + increment; -}).then(() => { - return console.log('Counter updated.'); + }).then(() => { + return console.log('Counter updated.'); }); }); @@ -48,8 +48,8 @@ exports.recountlikes = functions.database.ref('/posts/{postid}/likes_count').onW if (!event.data.exists()) { const counterRef = event.data.ref; const collectionRef = counterRef.parent.child('likes'); - - // Return the promise from counterRef.set() so our function + + // Return the promise from counterRef.set() so our function // waits for this async event to complete before it exits. return collectionRef.once('value') .then(messagesData => counterRef.set(messagesData.numChildren())); diff --git a/coupon-on-purchase/functions/index.js b/coupon-on-purchase/functions/index.js index cc4c59b52e..0187872297 100644 --- a/coupon-on-purchase/functions/index.js +++ b/coupon-on-purchase/functions/index.js @@ -112,9 +112,9 @@ function sendHighValueCouponViaFCM(uid, userLanguage) { } /** - * Get the Device Tokens for the given user. - * - * @param {string} uid The UID of the user. + * Get the Device Tokens for the given user. + * + * @param {string} uid The UID of the user. */ function getDeviceTokens(uid) { return admin.database().ref(`/users/${uid}/tokens`).once('value').then(snap => { diff --git a/crashlytics-integration/email-notifier/functions/index.js b/crashlytics-integration/email-notifier/functions/index.js index f99654d92a..49c477e9ec 100644 --- a/crashlytics-integration/email-notifier/functions/index.js +++ b/crashlytics-integration/email-notifier/functions/index.js @@ -115,7 +115,7 @@ exports.sendOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert(even

Creation Time: ${createTime}

# of Total Crashes: ${crashes.toString()}

` }; - + return sendgridMail.send(emailDetails).then(() => { return console.log('Successfully sent velocity alert email'); }).catch(error => { diff --git a/crashlytics-integration/jira-issue/functions/index.js b/crashlytics-integration/jira-issue/functions/index.js index ed04c2032f..8d5ae2567b 100644 --- a/crashlytics-integration/jira-issue/functions/index.js +++ b/crashlytics-integration/jira-issue/functions/index.js @@ -61,7 +61,7 @@ const createJiraIssue = (summary, description, priority) => { const pass = functions.config().jira.pass; const issue_type = functions.config().jira.issue_type; const component_id = functions.config().jira.component_id; - + const { protocol, domain, contextPath, projectKey} = parseUrl(project_url); const baseUrl = [protocol, domain, contextPath].join(''); const url = `${baseUrl}/rest/api/2/issue`; diff --git a/crashlytics-integration/slack-notifier/functions/index.js b/crashlytics-integration/slack-notifier/functions/index.js index 8331245e38..eb47ba3501 100644 --- a/crashlytics-integration/slack-notifier/functions/index.js +++ b/crashlytics-integration/slack-notifier/functions/index.js @@ -81,7 +81,7 @@ exports.postOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert(even const slackMessage = ` There is an issue ${issueTitle} (${issueId}) ` + `in ${appName}, version ${latestAppVersion} on ${appPlatform} that is causing ` + `${parseFloat(crashPercentage).toFixed(2)}% of all sessions to crash.`; - + return notifySlack(slackMessage)/then(() => { console.log(`Posted velocity alert ${issueId} successfully to Slack`); }); diff --git a/delete-old-child-nodes/functions/index.js b/delete-old-child-nodes/functions/index.js index 9ad19b8eba..8a41460da9 100644 --- a/delete-old-child-nodes/functions/index.js +++ b/delete-old-child-nodes/functions/index.js @@ -27,18 +27,18 @@ const CUT_OFF_TIME = 2 * 60 * 60 * 1000; // 2 Hours in milliseconds. * cut-off time. Each child needs to have a `timestamp` attribute. */ exports.deleteOldItems = functions.database.ref('/path/to/items/{pushId}') - .onWrite(event => { - const ref = event.data.ref.parent; // reference to the items - const now = Date.now(); - const cutoff = now - CUT_OFF_TIME; - const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff); - return oldItemsQuery.once('value').then(snapshot => { - // create a map with all children that need to be removed - const updates = {}; - snapshot.forEach(child => { - updates[child.key] = null; - }); - // execute all updates in one go and return the result to end the function - return ref.update(updates); + .onWrite(event => { + const ref = event.data.ref.parent; // reference to the items + const now = Date.now(); + const cutoff = now - CUT_OFF_TIME; + const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff); + return oldItemsQuery.once('value').then(snapshot => { + // create a map with all children that need to be removed + const updates = {}; + snapshot.forEach(child => { + updates[child.key] = null; }); + // execute all updates in one go and return the result to end the function + return ref.update(updates); }); + }); diff --git a/delete-unused-accounts-cron/functions/index.js b/delete-unused-accounts-cron/functions/index.js index a80962182e..a3bcde8ddd 100644 --- a/delete-unused-accounts-cron/functions/index.js +++ b/delete-unused-accounts-cron/functions/index.js @@ -10,7 +10,7 @@ * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for t`he specific language governing permissions and + * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; diff --git a/developer-motivator/functions/index.js b/developer-motivator/functions/index.js index 2c2d121bf5..cda6930157 100644 --- a/developer-motivator/functions/index.js +++ b/developer-motivator/functions/index.js @@ -27,14 +27,13 @@ const deviceToken = functions.config().dev_motivator.device_token; * The device model name, the city and the country of the user are sent in the notification message */ exports.appinstalled = functions.analytics.event('first_open').onLog(event => { - const payload = { - notification: { - title: 'you have a new user \uD83D\uDE43', - body: event.data.user.deviceInfo.mobileModelName + ' from ' + event.data.user.geoInfo.city + ', ' + event.data.user.geoInfo.country - } - }; - - admin.messaging().sendToDevice(deviceToken, payload); + const payload = { + notification: { + title: 'you have a new user \uD83D\uDE43', + body: event.data.user.deviceInfo.mobileModelName + ' from ' + event.data.user.geoInfo.city + ', ' + event.data.user.geoInfo.country + } + }; + admin.messaging().sendToDevice(deviceToken, payload); }); /** @@ -45,13 +44,13 @@ exports.appinstalled = functions.analytics.event('first_open').onLog(event => { * The device model name, the city and the country of the user are sent in the notification message */ exports.appremoved = functions.analytics.event('app_remove').onLog(event => { - const payload = { - notification: { - title: 'you lost a user \uD83D\uDE1E', - body: event.data.user.deviceInfo.mobileModelName + ' from ' + event.data.user.geoInfo.city + ', ' + event.data.user.geoInfo.country - } - }; + const payload = { + notification: { + title: 'you lost a user \uD83D\uDE1E', + body: event.data.user.deviceInfo.mobileModelName + ' from ' + event.data.user.geoInfo.city + ', ' + event.data.user.geoInfo.country + } + }; - admin.messaging().sendToDevice(deviceToken, payload); + admin.messaging().sendToDevice(deviceToken, payload); }); diff --git a/ffmpeg-convert-audio/functions/index.js b/ffmpeg-convert-audio/functions/index.js index 9ec80dd50a..96efc6d2f5 100644 --- a/ffmpeg-convert-audio/functions/index.js +++ b/ffmpeg-convert-audio/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2017 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for t`he specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for t`he specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -37,8 +37,8 @@ function promisifyCommand(command) { } /** -* Utility method to convert audio to mono channel using FFMPEG. -*/ + * Utility method to convert audio to mono channel using FFMPEG. + */ function reencodeAsync(tempFilePath, targetTempFilePath) { return new Promise((resolve, reject) => { const command = ffmpeg(tempFilePath) @@ -58,9 +58,9 @@ function reencodeAsync(tempFilePath, targetTempFilePath) { } /** -* When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using -* node-fluent-ffmpeg. -*/ + * When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using + * node-fluent-ffmpeg. + */ exports.generateMonoAudio = functions.storage.object().onChange(event => { const object = event.data; // The Storage object. diff --git a/github-to-slack/functions/index.js b/github-to-slack/functions/index.js index 5d40acd7de..c09cfd609c 100644 --- a/github-to-slack/functions/index.js +++ b/github-to-slack/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -21,43 +21,43 @@ const crypto = require('crypto'); const secureCompare = require('secure-compare'); /** -* Webhook that will be called each time there is a new GitHub commit and will post a message to -* Slack. -*/ + * Webhook that will be called each time there is a new GitHub commit and will post a message to + * Slack. + */ exports.githubWebhook = functions.https.onRequest((req, res) => { - const cipher = 'sha1'; - const signature = req.headers['x-hub-signature']; + const cipher = 'sha1'; + const signature = req.headers['x-hub-signature']; - // TODO: Configure the `github.secret` Google Cloud environment variables. - const hmac = crypto.createHmac(cipher, functions.config().github.secret) - .update(req.body) - .digest('hex'); - const expectedSignature = `${cipher}=${hmac}`; + // TODO: Configure the `github.secret` Google Cloud environment variables. + const hmac = crypto.createHmac(cipher, functions.config().github.secret) + .update(req.body) + .digest('hex'); + const expectedSignature = `${cipher}=${hmac}`; - // Check that the body of the request has been signed with the GitHub Secret. - if (!secureCompare(signature, expectedSignature)) { - console.error('x-hub-signature', signature, 'did not match', expectedSignature); - return res.status(403).send('Your x-hub-signature\'s bad and you should feel bad!'); - } - return postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => { - return res.end(); - }).catch(error => { - console.error(error); - return res.status(500).send('Something went wrong while posting the message to Slack.'); - }); + // Check that the body of the request has been signed with the GitHub Secret. + if (!secureCompare(signature, expectedSignature)) { + console.error('x-hub-signature', signature, 'did not match', expectedSignature); + return res.status(403).send('Your x-hub-signature\'s bad and you should feel bad!'); + } + return postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => { + return res.end(); + }).catch(error => { + console.error(error); + return res.status(500).send('Something went wrong while posting the message to Slack.'); + }); }); /** -* Post a message to Slack about the new GitHub commit. -*/ + * Post a message to Slack about the new GitHub commit. + */ function postToSlack(url, commits, repo) { - return rp({ - method: 'POST', - // TODO: Configure the `slack.webhook_url` Google Cloud environment variables. - uri: functions.config().slack.webhook_url, - body: { - text: `<${url}|${commits} new commit${commits > 1 ? 's' : ''}> pushed to <${repo.url}|${repo.full_name}>.` - }, - json: true - }); + return rp({ + method: 'POST', + // TODO: Configure the `slack.webhook_url` Google Cloud environment variables. + uri: functions.config().slack.webhook_url, + body: { + text: `<${url}|${commits} new commit${commits > 1 ? 's' : ''}> pushed to <${repo.url}|${repo.full_name}>.` + }, + json: true + }); } diff --git a/google-sheet-sync/functions/index.js b/google-sheet-sync/functions/index.js index 8ff05e9877..8d74f122d2 100644 --- a/google-sheet-sync/functions/index.js +++ b/google-sheet-sync/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2017 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; // Sample trigger function that copies new Firebase data to a Google Sheet diff --git a/image-sharp/functions/index.js b/image-sharp/functions/index.js index 1a71b252eb..036d2bb342 100644 --- a/image-sharp/functions/index.js +++ b/image-sharp/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for t`he specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for t`he specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -24,9 +24,9 @@ const THUMB_MAX_WIDTH = 200; const THUMB_MAX_HEIGHT = 200; /** -* When an image is uploaded in the Storage bucket We generate a thumbnail automatically using -* Sharp. -*/ + * When an image is uploaded in the Storage bucket We generate a thumbnail automatically using + * Sharp. + */ exports.generateThumbnail = functions.storage.object().onChange(event => { const object = event.data; // The Storage object. diff --git a/instagram-auth/functions/index.js b/instagram-auth/functions/index.js index 9b07b5112d..14182fb16a 100644 --- a/instagram-auth/functions/index.js +++ b/instagram-auth/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -31,8 +31,8 @@ const OAUTH_REDIRECT_URI = `https://${process.env.GCLOUD_PROJECT}.firebaseapp.co const OAUTH_SCOPES = 'basic'; /** -* Creates a configured simple-oauth2 client for Instagram. -*/ + * Creates a configured simple-oauth2 client for Instagram. + */ function instagramOAuth2Client() { // Instagram OAuth 2 setup // TODO: Configure the `instagram.client_id` and `instagram.client_secret` Google Cloud environment variables. @@ -50,16 +50,20 @@ function instagramOAuth2Client() { } /** -* Redirects the User to the Instagram authentication consent screen. Also the 'state' cookie is set for later state -* verification. -*/ + * Redirects the User to the Instagram authentication consent screen. Also the 'state' cookie is set for later state + * verification. + */ exports.redirect = functions.https.onRequest((req, res) => { const oauth2 = instagramOAuth2Client(); cookieParser()(req, res, () => { const state = req.cookies.state || crypto.randomBytes(20).toString('hex'); console.log('Setting verification state:', state); - res.cookie('state', state.toString(), {maxAge: 3600000, secure: true, httpOnly: true}); + res.cookie('state', state.toString(), { + maxAge: 3600000, + secure: true, + httpOnly: true + }); const redirectUri = oauth2.authorizationCode.authorizeURL({ redirect_uri: OAUTH_REDIRECT_URI, scope: OAUTH_SCOPES, @@ -71,11 +75,11 @@ exports.redirect = functions.https.onRequest((req, res) => { }); /** -* Exchanges a given Instagram auth code passed in the 'code' URL query parameter for a Firebase auth token. -* The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. -* The Firebase custom auth token, display name, photo URL and Instagram acces token are sent back in a JSONP callback -* function with function name defined by the 'callback' query parameter. -*/ + * Exchanges a given Instagram auth code passed in the 'code' URL query parameter for a Firebase auth token. + * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. + * The Firebase custom auth token, display name, photo URL and Instagram acces token are sent back in a JSONP callback + * function with function name defined by the 'callback' query parameter. + */ exports.token = functions.https.onRequest((req, res) => { const oauth2 = instagramOAuth2Client(); @@ -106,28 +110,31 @@ exports.token = functions.https.onRequest((req, res) => { return createFirebaseAccount(instagramUserID, userName, profilePic, accessToken) }).then(firebaseToken => { // Serve an HTML page that signs the user in and updates the user profile. - return res.jsonp({token: firebaseToken}); + return res.jsonp({ + token: firebaseToken + }); }); } catch (error) { - return res.jsonp({error: error.toString}); + return res.jsonp({ + error: error.toString + }); } }); /** -* Creates a Firebase account with the given user profile and returns a custom auth token allowing -* signing-in this account. -* Also saves the accessToken to the datastore at /instagramAccessToken/$uid -* -* @returns {Promise} The Firebase custom auth token in a promise. -*/ + * Creates a Firebase account with the given user profile and returns a custom auth token allowing + * signing-in this account. + * Also saves the accessToken to the datastore at /instagramAccessToken/$uid + * + * @returns {Promise} The Firebase custom auth token in a promise. + */ function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) { // The UID we'll assign to the user. const uid = `instagram:${instagramID}`; // Save the access token tot he Firebase Realtime Database. const databaseTask = admin.database().ref(`/instagramAccessToken/${uid}`) - .set(accessToken); - + .set(accessToken); // Create or update the user account. const userCreationTask = admin.auth().updateUser(uid, { displayName: displayName, @@ -152,4 +159,4 @@ function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) console.log('Created Custom token for UID "', uid, '" Token:', token); return token; }); -} +} \ No newline at end of file diff --git a/isomorphic-react-app/functions/index.js b/isomorphic-react-app/functions/index.js index 98230c1de5..54c463099f 100644 --- a/isomorphic-react-app/functions/index.js +++ b/isomorphic-react-app/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const functions = require('firebase-functions'); const firebase = require('firebase'); @@ -32,29 +32,29 @@ database.initializeApp(appConfig); // Helper function to get the markup from React, inject the initial state, and // send the server-side markup to the client const renderApplication = (url, res, initialState) => { - const html = ReactDOMServer.renderToString(ServerApp({url: url, context: {}, initialState, appConfig})); - const templatedHtml = template({body: html, initialState: JSON.stringify(initialState)}); - res.send(templatedHtml); + const html = ReactDOMServer.renderToString(ServerApp({url: url, context: {}, initialState, appConfig})); + const templatedHtml = template({body: html, initialState: JSON.stringify(initialState)}); + res.send(templatedHtml); }; app.get('/favicon.ico', (req, res) => { - return res.send(204); + return res.send(204); }); app.get('/:userId?', (req, res) => { - res.set('Cache-Control', 'public, max-age=60, s-maxage=180'); - if (req.params.userId) { - // client is requesting user-details page with userId - // load the data for that employee and its direct reports - return database.getEmployeeById(req.params.userId).then(resp => { - return renderApplication(req.url, res, resp); - }); - } else { - // index page. load data for all employees - return database.getAllEmployees().then(resp => { - return renderApplication(req.url, res, resp); - }); - } + res.set('Cache-Control', 'public, max-age=60, s-maxage=180'); + if (req.params.userId) { + // client is requesting user-details page with userId + // load the data for that employee and its direct reports + return database.getEmployeeById(req.params.userId).then(resp => { + return renderApplication(req.url, res, resp); + }); + } else { + // index page. load data for all employees + return database.getAllEmployees().then(resp => { + return renderApplication(req.url, res, resp); + }); + } }); exports.app = functions.https.onRequest(app); diff --git a/line-auth/functions/index.js b/line-auth/functions/index.js index 8069b9ea7b..ab4b63ca5e 100644 --- a/line-auth/functions/index.js +++ b/line-auth/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; // Modules imports @@ -39,11 +39,11 @@ function generateLineApiRequest(apiEndpoint, lineAccessToken) { } /** -* Look up Firebase user based on LINE's mid. If the Firebase user does not exist, -+ fetch LINE profile and create a new Firebase user with it. -* -* @returns {Promise} The Firebase user record in a promise. -*/ + * Look up Firebase user based on LINE's mid. If the Firebase user does not exist, + * fetch LINE profile and create a new Firebase user with it. + * + * @returns {Promise} The Firebase user record in a promise. + */ function getFirebaseUser(lineMid, lineAccessToken) { // Generate Firebase user's uid based on LINE's mid const firebaseUid = `line:${lineMid}`; @@ -74,17 +74,17 @@ function getFirebaseUser(lineMid, lineAccessToken) { } /** -* Verify LINE access token and return a custom auth token allowing signing-in -* the corresponding Firebase account. -* -* Here are the steps involved: -* 1. Verify with LINE server that a LINE access token is valid -* 2. Check if a Firebase user corresponding to the LINE user already existed. -* If not, fetch user profile from LINE and generate a corresponding Firebase user. -* 3. Return a custom auth token allowing signing-in the Firebase account. -* -* @returns {Promise} The Firebase custom auth token in a promise. -*/ + * Verify LINE access token and return a custom auth token allowing signing-in + * the corresponding Firebase account. + * + * Here are the steps involved: + * 1. Verify with LINE server that a LINE access token is valid + * 2. Check if a Firebase user corresponding to the LINE user already existed. + * If not, fetch user profile from LINE and generate a corresponding Firebase user. + * 3. Return a custom auth token allowing signing-in the Firebase account. + * + * @returns {Promise} The Firebase custom auth token in a promise. + */ function verifyLineToken(lineAccessToken) { // Send request to LINE server for access token verification const verifyTokenOptions = generateLineApiRequest('https://api.line.me/v1/oauth/verify', lineAccessToken); diff --git a/linkedin-auth/functions/index.js b/linkedin-auth/functions/index.js index 73c0621e7b..b10e1ec804 100644 --- a/linkedin-auth/functions/index.js +++ b/linkedin-auth/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -30,8 +30,8 @@ admin.initializeApp({ const OAUTH_SCOPES = ['r_basicprofile', 'r_emailaddress']; /** -* Creates a configured LinkedIn API Client instance. -*/ + * Creates a configured LinkedIn API Client instance. + */ function linkedInClient() { // LinkedIn OAuth 2 setup // TODO: Configure the `linkedin.client_id` and `linkedin.client_secret` Google Cloud environment variables. @@ -42,26 +42,30 @@ function linkedInClient() { } /** -* Redirects the User to the LinkedIn authentication consent screen. ALso the 'state' cookie is set for later state -* verification. -*/ + * Redirects the User to the LinkedIn authentication consent screen. ALso the 'state' cookie is set for later state + * verification. + */ exports.redirect = functions.https.onRequest((req, res) => { const Linkedin = linkedInClient(); cookieParser()(req, res, () => { const state = req.cookies.state || crypto.randomBytes(20).toString('hex'); console.log('Setting verification state:', state); - res.cookie('state', state.toString(), {maxAge: 3600000, secure: true, httpOnly: true}); + res.cookie('state', state.toString(), { + maxAge: 3600000, + secure: true, + httpOnly: true + }); Linkedin.auth.authorize(res, OAUTH_SCOPES, state.toString()); }); }); /** -* Exchanges a given LinkedIn auth code passed in the 'code' URL query parameter for a Firebase auth token. -* The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. -* The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the -* 'callback' query parameter. -*/ + * Exchanges a given LinkedIn auth code passed in the 'code' URL query parameter for a Firebase auth token. + * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. + * The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the + * 'callback' query parameter. + */ exports.token = functions.https.onRequest((req, res) => { const Linkedin = linkedInClient(); @@ -97,23 +101,27 @@ exports.token = functions.https.onRequest((req, res) => { return createFirebaseAccount(linkedInUserID, userName, profilePic, email, accessToken).then( firebaseToken => { // Serve an HTML page that signs the user in and updates the user profile. - return res.jsonp({token: firebaseToken}); + return res.jsonp({ + token: firebaseToken + }); }); }); }); }); } catch (error) { - return res.jsonp({error: error.toString}); + return res.jsonp({ + error: error.toString + }); } }); /** -* Creates a Firebase account with the given user profile and returns a custom auth token allowing -* signing-in this account. -* Also saves the accessToken to the datastore at /linkedInAccessToken/$uid -* -* @returns {Promise} The Firebase custom auth token in a promise. -*/ + * Creates a Firebase account with the given user profile and returns a custom auth token allowing + * signing-in this account. + * Also saves the accessToken to the datastore at /linkedInAccessToken/$uid + * + * @returns {Promise} The Firebase custom auth token in a promise. + */ function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessToken) { // The UID we'll assign to the user. const uid = `linkedin:${linkedinID}`; @@ -149,4 +157,4 @@ function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessT console.log('Created Custom token for UID "', uid, '" Token:', token); return token; }); -} +} \ No newline at end of file diff --git a/message-translation/functions/index.js b/message-translation/functions/index.js index 8722ee2f11..d032428ff2 100644 --- a/message-translation/functions/index.js +++ b/message-translation/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); diff --git a/minimal-webhook/functions/index.js b/minimal-webhook/functions/index.js index 559eb21116..8f11766daa 100644 --- a/minimal-webhook/functions/index.js +++ b/minimal-webhook/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); diff --git a/moderate-images/functions/index.js b/moderate-images/functions/index.js index 7725ba896b..30cbe3122a 100644 --- a/moderate-images/functions/index.js +++ b/moderate-images/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for t`he specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for t`he specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -25,9 +25,9 @@ const os = require('os'); const fs = require('fs'); /** -* When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision -* API and if it is we blur it using ImageMagick. -*/ + * When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision + * API and if it is we blur it using ImageMagick. + */ exports.blurOffensiveImages = functions.storage.object().onChange(event => { const object = event.data; const file = gcs.bucket(object.bucket).file(object.name); @@ -50,8 +50,8 @@ exports.blurOffensiveImages = functions.storage.object().onChange(event => { }); /** -* Blurs the given image located in the given bucket using ImageMagick. -*/ + * Blurs the given image located in the given bucket using ImageMagick. + */ function blurImage(filePath, bucketName, metadata) { const tempLocalFile = path.join(os.tmpdir(), filePath); const tempLocalDir = path.dirname(tempLocalFile); diff --git a/paypal/functions/index.js b/paypal/functions/index.js index 9b6cfc2e35..c039f6aa66 100644 --- a/paypal/functions/index.js +++ b/paypal/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -29,10 +29,10 @@ paypal.configure({ client_secret: functions.config().paypal.client_secret // run: firebase functions:config:set paypal.client_secret="yourPaypalClientSecret" }); /** -* Expected in the body the amount -* Set up the payment information object -* Initialize the payment and redirect the user to the PayPal payment page -*/ + * Expected in the body the amount + * Set up the payment information object + * Initialize the payment and redirect the user to the PayPal payment page + */ exports.pay = functions.https.onRequest((req, res) => { // 1.Set up a payment information object, Nuild PayPal payment request const payReq = JSON.stringify({ diff --git a/presence-firestore/functions/index.js b/presence-firestore/functions/index.js index 060fcc23eb..62dbcd4c39 100644 --- a/presence-firestore/functions/index.js +++ b/presence-firestore/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2017 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the 'License'); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an 'AS IS' BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ // [START presence_sync_function] const functions = require('firebase-functions'); diff --git a/quickstarts/email-users/functions/index.js b/quickstarts/email-users/functions/index.js index 4445ed68ad..b2851b19a1 100644 --- a/quickstarts/email-users/functions/index.js +++ b/quickstarts/email-users/functions/index.js @@ -39,8 +39,8 @@ const APP_NAME = 'Cloud Storage for Firebase quickstart'; // [START sendWelcomeEmail] /** -* Sends a welcome email to new user. -*/ + * Sends a welcome email to new user. + */ // [START onCreateTrigger] exports.sendWelcomeEmail = functions.auth.user().onCreate(event => { // [END onCreateTrigger] @@ -57,8 +57,8 @@ exports.sendWelcomeEmail = functions.auth.user().onCreate(event => { // [START sendByeEmail] /** -* Send an account deleted email confirmation to users who delete their accounts. -*/ + * Send an account deleted email confirmation to users who delete their accounts. + */ // [START onDeleteTrigger] exports.sendByeEmail = functions.auth.user().onDelete(event => { // [END onDeleteTrigger] diff --git a/quickstarts/thumbnails/functions/index.js b/quickstarts/thumbnails/functions/index.js index 28d5a3886c..a06d41a9fe 100644 --- a/quickstarts/thumbnails/functions/index.js +++ b/quickstarts/thumbnails/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for t`he specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for t`he specific language governing permissions and + * limitations under the License. + */ 'use strict'; // [START import] @@ -26,9 +26,9 @@ const fs = require('fs'); // [START generateThumbnail] /** -* When an image is uploaded in the Storage bucket We generate a thumbnail automatically using -* ImageMagick. -*/ + * When an image is uploaded in the Storage bucket We generate a thumbnail automatically using + * ImageMagick. + */ // [START generateThumbnailTrigger] exports.generateThumbnail = functions.storage.object().onChange(event => { // [END generateThumbnailTrigger] @@ -75,7 +75,9 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { // Download file from bucket. const bucket = gcs.bucket(fileBucket); const tempFilePath = path.join(os.tmpdir(), fileName); - const metadata = { contentType: contentType }; + const metadata = { + contentType: contentType + }; return bucket.file(filePath).download({ destination: tempFilePath }).then(() => { @@ -88,9 +90,12 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { const thumbFileName = `thumb_${fileName}`; const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); // Uploading the thumbnail. - return bucket.upload(tempFilePath, { destination: thumbFilePath, metadata: metadata }); + return bucket.upload(tempFilePath, { + destination: thumbFilePath, + metadata: metadata + }); // Once the thumbnail has been uploaded delete the local file to free up disk space. }).then(() => fs.unlinkSync(tempFilePath)); // [END thumbnailGeneration] }); -// [END generateThumbnail] +// [END generateThumbnail] \ No newline at end of file diff --git a/quickstarts/time-server/functions/index.js b/quickstarts/time-server/functions/index.js index 88a0c9aeb3..5786ce8b63 100644 --- a/quickstarts/time-server/functions/index.js +++ b/quickstarts/time-server/functions/index.js @@ -22,7 +22,9 @@ const functions = require('firebase-functions'); // Moments library to format dates. const moment = require('moment'); // CORS Express middleware to enable CORS Requests. -const cors = require('cors')({origin: true}); +const cors = require('cors')({ + origin: true +}); // [END additionalimports] // [START all] @@ -44,7 +46,7 @@ const cors = require('cors')({origin: true}); */ // [START trigger] exports.date = functions.https.onRequest((req, res) => { -// [END trigger] + // [END trigger] // [START sendError] // Forbidding PUT requests. if (req.method === 'PUT') { @@ -55,7 +57,7 @@ exports.date = functions.https.onRequest((req, res) => { // [START usingMiddleware] // Enable CORS using the `cors` express middleware. cors(req, res, () => { - // [END usingMiddleware] + // [END usingMiddleware] // Reading date format from URL query parameter. // [START readQueryParam] let format = req.query.format; @@ -73,4 +75,4 @@ exports.date = functions.https.onRequest((req, res) => { // [END sendResponse] }); }); -// [END all] +// [END all] \ No newline at end of file diff --git a/quickstarts/uppercase-firestore/functions/index.js b/quickstarts/uppercase-firestore/functions/index.js index 99658ee726..43e0ec5d4a 100644 --- a/quickstarts/uppercase-firestore/functions/index.js +++ b/quickstarts/uppercase-firestore/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2017 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the 'License'); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an 'AS IS' BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; // [START all] @@ -62,4 +62,4 @@ exports.makeUppercase = functions.firestore.document('/messages/{documentId}').o // [END makeUppercaseBody] }); // [END makeUppercase] -// [END all] +// [END all] \ No newline at end of file diff --git a/quickstarts/uppercase/functions/index.js b/quickstarts/uppercase/functions/index.js index 74cd077169..9abaf54b98 100644 --- a/quickstarts/uppercase/functions/index.js +++ b/quickstarts/uppercase/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; // [START all] @@ -61,4 +61,4 @@ exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').on // [END makeUppercaseBody] }); // [END makeUppercase] -// [END all] +// [END all] \ No newline at end of file diff --git a/spotify-auth/functions/index.js b/spotify-auth/functions/index.js index 95314ddfdb..8285ca8d37 100644 --- a/spotify-auth/functions/index.js +++ b/spotify-auth/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -40,9 +40,9 @@ const Spotify = new SpotifyWebApi({ const OAUTH_SCOPES = ['user-read-email']; /** -* Redirects the User to the Spotify authentication consent screen. Also the 'state' cookie is set for later state -* verification. -*/ + * Redirects the User to the Spotify authentication consent screen. Also the 'state' cookie is set for later state + * verification. + */ exports.redirect = functions.https.onRequest((req, res) => { cookieParser()(req, res, () => { const state = req.cookies.state || crypto.randomBytes(20).toString('hex'); @@ -54,11 +54,11 @@ exports.redirect = functions.https.onRequest((req, res) => { }); /** -* Exchanges a given Spotify auth code passed in the 'code' URL query parameter for a Firebase auth token. -* The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. -* The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the -* 'callback' query parameter. -*/ + * Exchanges a given Spotify auth code passed in the 'code' URL query parameter for a Firebase auth token. + * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie. + * The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the + * 'callback' query parameter. + */ exports.token = functions.https.onRequest((req, res) => { try { cookieParser()(req, res, () => { @@ -105,12 +105,12 @@ exports.token = functions.https.onRequest((req, res) => { }); /** -* Creates a Firebase account with the given user profile and returns a custom auth token allowing -* signing-in this account. -* Also saves the accessToken to the datastore at /spotifyAccessToken/$uid -* -* @returns {Promise} The Firebase custom auth token in a promise. -*/ + * Creates a Firebase account with the given user profile and returns a custom auth token allowing + * signing-in this account. + * Also saves the accessToken to the datastore at /spotifyAccessToken/$uid + * + * @returns {Promise} The Firebase custom auth token in a promise. + */ function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessToken) { // The UID we'll assign to the user. const uid = `spotify:${spotifyID}`; diff --git a/stripe/functions/index.js b/stripe/functions/index.js index e10ca768f0..ad1445aafe 100644 --- a/stripe/functions/index.js +++ b/stripe/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'), diff --git a/text-moderation/functions/index.js b/text-moderation/functions/index.js index 5c5b195256..00bf9fa2af 100644 --- a/text-moderation/functions/index.js +++ b/text-moderation/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -79,4 +79,4 @@ function isShouting(message) { // and remove exclamation points. function stopShouting(message) { return capitalizeSentence(message.toLowerCase()).replace(/!+/g, '.'); -} +} \ No newline at end of file diff --git a/url-shortener/functions/index.js b/url-shortener/functions/index.js index b16f8ff536..2708085caf 100644 --- a/url-shortener/functions/index.js +++ b/url-shortener/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2017 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -56,4 +56,4 @@ function createShortenerPromise(snapshot) { short: shortUrl }); }); -} +} \ No newline at end of file diff --git a/username-password-auth/functions/index.js b/username-password-auth/functions/index.js index 3222d6239b..aad6925734 100644 --- a/username-password-auth/functions/index.js +++ b/username-password-auth/functions/index.js @@ -1,18 +1,17 @@ -/** -* Copyright 2017 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for t`he specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for t`he specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -35,13 +34,13 @@ const basicAuthRequest = require('request'); /** -* Authenticate the provided credentials returning a Firebase custom auth token. -* `username` and `password` values are expected in the body of the request. -* If authentication fails return a 401 response. -* If the request is badly formed return a 400 response. -* If the request method is unsupported (not POST) return a 403 response. -* If an error occurs log the details and return a 500 response. -*/ + * Authenticate the provided credentials returning a Firebase custom auth token. + * `username` and `password` values are expected in the body of the request. + * If authentication fails return a 401 response. + * If the request is badly formed return a 400 response. + * If the request method is unsupported (not POST) return a 403 response. + * If an error occurs log the details and return a 500 response. + */ exports.auth = functions.https.onRequest((req, res) => { const handleError = (username, error) => { console.error({ @@ -104,10 +103,10 @@ exports.auth = functions.https.onRequest((req, res) => { }); /** -* Authenticate the provided credentials. -* TODO(DEVELOPER): In production you'll need to update this function so that it authenticates with your own credentials system. -* @returns {Promise} success or failure. -*/ + * Authenticate the provided credentials. + * TODO(DEVELOPER): In production you'll need to update this function so that it authenticates with your own credentials system. + * @returns {Promise} success or failure. + */ function authenticate(username, password) { // For the purpose of this example use httpbin (https://httpbin.org) and send a basic authentication request. @@ -134,4 +133,4 @@ function authenticate(username, password) { return resolve(true); }); }); -} +} \ No newline at end of file From eec14483bd6f27fdca3dca606d6513bb39d3cb4c Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Wed, 7 Feb 2018 15:34:30 -0800 Subject: [PATCH 09/16] fixed username-password-auth/functions/index.js --- username-password-auth/functions/index.js | 1 + 1 file changed, 1 insertion(+) diff --git a/username-password-auth/functions/index.js b/username-password-auth/functions/index.js index aad6925734..b1fe7c9cb3 100644 --- a/username-password-auth/functions/index.js +++ b/username-password-auth/functions/index.js @@ -1,3 +1,4 @@ +/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); From d2f0d6d2a6acea50544fcedeeb3c3ef8b4a7e5df Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Wed, 7 Feb 2018 16:20:12 -0800 Subject: [PATCH 10/16] more syntax fixes --- .../functions/index.js | 2 +- google-sheet-sync/functions/index.js | 8 ++--- message-translation/functions/index.js | 16 +++++----- quickstarts/email-users/functions/index.js | 30 +++++++++---------- .../uppercase-firestore/functions/index.js | 4 +-- quickstarts/uppercase/functions/index.js | 4 +-- spotify-auth/functions/index.js | 8 ++--- stripe/functions/index.js | 11 ++++--- 8 files changed, 41 insertions(+), 42 deletions(-) diff --git a/delete-unused-accounts-cron/functions/index.js b/delete-unused-accounts-cron/functions/index.js index a3bcde8ddd..293ade0d27 100644 --- a/delete-unused-accounts-cron/functions/index.js +++ b/delete-unused-accounts-cron/functions/index.js @@ -47,7 +47,7 @@ exports.accountcleanup = functions.https.onRequest((req, res) => { }).then(users => { // Find users that have not signed in in the last 30 days. const inactiveUsers = users.filter( - user => parseInt(user.lastLoginAt, 10) < Date.now() - 30 * 24 * 60 * 60 * 1000); + user => parseInt(user.lastLoginAt, 10) < Date.now() - 30 * 24 * 60 * 60 * 1000); // Use a pool so that we delete maximum `MAX_CONCURRENT` users in parallel. const promisePool = new PromisePool(() => { diff --git a/google-sheet-sync/functions/index.js b/google-sheet-sync/functions/index.js index 8d74f122d2..93113b65f9 100644 --- a/google-sheet-sync/functions/index.js +++ b/google-sheet-sync/functions/index.js @@ -72,10 +72,10 @@ exports.oauthcallback = functions.https.onRequest((req, res) => { return res.status(400).send(err); } return db.ref(DB_TOKEN_PATH).set(tokens) - .then(() => { - return res.status(200).send('App successfully configured with new Credentials. ' - + 'You can now close this page.'); - }); + .then(() => { + return res.status(200).send('App successfully configured with new Credentials. ' + + 'You can now close this page.'); + }); }); }); diff --git a/message-translation/functions/index.js b/message-translation/functions/index.js index d032428ff2..c30528a3d6 100644 --- a/message-translation/functions/index.js +++ b/message-translation/functions/index.js @@ -48,12 +48,12 @@ function createTranslationPromise(source, target, snapshot) { const key = snapshot.key; const message = snapshot.val().message; return request(createTranslateUrl(source, target, message), {resolveWithFullResponse: true}).then( - response => { - if (response.statusCode === 200) { - const data = JSON.parse(response.body).data; - return admin.database().ref(`/messages/${target}/${key}`) - .set({message: data.translations[0].translatedText, translated: true}); - } - throw response.body; - }); + response => { + if (response.statusCode === 200) { + const data = JSON.parse(response.body).data; + return admin.database().ref(`/messages/${target}/${key}`) + .set({message: data.translations[0].translatedText, translated: true}); + } + throw response.body; + }); } diff --git a/quickstarts/email-users/functions/index.js b/quickstarts/email-users/functions/index.js index b2851b19a1..800c3c43f6 100644 --- a/quickstarts/email-users/functions/index.js +++ b/quickstarts/email-users/functions/index.js @@ -1,18 +1,18 @@ /** -* Copyright 2015 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2015 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const functions = require('firebase-functions'); @@ -99,4 +99,4 @@ function sendGoodbyEmail(email, displayName) { return mailTransport.sendMail(mailOptions).then(() => { return console.log('Account deletion confirmation email sent to:', email); }); -} +} \ No newline at end of file diff --git a/quickstarts/uppercase-firestore/functions/index.js b/quickstarts/uppercase-firestore/functions/index.js index 43e0ec5d4a..1cdefd170c 100644 --- a/quickstarts/uppercase-firestore/functions/index.js +++ b/quickstarts/uppercase-firestore/functions/index.js @@ -30,7 +30,7 @@ admin.initializeApp(functions.config().firebase); // Realtime Database under the path /messages/:documentId/original // [START addMessageTrigger] exports.addMessage = functions.https.onRequest((req, res) => { - // [END addMessageTrigger] +// [END addMessageTrigger] // Grab the text parameter. const original = req.query.text; // [START adminSdkAdd] @@ -48,7 +48,7 @@ exports.addMessage = functions.https.onRequest((req, res) => { // uppercase version of the message to /messages/:documentId/uppercase // [START makeUppercaseTrigger] exports.makeUppercase = functions.firestore.document('/messages/{documentId}').onCreate(event => { - // [END makeUppercaseTrigger] +// [END makeUppercaseTrigger] // [START makeUppercaseBody] // Grab the current value of what was written to the Realtime Database. diff --git a/quickstarts/uppercase/functions/index.js b/quickstarts/uppercase/functions/index.js index 9abaf54b98..b1cc71cee0 100644 --- a/quickstarts/uppercase/functions/index.js +++ b/quickstarts/uppercase/functions/index.js @@ -30,7 +30,7 @@ admin.initializeApp(functions.config().firebase); // Realtime Database under the path /messages/:pushId/original // [START addMessageTrigger] exports.addMessage = functions.https.onRequest((req, res) => { - // [END addMessageTrigger] +// [END addMessageTrigger] // Grab the text parameter. const original = req.query.text; // [START adminSdkPush] @@ -48,7 +48,7 @@ exports.addMessage = functions.https.onRequest((req, res) => { // uppercase version of the message to /messages/:pushId/uppercase // [START makeUppercaseTrigger] exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onWrite(event => { - // [END makeUppercaseTrigger] +// [END makeUppercaseTrigger] // [START makeUppercaseBody] // Grab the current value of what was written to the Realtime Database. const original = event.data.val(); diff --git a/spotify-auth/functions/index.js b/spotify-auth/functions/index.js index 8285ca8d37..e98e27fdae 100644 --- a/spotify-auth/functions/index.js +++ b/spotify-auth/functions/index.js @@ -91,10 +91,10 @@ exports.token = functions.https.onRequest((req, res) => { // Create a Firebase account and get the Custom Auth Token. return createFirebaseAccount(spotifyUserID, userName, profilePic, email, accessToken).then( - firebaseToken => { - // Serve an HTML page that signs the user in and updates the user profile. - return res.jsonp({token: firebaseToken}); - }); + firebaseToken => { + // Serve an HTML page that signs the user in and updates the user profile. + return res.jsonp({token: firebaseToken}); + }); }); }); }); diff --git a/stripe/functions/index.js b/stripe/functions/index.js index ad1445aafe..5cabb44877 100644 --- a/stripe/functions/index.js +++ b/stripe/functions/index.js @@ -15,9 +15,9 @@ */ 'use strict'; -const functions = require('firebase-functions'), - admin = require('firebase-admin'), - logging = require('@google-cloud/logging')(); +const functions = require('firebase-functions'); +const admin = require('firebase-admin'); +const logging = require('@google-cloud/logging')(); admin.initializeApp(functions.config().firebase); @@ -44,12 +44,11 @@ exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/ }).then(response => { // If the result is successful, write it back to the database return event.data.adminRef.set(response); - }, error => { + }).catch(error => { // We want to capture errors and render them in a user-friendly way, while // still logging an exception with Stackdriver return event.data.adminRef.child('error').set(userFacingMessage(error)) - } - ).then(() => { + }).then(() => { return reportError(error, {user: event.params.userId}); }); }); From 6e4d95276fe32af86ca99ee5dc5473f511d37533 Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Wed, 7 Feb 2018 16:29:11 -0800 Subject: [PATCH 11/16] last round of syntax fixes --- fcm-notifications/functions/index.js | 3 +-- linkedin-auth/functions/index.js | 6 +++--- template-handlebars/functions/index.js | 1 + 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/fcm-notifications/functions/index.js b/fcm-notifications/functions/index.js index 65a9bf3c62..333d0badde 100644 --- a/fcm-notifications/functions/index.js +++ b/fcm-notifications/functions/index.js @@ -73,8 +73,7 @@ exports.sendFollowerNotification = functions.database.ref('/followers/{followedU if (error) { console.error('Failure sending notification to', tokens[index], error); // Cleanup the tokens who are not registered anymore. - if (error.code === 'messaging/invalid-registration-token' || - error.code === 'messaging/registration-token-not-registered') { + if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') { tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove()); } } diff --git a/linkedin-auth/functions/index.js b/linkedin-auth/functions/index.js index b10e1ec804..da27a8dcab 100644 --- a/linkedin-auth/functions/index.js +++ b/linkedin-auth/functions/index.js @@ -36,9 +36,9 @@ function linkedInClient() { // LinkedIn OAuth 2 setup // TODO: Configure the `linkedin.client_id` and `linkedin.client_secret` Google Cloud environment variables. return require('node-linkedin')( - functions.config().linkedin.client_id, - functions.config().linkedin.client_secret, - `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`); + functions.config().linkedin.client_id, + functions.config().linkedin.client_secret, + `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`); } /** diff --git a/template-handlebars/functions/index.js b/template-handlebars/functions/index.js index 3e62de9860..a0ed2a3dd9 100644 --- a/template-handlebars/functions/index.js +++ b/template-handlebars/functions/index.js @@ -18,6 +18,7 @@ const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); + const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); From c681d93d6f51bc2bbd760c2edd999c5c4e5b705d Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Wed, 7 Feb 2018 16:31:04 -0800 Subject: [PATCH 12/16] fixed comments for template-handlebars/functions/firebaseUser.js --- template-handlebars/functions/firebaseUser.js | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/template-handlebars/functions/firebaseUser.js b/template-handlebars/functions/firebaseUser.js index c29338fc3b..18094028fd 100644 --- a/template-handlebars/functions/firebaseUser.js +++ b/template-handlebars/functions/firebaseUser.js @@ -1,18 +1,18 @@ /** -* Copyright 2016 Google Inc. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ 'use strict'; const admin = require('firebase-admin'); @@ -37,8 +37,8 @@ const validateFirebaseIdToken = (req, res, next) => { }; /** -* Returns a Promise with the Firebase ID Token if found in the Authorization or the __session cookie. -*/ + * Returns a Promise with the Firebase ID Token if found in the Authorization or the __session cookie. + */ function getIdTokenFromRequest(req, res) { if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) { console.log('Found "Authorization" header'); @@ -59,8 +59,8 @@ function getIdTokenFromRequest(req, res) { } /** -* Returns a Promise with the Decoded ID Token and adds it to req.user. -*/ + * Returns a Promise with the Decoded ID Token and adds it to req.user. + */ function addDecodedIdTokenToRequest(idToken, req) { return admin.auth().verifyIdToken(idToken).then(decodedIdToken => { req.user = decodedIdToken; @@ -70,4 +70,4 @@ function addDecodedIdTokenToRequest(idToken, req) { }); } -exports.validateFirebaseIdToken = validateFirebaseIdToken; +exports.validateFirebaseIdToken = validateFirebaseIdToken; \ No newline at end of file From 3efe9ca3c5b636aa30a11210e103118f1fea397f Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Wed, 7 Feb 2018 16:49:16 -0800 Subject: [PATCH 13/16] fixed indentations --- child-count/functions/index.js | 2 +- coupon-on-purchase/functions/index.js | 6 +-- delete-old-child-nodes/functions/index.js | 28 ++++++------ ffmpeg-convert-audio/functions/index.js | 52 ++++++++++----------- github-to-slack/functions/index.js | 56 +++++++++++------------ 5 files changed, 72 insertions(+), 72 deletions(-) diff --git a/child-count/functions/index.js b/child-count/functions/index.js index 0c3b3f2ffa..813f89e029 100644 --- a/child-count/functions/index.js +++ b/child-count/functions/index.js @@ -37,7 +37,7 @@ exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid} // Return the promise from countRef.transaction() so our function // waits for this async event to complete before it exits. return countRef.transaction(current => { - (current || 0) + increment; + return (current || 0) + increment; }).then(() => { return console.log('Counter updated.'); }); diff --git a/coupon-on-purchase/functions/index.js b/coupon-on-purchase/functions/index.js index 0187872297..cc4c59b52e 100644 --- a/coupon-on-purchase/functions/index.js +++ b/coupon-on-purchase/functions/index.js @@ -112,9 +112,9 @@ function sendHighValueCouponViaFCM(uid, userLanguage) { } /** - * Get the Device Tokens for the given user. - * - * @param {string} uid The UID of the user. + * Get the Device Tokens for the given user. + * + * @param {string} uid The UID of the user. */ function getDeviceTokens(uid) { return admin.database().ref(`/users/${uid}/tokens`).once('value').then(snap => { diff --git a/delete-old-child-nodes/functions/index.js b/delete-old-child-nodes/functions/index.js index 8a41460da9..77ddb1ccbc 100644 --- a/delete-old-child-nodes/functions/index.js +++ b/delete-old-child-nodes/functions/index.js @@ -27,18 +27,18 @@ const CUT_OFF_TIME = 2 * 60 * 60 * 1000; // 2 Hours in milliseconds. * cut-off time. Each child needs to have a `timestamp` attribute. */ exports.deleteOldItems = functions.database.ref('/path/to/items/{pushId}') - .onWrite(event => { - const ref = event.data.ref.parent; // reference to the items - const now = Date.now(); - const cutoff = now - CUT_OFF_TIME; - const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff); - return oldItemsQuery.once('value').then(snapshot => { - // create a map with all children that need to be removed - const updates = {}; - snapshot.forEach(child => { - updates[child.key] = null; + .onWrite(event => { + const ref = event.data.ref.parent; // reference to the items + const now = Date.now(); + const cutoff = now - CUT_OFF_TIME; + const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff); + return oldItemsQuery.once('value').then(snapshot => { + // create a map with all children that need to be removed + const updates = {}; + snapshot.forEach(child => { + updates[child.key] = null; + }); + // execute all updates in one go and return the result to end the function + return ref.update(updates); }); - // execute all updates in one go and return the result to end the function - return ref.update(updates); - }); - }); + }); \ No newline at end of file diff --git a/ffmpeg-convert-audio/functions/index.js b/ffmpeg-convert-audio/functions/index.js index 96efc6d2f5..79304c4675 100644 --- a/ffmpeg-convert-audio/functions/index.js +++ b/ffmpeg-convert-audio/functions/index.js @@ -26,13 +26,13 @@ const ffmpeg_static = require('ffmpeg-static'); function promisifyCommand(command) { return new Promise((resolve, reject) => { command - .on('end', () => { - resolve(); - }) - .on('error', error => { - reject(error); - }) - .run(); + .on('end', () => { + resolve(); + }) + .on('error', error => { + reject(error); + }) + .run(); }); } @@ -42,18 +42,18 @@ function promisifyCommand(command) { function reencodeAsync(tempFilePath, targetTempFilePath) { return new Promise((resolve, reject) => { const command = ffmpeg(tempFilePath) - .setFfmpegPath(ffmpeg_static.path) - .audioChannels(1) - .audioFrequency(16000) - .format('flac') - .on('error', (err) => { - console.log('An error occurred: ' + err.message); - reject(err); - }) - .on('end', () => { - console.log('Output audio created at', targetTempFilePath); - }) - .save(targetTempFilePath); + .setFfmpegPath(ffmpeg_static.path) + .audioChannels(1) + .audioFrequency(16000) + .format('flac') + .on('error', (err) => { + console.log('An error occurred: ' + err.message); + reject(err); + }) + .on('end', () => { + console.log('Output audio created at', targetTempFilePath); + }) + .save(targetTempFilePath); }); } @@ -112,11 +112,11 @@ exports.generateMonoAudio = functions.storage.object().onChange(event => { // Convert the audio to mono channel using FFMPEG. let command = ffmpeg(tempFilePath) - .setFfmpegPath(ffmpeg_static.path) - .audioChannels(1) - .audioFrequency(16000) - .format('flac') - .output(targetTempFilePath); + .setFfmpegPath(ffmpeg_static.path) + .audioChannels(1) + .audioFrequency(16000) + .format('flac') + .output(targetTempFilePath); command = promisifyCommand(command); @@ -124,7 +124,7 @@ exports.generateMonoAudio = functions.storage.object().onChange(event => { }).then(() => { console.log('Output audio created at', targetTempFilePath); // Uploading the audio. - return bucket.upload(targetTempFilePath, { destination: targetStorageFilePath }) + return bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}) }).then(() => { console.log('Output audio uploaded to', targetStorageFilePath); @@ -134,4 +134,4 @@ exports.generateMonoAudio = functions.storage.object().onChange(event => { return console.log('Temporary files removed.', targetTempFilePath); }); -}); +}); \ No newline at end of file diff --git a/github-to-slack/functions/index.js b/github-to-slack/functions/index.js index c09cfd609c..cbb0adb0fa 100644 --- a/github-to-slack/functions/index.js +++ b/github-to-slack/functions/index.js @@ -25,39 +25,39 @@ const secureCompare = require('secure-compare'); * Slack. */ exports.githubWebhook = functions.https.onRequest((req, res) => { - const cipher = 'sha1'; - const signature = req.headers['x-hub-signature']; + const cipher = 'sha1'; + const signature = req.headers['x-hub-signature']; - // TODO: Configure the `github.secret` Google Cloud environment variables. - const hmac = crypto.createHmac(cipher, functions.config().github.secret) - .update(req.body) - .digest('hex'); - const expectedSignature = `${cipher}=${hmac}`; + // TODO: Configure the `github.secret` Google Cloud environment variables. + const hmac = crypto.createHmac(cipher, functions.config().github.secret) + .update(req.body) + .digest('hex'); + const expectedSignature = `${cipher}=${hmac}`; - // Check that the body of the request has been signed with the GitHub Secret. - if (!secureCompare(signature, expectedSignature)) { - console.error('x-hub-signature', signature, 'did not match', expectedSignature); - return res.status(403).send('Your x-hub-signature\'s bad and you should feel bad!'); - } - return postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => { - return res.end(); - }).catch(error => { - console.error(error); - return res.status(500).send('Something went wrong while posting the message to Slack.'); - }); + // Check that the body of the request has been signed with the GitHub Secret. + if (!secureCompare(signature, expectedSignature)) { + console.error('x-hub-signature', signature, 'did not match', expectedSignature); + return res.status(403).send('Your x-hub-signature\'s bad and you should feel bad!'); + } + return postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => { + return res.end(); + }).catch(error => { + console.error(error); + return res.status(500).send('Something went wrong while posting the message to Slack.'); + }); }); /** * Post a message to Slack about the new GitHub commit. */ function postToSlack(url, commits, repo) { - return rp({ - method: 'POST', - // TODO: Configure the `slack.webhook_url` Google Cloud environment variables. - uri: functions.config().slack.webhook_url, - body: { - text: `<${url}|${commits} new commit${commits > 1 ? 's' : ''}> pushed to <${repo.url}|${repo.full_name}>.` - }, - json: true - }); -} + return rp({ + method: 'POST', + // TODO: Configure the `slack.webhook_url` Google Cloud environment variables. + uri: functions.config().slack.webhook_url, + body: { + text: `<${url}|${commits} new commit${commits > 1 ? 's' : ''}> pushed to <${repo.url}|${repo.full_name}>.` + }, + json: true + }); +} \ No newline at end of file From 965e39b0fd2cdb81ef75685aedd4fda912e3190e Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Wed, 7 Feb 2018 18:01:00 -0800 Subject: [PATCH 14/16] passes eslint-config-google standards --- assistant-say-number/functions/index.js | 6 +- authenticated-json-api/functions/index.js | 26 ++++----- authorized-https-endpoint/functions/index.js | 4 +- bigquery-import/functions/index.js | 4 +- child-count/functions/index.js | 11 ++-- convert-images/functions/index.js | 2 +- coupon-on-purchase/functions/index.js | 24 ++++---- .../email-notifier/functions/index.js | 22 +++---- .../jira-issue/functions/index.js | 28 ++++----- .../slack-notifier/functions/index.js | 14 ++--- delete-old-child-nodes/functions/index.js | 8 +-- .../functions/index.js | 20 +++---- developer-motivator/functions/index.js | 12 ++-- email-confirmation/functions/index.js | 14 ++--- exif-images/functions/index.js | 6 +- fcm-notifications/functions/index.js | 10 ++-- ffmpeg-convert-audio/functions/index.js | 58 +++++++++---------- fulltext-search-firestore/functions/index.js | 14 ++--- fulltext-search/functions/index.js | 10 ++-- generate-thumbnail/functions/index.js | 12 ++-- github-to-slack/functions/index.js | 8 +-- google-sheet-sync/functions/index.js | 20 +++---- image-maker/functions/index.js | 20 +++---- image-sharp/functions/index.js | 2 +- instagram-auth/functions/index.js | 34 +++++------ lastmodified-tracking/functions/index.js | 2 +- limit-children/functions/index.js | 4 +- line-auth/functions/index.js | 32 +++++----- linkedin-auth/functions/index.js | 18 +++--- message-translation/functions/index.js | 6 +- minimal-webhook/functions/index.js | 6 +- moderate-images/functions/index.js | 4 +- .../src/functions/index.js | 2 +- presence-firestore/functions/index.js | 4 +- quickstarts/email-users/functions/index.js | 14 ++--- .../pubsub-helloworld/functions/index.js | 6 +- quickstarts/thumbnails/functions/index.js | 8 +-- quickstarts/time-server/functions/index.js | 4 +- .../uppercase-firestore/functions/index.js | 6 +- quickstarts/uppercase/functions/index.js | 6 +- spotify-auth/functions/index.js | 14 ++--- stripe/functions/index.js | 54 ++++++++--------- survey-app-update/functions/index.js | 6 +- template-handlebars/functions/index.js | 2 +- text-moderation/functions/index.js | 6 +- url-shortener/functions/index.js | 14 ++--- username-password-auth/functions/index.js | 29 +++++----- 47 files changed, 318 insertions(+), 318 deletions(-) diff --git a/assistant-say-number/functions/index.js b/assistant-say-number/functions/index.js index f086d9d5a6..22836571dc 100644 --- a/assistant-say-number/functions/index.js +++ b/assistant-say-number/functions/index.js @@ -30,12 +30,12 @@ exports.sayNumber = functions.https.onRequest((req, res) => { const reprompts = [ 'I didn\'t hear a number', 'If you\'re still there, what\'s the number?', - 'What is the number?' + 'What is the number?', ]; const actionMap = new Map(); - actionMap.set(assistant.StandardIntents.MAIN, assistant => { + actionMap.set(assistant.StandardIntents.MAIN, (assistant) => { const inputPrompt = assistant.buildInputPrompt(true, ` Hi! I can read out an ordinal number like 123. @@ -45,7 +45,7 @@ exports.sayNumber = functions.https.onRequest((req, res) => { assistant.ask(inputPrompt); }); - actionMap.set(assistant.StandardIntents.TEXT, assistant => { + actionMap.set(assistant.StandardIntents.TEXT, (assistant) => { const rawInput = assistant.getRawInput(); if (rawInput === 'bye') { assistant.tell('Goodbye!'); diff --git a/authenticated-json-api/functions/index.js b/authenticated-json-api/functions/index.js index 54b793e7bf..ae943071fd 100644 --- a/authenticated-json-api/functions/index.js +++ b/authenticated-json-api/functions/index.js @@ -36,10 +36,10 @@ const authenticate = (req, res, next) => { return; } const idToken = req.headers.authorization.split('Bearer ')[1]; - admin.auth().verifyIdToken(idToken).then(decodedIdToken => { + admin.auth().verifyIdToken(idToken).then((decodedIdToken) => { req.user = decodedIdToken; return next(); - }).catch(error => { + }).catch(() => { res.status(403).send('Unauthorized'); }); }; @@ -52,16 +52,16 @@ app.use(authenticate); app.post('/messages', (req, res) => { const message = req.body.message; - language.detectSentiment(message).then(results => { + language.detectSentiment(message).then((results) => { const category = categorizeScore(results[0].score); const data = {message: message, sentiment: results, category: category}; return admin.database().ref(`/users/${req.user.uid}/messages`).push(data); - }).then(snapshot => { + }).then((snapshot) => { return snapshot.ref.once('value'); - }).then(snapshot => { + }).then((snapshot) => { const val = snapshot.val(); return res.status(201).json({message: val.message, category: val.category}); - }).catch(error => { + }).catch((error) => { console.log('Error detecting sentiment or saving message', error.message); res.sendStatus(500); }); @@ -80,14 +80,14 @@ app.get('/messages', (req, res) => { return res.status(404).json({errorCode: 404, errorMessage: `category '${category}' not found`}); } - return query.once('value').then(snapshot => { - var messages = []; - snapshot.forEach(childSnapshot => { + return query.once('value').then((snapshot) => { + let messages = []; + snapshot.forEach((childSnapshot) => { messages.push({key: childSnapshot.key, message: childSnapshot.val().message}); }); return res.status(200).json(messages); - }).catch(error => { + }).catch((error) => { console.log('Error getting messages', error.message); res.sendStatus(500); }); @@ -97,12 +97,12 @@ app.get('/messages', (req, res) => { // Get details about a message app.get('/message/:messageId', (req, res) => { const messageId = req.params.messageId; - admin.database().ref(`/users/${req.user.uid}/messages/${messageId}`).once('value').then(snapshot => { + admin.database().ref(`/users/${req.user.uid}/messages/${messageId}`).once('value').then((snapshot) => { if (snapshot.val() === null) { return res.status(404).json({errorCode: 404, errorMessage: `message '${messageId}' not found`}); } return res.set('Cache-Control', 'private, max-age=300'); - }).catch(error => { + }).catch((error) => { console.log('Error getting message details', messageId, error.message); res.sendStatus(500); }); @@ -112,7 +112,7 @@ app.get('/message/:messageId', (req, res) => { exports.api = functions.https.onRequest(app); // Helper function to categorize a sentiment score as positive, negative, or neutral -const categorizeScore = score => { +const categorizeScore = (score) => { if (score > 0.25) { return 'positive'; } else if (score < -0.25) { diff --git a/authorized-https-endpoint/functions/index.js b/authorized-https-endpoint/functions/index.js index d21be63035..3d7e8f29f1 100644 --- a/authorized-https-endpoint/functions/index.js +++ b/authorized-https-endpoint/functions/index.js @@ -50,11 +50,11 @@ const validateFirebaseIdToken = (req, res, next) => { // Read the ID Token from cookie. idToken = req.cookies.__session; } - admin.auth().verifyIdToken(idToken).then(decodedIdToken => { + admin.auth().verifyIdToken(idToken).then((decodedIdToken) => { console.log('ID Token correctly decoded', decodedIdToken); req.user = decodedIdToken; return next(); - }).catch(error => { + }).catch((error) => { console.error('Error while verifying Firebase ID token:', error); res.status(403).send('Unauthorized'); }); diff --git a/bigquery-import/functions/index.js b/bigquery-import/functions/index.js index 846f2eb847..1ebbc44238 100644 --- a/bigquery-import/functions/index.js +++ b/bigquery-import/functions/index.js @@ -21,7 +21,7 @@ const bigquery = require('@google-cloud/bigquery')(); /** * Writes all logs from the Realtime Database into bigquery. */ -exports.addtobigquery = functions.database.ref('/logs/{logid}').onWrite(event => { +exports.addtobigquery = functions.database.ref('/logs/{logid}').onWrite((event) => { // TODO: Make sure you set the `bigquery.datasetName` Google Cloud environment variable. const dataset = bigquery.dataset(functions.config().bigquery.datasetname); // TODO: Make sure you set the `bigquery.tableName` Google Cloud environment variable. @@ -30,6 +30,6 @@ exports.addtobigquery = functions.database.ref('/logs/{logid}').onWrite(event => return table.insert({ ID: event.data.key, MESSAGE: event.data.val().message, - NUMBER: event.data.val().number + NUMBER: event.data.val().number, }); }); diff --git a/child-count/functions/index.js b/child-count/functions/index.js index 813f89e029..718e36eea1 100644 --- a/child-count/functions/index.js +++ b/child-count/functions/index.js @@ -20,15 +20,14 @@ const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); // Keeps track of the length of the 'likes' child list in a separate property. -exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(event => { +exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite((event) => { const collectionRef = event.data.ref.parent; const countRef = collectionRef.parent.child('likes_count'); let increment; if (event.data.exists() && !event.data.previous.exists()) { increment = 1; - } - else if (!event.data.exists() && event.data.previous.exists()) { + } else if (!event.data.exists() && event.data.previous.exists()) { increment = -1; } else { return null; @@ -36,7 +35,7 @@ exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid} // Return the promise from countRef.transaction() so our function // waits for this async event to complete before it exits. - return countRef.transaction(current => { + return countRef.transaction((current) => { return (current || 0) + increment; }).then(() => { return console.log('Counter updated.'); @@ -44,7 +43,7 @@ exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid} }); // If the number of likes gets deleted, recount the number of likes -exports.recountlikes = functions.database.ref('/posts/{postid}/likes_count').onWrite(event => { +exports.recountlikes = functions.database.ref('/posts/{postid}/likes_count').onWrite((event) => { if (!event.data.exists()) { const counterRef = event.data.ref; const collectionRef = counterRef.parent.child('likes'); @@ -52,7 +51,7 @@ exports.recountlikes = functions.database.ref('/posts/{postid}/likes_count').onW // Return the promise from counterRef.set() so our function // waits for this async event to complete before it exits. return collectionRef.once('value') - .then(messagesData => counterRef.set(messagesData.numChildren())); + .then((messagesData) => counterRef.set(messagesData.numChildren())); } return null; }); diff --git a/convert-images/functions/index.js b/convert-images/functions/index.js index c0917caa8e..cd0decb24c 100644 --- a/convert-images/functions/index.js +++ b/convert-images/functions/index.js @@ -30,7 +30,7 @@ const JPEG_EXTENSION = '.jpg'; * When an image is uploaded in the Storage bucket it is converted to JPEG automatically using * ImageMagick. */ -exports.imageToJPG = functions.storage.object().onChange(event => { +exports.imageToJPG = functions.storage.object().onChange((event) => { const object = event.data; const filePath = object.name; const baseFileName = path.basename(filePath, path.extname(filePath)); diff --git a/coupon-on-purchase/functions/index.js b/coupon-on-purchase/functions/index.js index cc4c59b52e..3b5e055cfd 100644 --- a/coupon-on-purchase/functions/index.js +++ b/coupon-on-purchase/functions/index.js @@ -24,7 +24,7 @@ admin.initializeApp(functions.config().firebase); * After a user has completed a purchase, send them a coupon via FCM valid on their next purchase. */ // [START trigger] -exports.sendCouponOnPurchase = functions.analytics.event('in_app_purchase').onLog(event => { +exports.sendCouponOnPurchase = functions.analytics.event('in_app_purchase').onLog((event) => { // [END trigger] // [START attributes] const user = event.data.user; @@ -49,14 +49,14 @@ exports.sendCouponOnPurchase = functions.analytics.event('in_app_purchase').onLo */ function sendCouponViaFCM(uid, userLanguage) { // Fetching all the user's device tokens. - return getDeviceTokens(uid).then(tokens => { + return getDeviceTokens(uid).then((tokens) => { if (tokens.length > 0) { // Notification details. let payload = { notification: { title: 'Thanks for your Purchase!', - body: 'Get 10% off your next purchase with "COMEBACK10".' - } + body: 'Get 10% off your next purchase with "COMEBACK10".', + }, }; // Notification in French. @@ -64,8 +64,8 @@ function sendCouponViaFCM(uid, userLanguage) { payload = { notification: { title: 'Merci pour votre achat!', - body: 'Obtenez 10% de réduction sur votre prochain achat avec "COMEBACK10".' - } + body: 'Obtenez 10% de réduction sur votre prochain achat avec "COMEBACK10".', + }, }; } @@ -84,14 +84,14 @@ function sendCouponViaFCM(uid, userLanguage) { */ function sendHighValueCouponViaFCM(uid, userLanguage) { // Fetching all the user's device tokens. - return getDeviceTokens(uid).then(tokens => { + return getDeviceTokens(uid).then((tokens) => { if (tokens.length > 0) { // Notification details. let payload = { notification: { title: 'Thanks for your Purchase!', - body: 'Get 30% off your next purchase with "COMEBACK30".' - } + body: 'Get 30% off your next purchase with "COMEBACK30".', + }, }; // Notification in French. @@ -99,8 +99,8 @@ function sendHighValueCouponViaFCM(uid, userLanguage) { payload = { notification: { title: 'Merci pour votre achat!', - body: 'Obtenez 30% de réduction sur votre prochain achat avec "COMEBACK30".' - } + body: 'Obtenez 30% de réduction sur votre prochain achat avec "COMEBACK30".', + }, }; } @@ -117,7 +117,7 @@ function sendHighValueCouponViaFCM(uid, userLanguage) { * @param {string} uid The UID of the user. */ function getDeviceTokens(uid) { - return admin.database().ref(`/users/${uid}/tokens`).once('value').then(snap => { + return admin.database().ref(`/users/${uid}/tokens`).once('value').then((snap) => { if (snap.exists()) { return Object.keys(snap.val()); } diff --git a/crashlytics-integration/email-notifier/functions/index.js b/crashlytics-integration/email-notifier/functions/index.js index 49c477e9ec..abfb221c54 100644 --- a/crashlytics-integration/email-notifier/functions/index.js +++ b/crashlytics-integration/email-notifier/functions/index.js @@ -15,13 +15,13 @@ */ 'use strict'; -const functions = require('firebase-functions'), - sendgridMail = require('@sendgrid/mail'); +const functions = require('firebase-functions'); +const sendgridMail = require('@sendgrid/mail'); // Authentication for the SendGrid account sendgridMail.setApiKey(functions.config().sendgrid.api_key); -exports.sendOnNewIssue = functions.crashlytics.issue().onNewDetected(event => { +exports.sendOnNewIssue = functions.crashlytics.issue().onNewDetected((event) => { const data = event.data; const issueId = data.issueId; @@ -43,17 +43,17 @@ exports.sendOnNewIssue = functions.crashlytics.issue().onNewDetected(event => {

Version: ${latestAppVersion}

Issue Id: ${issueId}

Issue Title: ${issueTitle}

-

Creation Time: ${createTime}

` +

Creation Time: ${createTime}

`, }; return sendgridMail.send(emailDetails).then(() => { return console.log('Successfully sent new issue email'); - }).catch(error => { + }).catch((error) => { console.error(error.toString()); }); }); -exports.sendOnRegressedIssue = functions.crashlytics.issue().onRegressed(event => { +exports.sendOnRegressedIssue = functions.crashlytics.issue().onRegressed((event) => { const data = event.data; const issueId = data.issueId; @@ -77,17 +77,17 @@ exports.sendOnRegressedIssue = functions.crashlytics.issue().onRegressed(event =

Issue Id: ${issueId}

Issue Title: ${issueTitle}

Creation Time: ${createTime}

-

Originally Resolved On: ${new Date(resolvedTime).toString()}

` +

Originally Resolved On: ${new Date(resolvedTime).toString()}

`, }; return sendgridMail.send(emailDetails).then(() => { return console.log('Successfully sent regressed issue email'); - }).catch(error => { + }).catch((error) => { console.error(error.toString()); }); }); -exports.sendOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert(event => { +exports.sendOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert((event) => { const data = event.data; const issueId = data.issueId; @@ -113,12 +113,12 @@ exports.sendOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert(even

Issue Id: ${issueId}

Issue Title: ${issueTitle}

Creation Time: ${createTime}

-

# of Total Crashes: ${crashes.toString()}

` +

# of Total Crashes: ${crashes.toString()}

`, }; return sendgridMail.send(emailDetails).then(() => { return console.log('Successfully sent velocity alert email'); - }).catch(error => { + }).catch((error) => { console.error(error.toString()); }); }); diff --git a/crashlytics-integration/jira-issue/functions/index.js b/crashlytics-integration/jira-issue/functions/index.js index 8d5ae2567b..14bee80301 100644 --- a/crashlytics-integration/jira-issue/functions/index.js +++ b/crashlytics-integration/jira-issue/functions/index.js @@ -15,11 +15,11 @@ */ 'use strict'; -const functions = require('firebase-functions'), - rp = require('request-promise'); +const functions = require('firebase-functions'); +const rp = require('request-promise'); // Helper function that calculates the priority of the issue -const calculateIssuePriority = eventType => { +const calculateIssuePriority = (eventType) => { // Run custom logic that can determine the priority or severity of this issue // For example, you can parse the stack trace to determine which part of your app // is causing the crash and assign priorities based on that @@ -44,7 +44,7 @@ const calculateIssuePriority = eventType => { // Helper function that parses the Jira project url and returns an object // of the url fragments -const parseUrl = url => { +const parseUrl = (url) => { // input url format: https://yourdomain.atlassian.net/projects/XX const matches = url.match(/(https?:\/\/)(.+?)(\/.+)?\/(projects|browse)\/([\w-]+)/); if (matches && matches.length === 6) { @@ -62,7 +62,7 @@ const createJiraIssue = (summary, description, priority) => { const issue_type = functions.config().jira.issue_type; const component_id = functions.config().jira.component_id; - const { protocol, domain, contextPath, projectKey} = parseUrl(project_url); + const {protocol, domain, contextPath, projectKey} = parseUrl(project_url); const baseUrl = [protocol, domain, contextPath].join(''); const url = `${baseUrl}/rest/api/2/issue`; @@ -71,16 +71,16 @@ const createJiraIssue = (summary, description, priority) => { const newIssue = { fields: { components: [{id: component_id || '10000'}], - project: {key: projectKey }, + project: {key: projectKey}, summary, description, issuetype: { - name: issue_type || 'Bug' + name: issue_type || 'Bug', }, priority: { id: priority.toString(), - } - } + }, + }, }; // Uses Basic Authentication @@ -89,16 +89,16 @@ const createJiraIssue = (summary, description, priority) => { return rp({ auth: { 'user': user, - 'pass': pass + 'pass': pass, }, method: 'POST', uri: url, body: newIssue, - json: true + json: true, }); }; -exports.createNewIssue = functions.crashlytics.issue().onNewDetected(event => { +exports.createNewIssue = functions.crashlytics.issue().onNewDetected((event) => { const data = event.data; const issueId = data.issueId; @@ -117,7 +117,7 @@ exports.createNewIssue = functions.crashlytics.issue().onNewDetected(event => { }); }); -exports.createRegressedIssue = functions.crashlytics.issue().onRegressed(event => { +exports.createRegressedIssue = functions.crashlytics.issue().onRegressed((event) => { const data = event.data; const issueId = data.issueId; @@ -138,7 +138,7 @@ exports.createRegressedIssue = functions.crashlytics.issue().onRegressed(event = }); }); -exports.createVelocityAlert = functions.crashlytics.issue().onVelocityAlert(event => { +exports.createVelocityAlert = functions.crashlytics.issue().onVelocityAlert((event) => { const data = event.data; const issueId = data.issueId; diff --git a/crashlytics-integration/slack-notifier/functions/index.js b/crashlytics-integration/slack-notifier/functions/index.js index eb47ba3501..21763d4be6 100644 --- a/crashlytics-integration/slack-notifier/functions/index.js +++ b/crashlytics-integration/slack-notifier/functions/index.js @@ -15,11 +15,11 @@ */ 'use strict'; -const functions = require('firebase-functions'), - rp = require('request-promise'); +const functions = require('firebase-functions'); +const rp = require('request-promise'); // Helper function that posts to Slack about the new issue -const notifySlack = slackMessage => { +const notifySlack = (slackMessage) => { // See https://api.slack.com/docs/message-formatting on how // to customize the message payload return rp({ @@ -28,11 +28,11 @@ const notifySlack = slackMessage => { body: { text: slackMessage, }, - json: true + json: true, }); }; -exports.postOnNewIssue = functions.crashlytics.issue().onNewDetected(event => { +exports.postOnNewIssue = functions.crashlytics.issue().onNewDetected((event) => { const data = event.data; const issueId = data.issueId; @@ -49,7 +49,7 @@ exports.postOnNewIssue = functions.crashlytics.issue().onNewDetected(event => { }); }); -exports.postOnRegressedIssue = functions.crashlytics.issue().onRegressed(event => { +exports.postOnRegressedIssue = functions.crashlytics.issue().onRegressed((event) => { const data = event.data; const issueId = data.issueId; @@ -68,7 +68,7 @@ exports.postOnRegressedIssue = functions.crashlytics.issue().onRegressed(event = }); }); -exports.postOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert(event => { +exports.postOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert((event) => { const data = event.data; const issueId = data.issueId; diff --git a/delete-old-child-nodes/functions/index.js b/delete-old-child-nodes/functions/index.js index 77ddb1ccbc..a142932aba 100644 --- a/delete-old-child-nodes/functions/index.js +++ b/delete-old-child-nodes/functions/index.js @@ -27,18 +27,18 @@ const CUT_OFF_TIME = 2 * 60 * 60 * 1000; // 2 Hours in milliseconds. * cut-off time. Each child needs to have a `timestamp` attribute. */ exports.deleteOldItems = functions.database.ref('/path/to/items/{pushId}') - .onWrite(event => { + .onWrite((event) => { const ref = event.data.ref.parent; // reference to the items const now = Date.now(); const cutoff = now - CUT_OFF_TIME; const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff); - return oldItemsQuery.once('value').then(snapshot => { + return oldItemsQuery.once('value').then((snapshot) => { // create a map with all children that need to be removed const updates = {}; - snapshot.forEach(child => { + snapshot.forEach((child) => { updates[child.key] = null; }); // execute all updates in one go and return the result to end the function return ref.update(updates); }); - }); \ No newline at end of file + }); diff --git a/delete-unused-accounts-cron/functions/index.js b/delete-unused-accounts-cron/functions/index.js index 293ade0d27..bdf2208bbe 100644 --- a/delete-unused-accounts-cron/functions/index.js +++ b/delete-unused-accounts-cron/functions/index.js @@ -44,10 +44,10 @@ exports.accountcleanup = functions.https.onRequest((req, res) => { // Fetch all user details. return getUsers(); -}).then(users => { +}).then((users) => { // Find users that have not signed in in the last 30 days. const inactiveUsers = users.filter( - user => parseInt(user.lastLoginAt, 10) < Date.now() - 30 * 24 * 60 * 60 * 1000); + (user) => parseInt(user.lastLoginAt, 10) < Date.now() - 30 * 24 * 60 * 60 * 1000); // Use a pool so that we delete maximum `MAX_CONCURRENT` users in parallel. const promisePool = new PromisePool(() => { @@ -62,7 +62,7 @@ exports.accountcleanup = functions.https.onRequest((req, res) => { return promisePool.start(); }).then(() => { return console.log('Deleted user account', userToDelete.localId, 'because of inactivity'); - }).catch(error => { + }).catch((error) => { console.error('Deletion of inactive user account', userToDelete.localId, 'failed:', error); }).then(() => { console.log('User cleanup finished'); @@ -73,19 +73,19 @@ exports.accountcleanup = functions.https.onRequest((req, res) => { * Returns the list of all users with their ID and lastLogin timestamp. */ function getUsers(userIds = [], nextPageToken, accessToken) { - return getAccessToken(accessToken).then(accessToken => { + return getAccessToken(accessToken).then((accessToken) => { const options = { method: 'POST', uri: 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/downloadAccount?fields=users/localId,users/lastLoginAt,nextPageToken&access_token=' + accessToken, body: { nextPageToken: nextPageToken, - maxResults: 1000 + maxResults: 1000, }, - json: true + json: true, }; - return rp(options) - }).then(resp => { + return rp(options); + }).then((resp) => { if (!resp.users) { return userIds; } @@ -108,8 +108,8 @@ function getAccessToken(accessToken) { const options = { uri: 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token', headers: {'Metadata-Flavor': 'Google'}, - json: true + json: true, }; - return rp(options).then(resp => resp.access_token); + return rp(options).then((resp) => resp.access_token); } diff --git a/developer-motivator/functions/index.js b/developer-motivator/functions/index.js index cda6930157..9a8cd510c7 100644 --- a/developer-motivator/functions/index.js +++ b/developer-motivator/functions/index.js @@ -26,12 +26,12 @@ const deviceToken = functions.config().dev_motivator.device_token; * * The device model name, the city and the country of the user are sent in the notification message */ -exports.appinstalled = functions.analytics.event('first_open').onLog(event => { +exports.appinstalled = functions.analytics.event('first_open').onLog((event) => { const payload = { notification: { title: 'you have a new user \uD83D\uDE43', - body: event.data.user.deviceInfo.mobileModelName + ' from ' + event.data.user.geoInfo.city + ', ' + event.data.user.geoInfo.country - } + body: event.data.user.deviceInfo.mobileModelName + ' from ' + event.data.user.geoInfo.city + ', ' + event.data.user.geoInfo.country, + }, }; admin.messaging().sendToDevice(deviceToken, payload); }); @@ -43,12 +43,12 @@ exports.appinstalled = functions.analytics.event('first_open').onLog(event => { * * The device model name, the city and the country of the user are sent in the notification message */ -exports.appremoved = functions.analytics.event('app_remove').onLog(event => { +exports.appremoved = functions.analytics.event('app_remove').onLog((event) => { const payload = { notification: { title: 'you lost a user \uD83D\uDE1E', - body: event.data.user.deviceInfo.mobileModelName + ' from ' + event.data.user.geoInfo.city + ', ' + event.data.user.geoInfo.country - } + body: event.data.user.deviceInfo.mobileModelName + ' from ' + event.data.user.geoInfo.city + ', ' + event.data.user.geoInfo.country, + }, }; admin.messaging().sendToDevice(deviceToken, payload); diff --git a/email-confirmation/functions/index.js b/email-confirmation/functions/index.js index 7d45ca967b..2e96533996 100644 --- a/email-confirmation/functions/index.js +++ b/email-confirmation/functions/index.js @@ -26,12 +26,12 @@ const mailTransport = nodemailer.createTransport({ service: 'gmail', auth: { user: gmailEmail, - pass: gmailPassword - } + pass: gmailPassword, + }, }); // Sends an email confirmation when a user changes his mailing list subscription. -exports.sendEmailConfirmation = functions.database.ref('/users/{uid}').onWrite(event => { +exports.sendEmailConfirmation = functions.database.ref('/users/{uid}').onWrite((event) => { const snapshot = event.data; const val = snapshot.val(); @@ -41,16 +41,16 @@ exports.sendEmailConfirmation = functions.database.ref('/users/{uid}').onWrite(e const mailOptions = { from: '"Spammy Corp." ', - to: val.email + to: val.email, }; - + const subscribed = val.subscribedToMailingList; // Building Email message. mailOptions.subject = subscribed ? 'Thanks and Welcome!' : 'Sad to see you go :`('; mailOptions.text = subscribed ? 'Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.' : 'I hereby confirm that I will stop sending you the newsletter.'; - + return mailTransport.sendMail(mailOptions) .then(() => console.log(`New ${subscribed ? '' : 'un'}subscription confirmation email sent to:`, val.email)) - .catch(error => console.error('There was an error while sending the email:', error)); + .catch((error) => console.error('There was an error while sending the email:', error)); }); diff --git a/exif-images/functions/index.js b/exif-images/functions/index.js index 5f56f0dc45..9c1580cc45 100644 --- a/exif-images/functions/index.js +++ b/exif-images/functions/index.js @@ -30,7 +30,7 @@ const spawn = require('child-process-promise').spawn; * When an image is uploaded in the Storage bucket the information and metadata of the image (the * output of ImageMagick's `identify -verbose`) is saved in the Realtime Database. */ -exports.metadata = functions.storage.object().onChange(event => { +exports.metadata = functions.storage.object().onChange((event) => { const object = event.data; const filePath = object.name; @@ -54,11 +54,11 @@ exports.metadata = functions.storage.object().onChange(event => { const bucket = gcs.bucket(object.bucket); return bucket.file(filePath).download({destination: tempLocalFile}).then(() => { // Get Metadata from image. - return spawn('identify', ['-verbose', tempLocalFile], { capture: [ 'stdout', 'stderr' ]}) + return spawn('identify', ['-verbose', tempLocalFile], {capture: ['stdout', 'stderr']}); }).then(() => { const metadata = imageMagickOutputToObject(result.stdout); // Save metadata to realtime datastore. - return admin.database().ref(makeKeyFirebaseCompatible(filePath)).set(metadata) + return admin.database().ref(makeKeyFirebaseCompatible(filePath)).set(metadata); }).then(() => { return console.log('Wrote to:', filePath, 'data:', metadata); }).then(() => { diff --git a/fcm-notifications/functions/index.js b/fcm-notifications/functions/index.js index 333d0badde..2c234acef2 100644 --- a/fcm-notifications/functions/index.js +++ b/fcm-notifications/functions/index.js @@ -25,7 +25,7 @@ admin.initializeApp(functions.config().firebase); * Followers add a flag to `/followers/{followedUid}/{followerUid}`. * Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`. */ -exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => { +exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite((event) => { const followerUid = event.params.followerUid; const followedUid = event.params.followedUid; // If un-follow we exit the function. @@ -40,7 +40,7 @@ exports.sendFollowerNotification = functions.database.ref('/followers/{followedU // Get the follower profile. const getFollowerProfilePromise = admin.auth().getUser(followerUid); - return Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]).then(results => { + return Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]).then((results) => { const tokensSnapshot = results[0]; const follower = results[1]; @@ -56,8 +56,8 @@ exports.sendFollowerNotification = functions.database.ref('/followers/{followedU notification: { title: 'You have a new follower!', body: `${follower.displayName} is now following you.`, - icon: follower.photoURL - } + icon: follower.photoURL, + }, }; // Listing all tokens. @@ -65,7 +65,7 @@ exports.sendFollowerNotification = functions.database.ref('/followers/{followedU // Send notifications to all tokens. return admin.messaging().sendToDevice(tokens, payload); - }).then(response => { + }).then((response) => { // For each message check if there was an error. const tokensToRemove = []; response.results.forEach((result, index) => { diff --git a/ffmpeg-convert-audio/functions/index.js b/ffmpeg-convert-audio/functions/index.js index 79304c4675..79e17a4351 100644 --- a/ffmpeg-convert-audio/functions/index.js +++ b/ffmpeg-convert-audio/functions/index.js @@ -26,13 +26,13 @@ const ffmpeg_static = require('ffmpeg-static'); function promisifyCommand(command) { return new Promise((resolve, reject) => { command - .on('end', () => { - resolve(); - }) - .on('error', error => { - reject(error); - }) - .run(); + .on('end', () => { + resolve(); + }) + .on('error', (error) => { + reject(error); + }) + .run(); }); } @@ -42,18 +42,18 @@ function promisifyCommand(command) { function reencodeAsync(tempFilePath, targetTempFilePath) { return new Promise((resolve, reject) => { const command = ffmpeg(tempFilePath) - .setFfmpegPath(ffmpeg_static.path) - .audioChannels(1) - .audioFrequency(16000) - .format('flac') - .on('error', (err) => { - console.log('An error occurred: ' + err.message); - reject(err); - }) - .on('end', () => { - console.log('Output audio created at', targetTempFilePath); - }) - .save(targetTempFilePath); + .setFfmpegPath(ffmpeg_static.path) + .audioChannels(1) + .audioFrequency(16000) + .format('flac') + .on('error', (err) => { + console.log('An error occurred: ' + err.message); + reject(err); + }) + .on('end', () => { + console.log('Output audio created at', targetTempFilePath); + }) + .save(targetTempFilePath); }); } @@ -101,30 +101,30 @@ exports.generateMonoAudio = functions.storage.object().onChange(event => { const bucket = gcs.bucket(fileBucket); const tempFilePath = path.join(os.tmpdir(), fileName); // We add a '_output.flac' suffix to target audio file name. That's where we'll upload the converted audio. - const targetTempFileName = fileName.replace(/\.[^/.]+$/, "") + '_output.flac'; + const targetTempFileName = fileName.replace(/\.[^/.]+$/, '') + '_output.flac'; const targetTempFilePath = path.join(os.tmpdir(), targetTempFileName); const targetStorageFilePath = path.join(path.dirname(filePath), targetTempFileName); return bucket.file(filePath).download({ - destination: tempFilePath + destination: tempFilePath, }).then(() => { console.log('Audio downloaded locally to', tempFilePath); // Convert the audio to mono channel using FFMPEG. let command = ffmpeg(tempFilePath) - .setFfmpegPath(ffmpeg_static.path) - .audioChannels(1) - .audioFrequency(16000) - .format('flac') - .output(targetTempFilePath); + .setFfmpegPath(ffmpeg_static.path) + .audioChannels(1) + .audioFrequency(16000) + .format('flac') + .output(targetTempFilePath); command = promisifyCommand(command); - return command + return command; }).then(() => { console.log('Output audio created at', targetTempFilePath); // Uploading the audio. - return bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}) + return bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}); }).then(() => { console.log('Output audio uploaded to', targetStorageFilePath); @@ -134,4 +134,4 @@ exports.generateMonoAudio = functions.storage.object().onChange(event => { return console.log('Temporary files removed.', targetTempFilePath); }); -}); \ No newline at end of file +}); diff --git a/fulltext-search-firestore/functions/index.js b/fulltext-search-firestore/functions/index.js index 2df2b7966a..f6bd4fed4f 100644 --- a/fulltext-search-firestore/functions/index.js +++ b/fulltext-search-firestore/functions/index.js @@ -31,7 +31,7 @@ const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY); // [START update_index_function] // Update the search index every time a blog post is written. -exports.onNoteCreated = functions.firestore.document('notes/{noteId}').onCreate(event => { +exports.onNoteCreated = functions.firestore.document('notes/{noteId}').onCreate((event) => { // Get the note document const note = event.data.data(); @@ -66,14 +66,14 @@ function getFirebaseUser(req, res, next) { idToken = req.headers.authorization.split('Bearer ')[1]; } - admin + return admin .auth() .verifyIdToken(idToken) - .then(decodedIdToken => { + .then((decodedIdToken) => { console.log('ID Token correctly decoded', decodedIdToken); req.user = decodedIdToken; return next(); - }).catch(error => { + }).catch((error) => { console.error('Error while verifying Firebase ID token:', error); return res.status(403).send('Unauthorized'); }); @@ -87,7 +87,7 @@ const app = require('express')(); // We'll enable CORS support to allow the function to be invoked // from our app client-side. -app.use(require('cors')({ origin: true })); +app.use(require('cors')({origin: true})); // Then we'll also use a special 'getFirebaseUser' middleware which // verifies the Authorization header and adds a `user` field to the @@ -103,14 +103,14 @@ app.get('/', (req, res) => { // This filter ensures that only documents where author == user_id will be readable filters: `author:${req.user.user_id}`, // We also proxy the user_id as a unique token for this key. - userToken: req.user.user_id + userToken: req.user.user_id, }; // Call the Algolia API to generate a unique key based on our search key const key = client.generateSecuredApiKey(ALGOLIA_SEARCH_KEY, params); // Then return this key as {key: '...key'} - res.json({ key }); + res.json({key}); }); // Finally, pass our ExpressJS app to Cloud Functions as a function diff --git a/fulltext-search/functions/index.js b/fulltext-search/functions/index.js index ad5d06bbae..b90b63bec8 100644 --- a/fulltext-search/functions/index.js +++ b/fulltext-search/functions/index.js @@ -28,11 +28,11 @@ const client = algoliasearch(functions.config().algolia.app_id, functions.config const ALGOLIA_POSTS_INDEX_NAME = 'blogposts'; // Updates the search index when new blog entries are created or updated. -exports.indexentry = functions.database.ref('/blog-posts/{blogid}/text').onWrite(event => { +exports.indexentry = functions.database.ref('/blog-posts/{blogid}/text').onWrite((event) => { const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME); const firebaseObject = { text: event.data.val(), - objectID: event.params.blogid + objectID: event.params.blogid, }; return index.saveObject(firebaseObject).then( @@ -42,15 +42,15 @@ exports.indexentry = functions.database.ref('/blog-posts/{blogid}/text').onWrite // Starts a search query whenever a query is requested (by adding one to the `/search/queries` // element. Search results are then written under `/search/results`. -exports.searchentry = functions.database.ref('/search/queries/{queryid}').onWrite(event => { +exports.searchentry = functions.database.ref('/search/queries/{queryid}').onWrite((event) => { const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME); const query = event.data.val().query; const key = event.data.key; - return index.search(query).then(content => { + return index.search(query).then((content) => { const updates = { - '/search/last_query_timestamp': Date.parse(event.timestamp) + '/search/last_query_timestamp': Date.parse(event.timestamp), }; updates[`/search/results/${key}`] = content; return admin.database().ref().update(updates); diff --git a/generate-thumbnail/functions/index.js b/generate-thumbnail/functions/index.js index 190006e0d0..bee0ec6703 100644 --- a/generate-thumbnail/functions/index.js +++ b/generate-thumbnail/functions/index.js @@ -38,7 +38,7 @@ const THUMB_PREFIX = 'thumb_'; * After the thumbnail has been generated and uploaded to Cloud Storage, * we write the public URL to the Firebase Realtime Database. */ -exports.generateThumbnail = functions.storage.object().onChange(event => { +exports.generateThumbnail = functions.storage.object().onChange((event) => { // File and directory paths. const filePath = event.data.name; const contentType = event.data.contentType; // This is the image Mimme type @@ -71,7 +71,7 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { const bucket = gcs.bucket(event.data.bucket); const file = bucket.file(filePath); const thumbFile = bucket.file(thumbFilePath); - const metadata = { contentType: contentType }; + const metadata = {contentType: contentType}; // Create the temp directory where the storage file will be downloaded. return mkdirp(tempLocalDir).then(() => { @@ -84,7 +84,7 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { }).then(() => { console.log('Thumbnail created at', tempLocalThumbFile); // Uploading the Thumbnail. - return bucket.upload(tempLocalThumbFile, { destination: thumbFilePath, metadata: metadata }); + return bucket.upload(tempLocalThumbFile, {destination: thumbFilePath, metadata: metadata}); }).then(() => { console.log('Thumbnail uploaded to Storage at', thumbFilePath); // Once the image has been uploaded delete the local files to free up disk space. @@ -93,13 +93,13 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { // Get the Signed URLs for the thumbnail and original image. const config = { action: 'read', - expires: '03-01-2500' + expires: '03-01-2500', }; return Promise.all([ thumbFile.getSignedUrl(config), - file.getSignedUrl(config) + file.getSignedUrl(config), ]); - }).then(results => { + }).then((results) => { console.log('Got Signed URLs.'); const thumbResult = results[0]; const originalResult = results[1]; diff --git a/github-to-slack/functions/index.js b/github-to-slack/functions/index.js index cbb0adb0fa..7c60d5c922 100644 --- a/github-to-slack/functions/index.js +++ b/github-to-slack/functions/index.js @@ -41,7 +41,7 @@ exports.githubWebhook = functions.https.onRequest((req, res) => { } return postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => { return res.end(); - }).catch(error => { + }).catch((error) => { console.error(error); return res.status(500).send('Something went wrong while posting the message to Slack.'); }); @@ -56,8 +56,8 @@ function postToSlack(url, commits, repo) { // TODO: Configure the `slack.webhook_url` Google Cloud environment variables. uri: functions.config().slack.webhook_url, body: { - text: `<${url}|${commits} new commit${commits > 1 ? 's' : ''}> pushed to <${repo.url}|${repo.full_name}>.` + text: `<${url}|${commits} new commit${commits > 1 ? 's' : ''}> pushed to <${repo.url}|${repo.full_name}>.`, }, - json: true + json: true, }); -} \ No newline at end of file +} diff --git a/google-sheet-sync/functions/index.js b/google-sheet-sync/functions/index.js index 93113b65f9..9c11b5bf3a 100644 --- a/google-sheet-sync/functions/index.js +++ b/google-sheet-sync/functions/index.js @@ -19,7 +19,7 @@ const functions = require('firebase-functions'); const admin = require('firebase-admin'); -const { OAuth2Client } = require('google-auth-library'); +const {OAuth2Client} = require('google-auth-library'); const google = require('googleapis'); admin.initializeApp(functions.config().firebase); @@ -54,8 +54,8 @@ exports.authgoogleapi = functions.https.onRequest((req, res) => { res.redirect(functionsOauthClient.generateAuthUrl({ access_type: 'offline', scope: SCOPES, - prompt: 'consent' - })) + prompt: 'consent', + })); }); // setup for OauthCallback @@ -81,7 +81,7 @@ exports.oauthcallback = functions.https.onRequest((req, res) => { // trigger function to write to Sheet when new data comes in on CONFIG_DATA_PATH exports.appendrecordtospreadsheet = functions.database.ref(`${CONFIG_DATA_PATH}/{ITEM}`).onWrite( - event => { + (event) => { const newRecord = event.data.current.val(); return appendPromise({ spreadsheetId: CONFIG_SHEET_ID, @@ -89,8 +89,8 @@ exports.appendrecordtospreadsheet = functions.database.ref(`${CONFIG_DATA_PATH}/ valueInputOption: 'USER_ENTERED', insertDataOption: 'INSERT_ROWS', resource: { - values: [[newRecord.firstColumn, newRecord.secondColumn, newRecord.thirdColumn]] - } + values: [[newRecord.firstColumn, newRecord.secondColumn, newRecord.thirdColumn]], + }, }); } ); @@ -98,7 +98,7 @@ exports.appendrecordtospreadsheet = functions.database.ref(`${CONFIG_DATA_PATH}/ // accepts an append request, returns a Promise to append it, enriching it with auth function appendPromise(requestWithoutAuth) { return new Promise((resolve, reject) => { - return getAuthorizedClient().then(client => { + return getAuthorizedClient().then((client) => { const sheets = google.sheets('v4'); const request = requestWithoutAuth; request.auth = client; @@ -118,11 +118,11 @@ function getAuthorizedClient() { if (oauthTokens) { return Promise.resolve(functionsOauthClient); } - return db.ref(DB_TOKEN_PATH).once('value').then(snapshot => { + return db.ref(DB_TOKEN_PATH).once('value').then((snapshot) => { oauthTokens = snapshot.val(); functionsOauthClient.setCredentials(oauthTokens); return functionsOauthClient; - }) + }); } // HTTPS function to write new data to CONFIG_DATA_PATH, for testing @@ -134,7 +134,7 @@ exports.testsheetwrite = functions.https.onRequest((req, res) => { return db.ref(`${CONFIG_DATA_PATH}/${ID}`).set({ firstColumn: random1, secondColumn: random2, - thirdColumn: random3 + thirdColumn: random3, }).then(() => res.status(200).send( `Wrote ${random1}, ${random2}, ${random3} to DB, trigger should now update Sheet.`)); }); diff --git a/image-maker/functions/index.js b/image-maker/functions/index.js index 0f8417a3b0..ce66301fc4 100644 --- a/image-maker/functions/index.js +++ b/image-maker/functions/index.js @@ -27,27 +27,27 @@ app.get('/api/ray', (req, res) => { const tracers = JSON.parse(req.query.tracers); if (!_.isArray(tracers) || !_.every(tracers, (depth) => typeof depth === 'number')) { - //invalid format + // invalid format res.status(422); res.end(); } const canvas = new Canvas(243 * tracers.length, 243); const ctx = canvas.getContext('2d'); - for (var i=0; i { const colorOpts = req.query; - const canvas = new Canvas(320, 320) - const ctx = canvas.getContext('2d') + const canvas = new Canvas(320, 320); + const ctx = canvas.getContext('2d'); clock(ctx, colorOpts); res.set('Cache-Control', 'public, max-age=60, s-maxage=31536000'); - res.writeHead(200, { 'Content-Type': 'image/png' }) + res.writeHead(200, {'Content-Type': 'image/png'}); canvas.pngStream().pipe(res); }); @@ -55,15 +55,15 @@ app.get('/api/spark', (req, res) => { const dataSeries = JSON.parse(req.query.series); const colorOpts = req.query.colorOpts || {}; if (!_.isArray(dataSeries) || !_.every(dataSeries, (num) => typeof num === 'number')) { - //invalid format + // invalid format res.status(422); res.end(); } const canvas = new Canvas(320, 100); - var ctx = canvas.getContext('2d'); + let ctx = canvas.getContext('2d'); spark(ctx, dataSeries, colorOpts); res.set('Cache-Control', 'public, max-age=60, s-maxage=31536000'); - res.writeHead(200, { 'Content-Type': 'image/png' }) + res.writeHead(200, {'Content-Type': 'image/png'}); canvas.pngStream().pipe(res); }); diff --git a/image-sharp/functions/index.js b/image-sharp/functions/index.js index 036d2bb342..c3d054d0fd 100644 --- a/image-sharp/functions/index.js +++ b/image-sharp/functions/index.js @@ -67,7 +67,7 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { const bucket = gcs.bucket(fileBucket); const metadata = { - contentType: contentType + contentType: contentType, }; // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail. const thumbFileName = `thumb_${fileName}`; diff --git a/instagram-auth/functions/index.js b/instagram-auth/functions/index.js index 14182fb16a..8b4208a72a 100644 --- a/instagram-auth/functions/index.js +++ b/instagram-auth/functions/index.js @@ -24,7 +24,7 @@ const admin = require('firebase-admin'); const serviceAccount = require('./service-account.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), - databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com` + databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`, }); const OAUTH_REDIRECT_URI = `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`; @@ -39,12 +39,12 @@ function instagramOAuth2Client() { const credentials = { client: { id: functions.config().instagram.client_id, - secret: functions.config().instagram.client_secret + secret: functions.config().instagram.client_secret, }, auth: { tokenHost: 'https://api.instagram.com', - tokenPath: '/oauth/access_token' - } + tokenPath: '/oauth/access_token', + }, }; return require('simple-oauth2').create(credentials); } @@ -62,12 +62,12 @@ exports.redirect = functions.https.onRequest((req, res) => { res.cookie('state', state.toString(), { maxAge: 3600000, secure: true, - httpOnly: true + httpOnly: true, }); const redirectUri = oauth2.authorizationCode.authorizeURL({ redirect_uri: OAUTH_REDIRECT_URI, scope: OAUTH_SCOPES, - state: state + state: state, }); console.log('Redirecting to:', redirectUri); res.redirect(redirectUri); @@ -95,9 +95,9 @@ exports.token = functions.https.onRequest((req, res) => { console.log('Received auth code:', req.query.code); oauth2.authorizationCode.getToken({ code: req.query.code, - redirect_uri: OAUTH_REDIRECT_URI - }) - }).then(results => { + redirect_uri: OAUTH_REDIRECT_URI, + }); + }).then((results) => { console.log('Auth code exchange result received:', results); // We have an Instagram access token and the user identity now. @@ -107,16 +107,16 @@ exports.token = functions.https.onRequest((req, res) => { const userName = results.user.full_name; // Create a Firebase account and get the Custom Auth Token. - return createFirebaseAccount(instagramUserID, userName, profilePic, accessToken) - }).then(firebaseToken => { + return createFirebaseAccount(instagramUserID, userName, profilePic, accessToken); + }).then((firebaseToken) => { // Serve an HTML page that signs the user in and updates the user profile. return res.jsonp({ - token: firebaseToken + token: firebaseToken, }); }); } catch (error) { return res.jsonp({ - error: error.toString + error: error.toString, }); } }); @@ -138,14 +138,14 @@ function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) // Create or update the user account. const userCreationTask = admin.auth().updateUser(uid, { displayName: displayName, - photoURL: photoURL - }).catch(error => { + photoURL: photoURL, + }).catch((error) => { // If user does not exists we create it. if (error.code === 'auth/user-not-found') { return admin.auth().createUser({ uid: uid, displayName: displayName, - photoURL: photoURL + photoURL: photoURL, }); } throw error; @@ -154,7 +154,7 @@ function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) // Wait for all async task to complete then generate and return a custom auth token. return Promise.all([userCreationTask, databaseTask]).then(() => { // Create a Firebase custom auth token. - return admin.auth().createCustomToken(uid) + return admin.auth().createCustomToken(uid); }).then((token) => { console.log('Created Custom token for UID "', uid, '" Token:', token); return token; diff --git a/lastmodified-tracking/functions/index.js b/lastmodified-tracking/functions/index.js index 9a0aaac7c5..f53a02b42b 100644 --- a/lastmodified-tracking/functions/index.js +++ b/lastmodified-tracking/functions/index.js @@ -23,4 +23,4 @@ admin.initializeApp(functions.config().firebase); * This Function updates the `/lastmodified` with the timestamp of the last write to `/chat/$message`. */ exports.touch = functions.database.ref('/chat/{message}').onWrite( - event => admin.database().ref('/lastmodified').set(event.timestamp)); + (event) => admin.database().ref('/lastmodified').set(event.timestamp)); diff --git a/limit-children/functions/index.js b/limit-children/functions/index.js index 058f210c52..11e97b0a46 100644 --- a/limit-children/functions/index.js +++ b/limit-children/functions/index.js @@ -22,9 +22,9 @@ const MAX_LOG_COUNT = 5; // Removes siblings of the node that element that triggered the function if there are more than MAX_LOG_COUNT. // In this example we'll keep the max number of chat message history to MAX_LOG_COUNT. -exports.truncate = functions.database.ref('/chat/{messageid}').onWrite(event => { +exports.truncate = functions.database.ref('/chat/{messageid}').onWrite((event) => { const parentRef = event.data.ref.parent; - return parentRef.once('value').then(snapshot => { + return parentRef.once('value').then((snapshot) => { if (snapshot.numChildren() >= MAX_LOG_COUNT) { let childCount = 0; const updates = {}; diff --git a/line-auth/functions/index.js b/line-auth/functions/index.js index ab4b63ca5e..0208efb514 100644 --- a/line-auth/functions/index.js +++ b/line-auth/functions/index.js @@ -32,9 +32,9 @@ function generateLineApiRequest(apiEndpoint, lineAccessToken) { return { url: apiEndpoint, headers: { - 'Authorization': `Bearer ${lineAccessToken}` + 'Authorization': `Bearer ${lineAccessToken}`, }, - json: true + json: true, }; } @@ -51,24 +51,24 @@ function getFirebaseUser(lineMid, lineAccessToken) { // LINE's get user profile API endpoint const getProfileOptions = generateLineApiRequest('https://api.line.me/v1/profile', lineAccessToken); - return admin.auth().getUser(firebaseUid).catch(error => { + return admin.auth().getUser(firebaseUid).catch((error) => { // If user does not exist, fetch LINE profile and create a Firebase new user with it if (error.code === 'auth/user-not-found') { return rp(getProfileOptions); } // If error other than auth/user-not-found occurred, fail the whole login process return Promise.reject(error); - }).then(response => { + }).then((response) => { // Parse user profile from LINE's get user profile API response const displayName = response.displayName; const photoURL = response.pictureUrl; - console.log('Create new Firebase user for LINE user mid = "', lineMid,'"'); + console.log('Create new Firebase user for LINE user mid = "', lineMid, '"'); // Create a new Firebase user with LINE profile and return it return admin.auth().createUser({ uid: firebaseUid, displayName: displayName, - photoURL: photoURL + photoURL: photoURL, }); }); } @@ -91,12 +91,12 @@ function verifyLineToken(lineAccessToken) { // STEP 1: Verify with LINE server that a LINE access token is valid return rp(verifyTokenOptions) - .then(response => { + .then((response) => { // Verify the token’s channelId match with my channelId to prevent spoof attack // As LINE's Get user profiles API response doesn't include channelID, // you must not skip this step to make sure that the LINE access token is indeed // issued for your channel. - //TODO: consider !== here + // TODO: consider !== here if (response.channelId !== functions.config().line.channelid) { return Promise.reject(new Error('LINE channel ID mismatched')); } @@ -104,10 +104,10 @@ function verifyLineToken(lineAccessToken) { // STEP 2: Access token validation succeeded, so look up the corresponding Firebase user const lineMid = response.mid; return getFirebaseUser(lineMid, lineAccessToken); - }).then(userRecord => { + }).then((userRecord) => { // STEP 3: Generate Firebase Custom Auth Token return admin.auth().createCustomToken(userRecord.uid); - }).then(token => { + }).then((token) => { console.log('Created Custom token for UID "', userRecord.uid, '" Token:', token); return token; }); @@ -117,7 +117,7 @@ function verifyLineToken(lineAccessToken) { exports.verifyToken = functions.https.onRequest((req, res) => { if (req.body.token === undefined) { const ret = { - error_message: 'Access Token not found' + error_message: 'Access Token not found', }; return res.status(400).send(ret); } @@ -126,17 +126,17 @@ exports.verifyToken = functions.https.onRequest((req, res) => { // Verify LINE access token with LINE server then generate Firebase Custom Auth token return verifyLineToken(reqToken) - .then(customAuthToken => { + .then((customAuthToken) => { const ret = { - firebase_token: customAuthToken + firebase_token: customAuthToken, }; return res.status(200).send(ret); - }).catch(err => { + }).catch((err) => { // If LINE access token verification failed, return error response to client const ret = { - error_message: 'Authentication error: Cannot verify access token.' + error_message: 'Authentication error: Cannot verify access token.', }; console.error('LINE token verification failed: ', err); return res.status(403).send(ret); }); -}) +}); diff --git a/linkedin-auth/functions/index.js b/linkedin-auth/functions/index.js index da27a8dcab..6f3d46d9ec 100644 --- a/linkedin-auth/functions/index.js +++ b/linkedin-auth/functions/index.js @@ -24,7 +24,7 @@ const admin = require('firebase-admin'); const serviceAccount = require('./service-account.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), - databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com` + databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`, }); const OAUTH_SCOPES = ['r_basicprofile', 'r_emailaddress']; @@ -54,7 +54,7 @@ exports.redirect = functions.https.onRequest((req, res) => { res.cookie('state', state.toString(), { maxAge: 3600000, secure: true, - httpOnly: true + httpOnly: true, }); Linkedin.auth.authorize(res, OAUTH_SCOPES, state.toString()); }); @@ -99,10 +99,10 @@ exports.token = functions.https.onRequest((req, res) => { // Create a Firebase account and get the Custom Auth Token. return createFirebaseAccount(linkedInUserID, userName, profilePic, email, accessToken).then( - firebaseToken => { + (firebaseToken) => { // Serve an HTML page that signs the user in and updates the user profile. return res.jsonp({ - token: firebaseToken + token: firebaseToken, }); }); }); @@ -110,7 +110,7 @@ exports.token = functions.https.onRequest((req, res) => { }); } catch (error) { return res.jsonp({ - error: error.toString + error: error.toString, }); } }); @@ -134,8 +134,8 @@ function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessT displayName: displayName, photoURL: photoURL, email: email, - emailVerified: true - }).catch(error => { + emailVerified: true, + }).catch((error) => { // If user does not exists we create it. if (error.code === 'auth/user-not-found') { return admin.auth().createUser({ @@ -143,7 +143,7 @@ function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessT displayName: displayName, photoURL: photoURL, email: email, - emailVerified: true + emailVerified: true, }); } throw error; @@ -152,7 +152,7 @@ function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessT // Wait for all async task to complete then generate and return a custom auth token. return Promise.all([userCreationTask, databaseTask]).then(() => { // Create a Firebase custom auth token. - return admin.auth().createCustomToken(uid) + return admin.auth().createCustomToken(uid); }).then((token) => { console.log('Created Custom token for UID "', uid, '" Token:', token); return token; diff --git a/message-translation/functions/index.js b/message-translation/functions/index.js index c30528a3d6..8c03dab8aa 100644 --- a/message-translation/functions/index.js +++ b/message-translation/functions/index.js @@ -24,14 +24,14 @@ const request = require('request-promise'); const LANGUAGES = ['en', 'es', 'de', 'fr', 'sv', 'ga', 'it', 'jp']; // Translate an incoming message. -exports.translate = functions.database.ref('/messages/{languageID}/{messageID}').onWrite(event => { +exports.translate = functions.database.ref('/messages/{languageID}/{messageID}').onWrite((event) => { const snapshot = event.data; if (snapshot.val().translated) { return null; } const promises = []; for (let i = 0; i < LANGUAGES.length; i++) { - var language = LANGUAGES[i]; + let language = LANGUAGES[i]; if (language !== event.params.languageID) { promises.push(createTranslationPromise(event.params.languageID, language, snapshot)); } @@ -48,7 +48,7 @@ function createTranslationPromise(source, target, snapshot) { const key = snapshot.key; const message = snapshot.val().message; return request(createTranslateUrl(source, target, message), {resolveWithFullResponse: true}).then( - response => { + (response) => { if (response.statusCode === 200) { const data = JSON.parse(response.body).data; return admin.database().ref(`/messages/${target}/${key}`) diff --git a/minimal-webhook/functions/index.js b/minimal-webhook/functions/index.js index 8f11766daa..cd3f034391 100644 --- a/minimal-webhook/functions/index.js +++ b/minimal-webhook/functions/index.js @@ -25,14 +25,14 @@ const WEBHOOK_URL = 'http://requestb.in/1mqw97l1'; // Reads the content of the node that triggered the function and sends it to the registered Webhook // URL. -exports.webhook = functions.database.ref('/hooks/{hookId}').onWrite(event => { +exports.webhook = functions.database.ref('/hooks/{hookId}').onWrite((event) => { return request({ uri: WEBHOOK_URL, method: 'POST', json: true, body: event.data.val(), - resolveWithFullResponse: true - }).then(response => { + resolveWithFullResponse: true, + }).then((response) => { if (response.statusCode >= 400) { throw new Error(`HTTP Error: ${response.statusCode}`); } diff --git a/moderate-images/functions/index.js b/moderate-images/functions/index.js index 30cbe3122a..f8905069d7 100644 --- a/moderate-images/functions/index.js +++ b/moderate-images/functions/index.js @@ -38,7 +38,7 @@ exports.blurOffensiveImages = functions.storage.object().onChange(event => { } // Check the image content using the Cloud Vision API. - return vision.detectSafeSearch(file).then(data => { + return vision.detectSafeSearch(file).then((data) => { const safeSearch = data[0]; console.log('SafeSearch results on image', safeSearch); @@ -71,7 +71,7 @@ function blurImage(filePath, bucketName, metadata) { // Uploading the Blurred image. return bucket.upload(tempLocalFile, { destination: filePath, - metadata: {metadata: metadata} // Keeping custom metadata. + metadata: {metadata: metadata}, // Keeping custom metadata. }); }).then(() => { console.log('Blurred image uploaded to Storage at', filePath); diff --git a/nextjs-with-firebase-hosting/src/functions/index.js b/nextjs-with-firebase-hosting/src/functions/index.js index 7be5506283..9e3cb779cd 100644 --- a/nextjs-with-firebase-hosting/src/functions/index.js +++ b/nextjs-with-firebase-hosting/src/functions/index.js @@ -2,7 +2,7 @@ const functions = require('firebase-functions'); const next = require('next'); var dev = process.env.NODE_ENV !== 'production'; -var app = next({ dev, conf: { distDir: 'next' } }); +var app = next({dev, conf: {distDir: 'next'}}); var handle = app.getRequestHandler(); exports.next = functions.https.onRequest((req, res) => { diff --git a/presence-firestore/functions/index.js b/presence-firestore/functions/index.js index 62dbcd4c39..c1981b00c5 100644 --- a/presence-firestore/functions/index.js +++ b/presence-firestore/functions/index.js @@ -27,7 +27,7 @@ const firestore = admin.firestore(); // Create a new function which is triggered on changes to /status/{uid} // Note: This is a Realtime Database trigger, *not* Cloud Firestore. -exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate(event => { +exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate((event) => { // Get the data written to Realtime Database const eventStatus = event.data.val(); @@ -39,7 +39,7 @@ exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate(e // this event has already been overwritten by a fast change in // online / offline status, so we'll re-read the current data // and compare the timestamps. - return event.data.ref.once('value').then(statusSnapshot => { + return event.data.ref.once('value').then((statusSnapshot) => { const status = statusSnapshot.val(); console.log(status, eventStatus); // If the current timestamp for this data is newer than diff --git a/quickstarts/email-users/functions/index.js b/quickstarts/email-users/functions/index.js index 800c3c43f6..d7995e36b7 100644 --- a/quickstarts/email-users/functions/index.js +++ b/quickstarts/email-users/functions/index.js @@ -29,8 +29,8 @@ const mailTransport = nodemailer.createTransport({ service: 'gmail', auth: { user: gmailEmail, - pass: gmailPassword - } + pass: gmailPassword, + }, }); // Your company name to include in the emails @@ -42,7 +42,7 @@ const APP_NAME = 'Cloud Storage for Firebase quickstart'; * Sends a welcome email to new user. */ // [START onCreateTrigger] -exports.sendWelcomeEmail = functions.auth.user().onCreate(event => { +exports.sendWelcomeEmail = functions.auth.user().onCreate((event) => { // [END onCreateTrigger] // [START eventAttributes] const user = event.data; // The Firebase user. @@ -60,7 +60,7 @@ exports.sendWelcomeEmail = functions.auth.user().onCreate(event => { * Send an account deleted email confirmation to users who delete their accounts. */ // [START onDeleteTrigger] -exports.sendByeEmail = functions.auth.user().onDelete(event => { +exports.sendByeEmail = functions.auth.user().onDelete((event) => { // [END onDeleteTrigger] const user = event.data; @@ -75,7 +75,7 @@ exports.sendByeEmail = functions.auth.user().onDelete(event => { function sendWelcomeEmail(email, displayName) { const mailOptions = { from: `${APP_NAME} `, - to: email + to: email, }; // The user subscribed to the newsletter. @@ -90,7 +90,7 @@ function sendWelcomeEmail(email, displayName) { function sendGoodbyEmail(email, displayName) { const mailOptions = { from: `${APP_NAME} `, - to: email + to: email, }; // The user unsubscribed to the newsletter. @@ -99,4 +99,4 @@ function sendGoodbyEmail(email, displayName) { return mailTransport.sendMail(mailOptions).then(() => { return console.log('Account deletion confirmation email sent to:', email); }); -} \ No newline at end of file +} diff --git a/quickstarts/pubsub-helloworld/functions/index.js b/quickstarts/pubsub-helloworld/functions/index.js index fe33cdb5d7..a937a6a5f2 100644 --- a/quickstarts/pubsub-helloworld/functions/index.js +++ b/quickstarts/pubsub-helloworld/functions/index.js @@ -25,7 +25,7 @@ const functions = require('firebase-functions'); * topic. */ // [START trigger] -exports.helloPubSub = functions.pubsub.topic('topic-name').onPublish(event => { +exports.helloPubSub = functions.pubsub.topic('topic-name').onPublish((event) => { // [END trigger] // [START readBase64] const pubSubMessage = event.data; @@ -41,7 +41,7 @@ exports.helloPubSub = functions.pubsub.topic('topic-name').onPublish(event => { * Cloud Function to be triggered by Pub/Sub that logs a message using the data published to the * topic as JSON. */ -exports.helloPubSubJson = functions.pubsub.topic('another-topic-name').onPublish(event => { +exports.helloPubSubJson = functions.pubsub.topic('another-topic-name').onPublish((event) => { // [START readJson] const pubSubMessage = event.data; // Get the `name` attribute of the PubSub message JSON body. @@ -60,7 +60,7 @@ exports.helloPubSubJson = functions.pubsub.topic('another-topic-name').onPublish * Cloud Function to be triggered by Pub/Sub that logs a message using the data attributes * published to the topic. */ -exports.helloPubSubAttributes = functions.pubsub.topic('yet-another-topic-name').onPublish(event => { +exports.helloPubSubAttributes = functions.pubsub.topic('yet-another-topic-name').onPublish((event) => { // [START readAttributes] const pubSubMessage = event.data; // Get the `name` attribute of the message. diff --git a/quickstarts/thumbnails/functions/index.js b/quickstarts/thumbnails/functions/index.js index a06d41a9fe..9dcc8c68c0 100644 --- a/quickstarts/thumbnails/functions/index.js +++ b/quickstarts/thumbnails/functions/index.js @@ -30,7 +30,7 @@ const fs = require('fs'); * ImageMagick. */ // [START generateThumbnailTrigger] -exports.generateThumbnail = functions.storage.object().onChange(event => { +exports.generateThumbnail = functions.storage.object().onChange((event) => { // [END generateThumbnailTrigger] // [START eventAttributes] const object = event.data; // The Storage object. @@ -76,10 +76,10 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { const bucket = gcs.bucket(fileBucket); const tempFilePath = path.join(os.tmpdir(), fileName); const metadata = { - contentType: contentType + contentType: contentType, }; return bucket.file(filePath).download({ - destination: tempFilePath + destination: tempFilePath, }).then(() => { console.log('Image downloaded locally to', tempFilePath); // Generate a thumbnail using ImageMagick. @@ -92,7 +92,7 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { // Uploading the thumbnail. return bucket.upload(tempFilePath, { destination: thumbFilePath, - metadata: metadata + metadata: metadata, }); // Once the thumbnail has been uploaded delete the local file to free up disk space. }).then(() => fs.unlinkSync(tempFilePath)); diff --git a/quickstarts/time-server/functions/index.js b/quickstarts/time-server/functions/index.js index 5786ce8b63..839e833ff7 100644 --- a/quickstarts/time-server/functions/index.js +++ b/quickstarts/time-server/functions/index.js @@ -23,7 +23,7 @@ const functions = require('firebase-functions'); const moment = require('moment'); // CORS Express middleware to enable CORS Requests. const cors = require('cors')({ - origin: true + origin: true, }); // [END additionalimports] @@ -75,4 +75,4 @@ exports.date = functions.https.onRequest((req, res) => { // [END sendResponse] }); }); -// [END all] \ No newline at end of file +// [END all] diff --git a/quickstarts/uppercase-firestore/functions/index.js b/quickstarts/uppercase-firestore/functions/index.js index 1cdefd170c..85756cbad9 100644 --- a/quickstarts/uppercase-firestore/functions/index.js +++ b/quickstarts/uppercase-firestore/functions/index.js @@ -35,7 +35,7 @@ exports.addMessage = functions.https.onRequest((req, res) => { const original = req.query.text; // [START adminSdkAdd] // Push the new message into the Realtime Database using the Firebase Admin SDK. - return admin.firestore().collection('messages').add({original: original}).then(writeResult => { + return admin.firestore().collection('messages').add({original: original}).then((writeResult) => { // Send back a message that we've succesfully written the message return res.json({result: `Message with ID: ${writeResult.id} added.`}); }); @@ -47,7 +47,7 @@ exports.addMessage = functions.https.onRequest((req, res) => { // Listens for new messages added to /messages/:documentId/original and creates an // uppercase version of the message to /messages/:documentId/uppercase // [START makeUppercaseTrigger] -exports.makeUppercase = functions.firestore.document('/messages/{documentId}').onCreate(event => { +exports.makeUppercase = functions.firestore.document('/messages/{documentId}').onCreate((event) => { // [END makeUppercaseTrigger] // [START makeUppercaseBody] @@ -62,4 +62,4 @@ exports.makeUppercase = functions.firestore.document('/messages/{documentId}').o // [END makeUppercaseBody] }); // [END makeUppercase] -// [END all] \ No newline at end of file +// [END all] diff --git a/quickstarts/uppercase/functions/index.js b/quickstarts/uppercase/functions/index.js index b1cc71cee0..26c3a818b1 100644 --- a/quickstarts/uppercase/functions/index.js +++ b/quickstarts/uppercase/functions/index.js @@ -35,7 +35,7 @@ exports.addMessage = functions.https.onRequest((req, res) => { const original = req.query.text; // [START adminSdkPush] // Push the new message into the Realtime Database using the Firebase Admin SDK. - return admin.database().ref('/messages').push({original: original}).then(snapshot => { + return admin.database().ref('/messages').push({original: original}).then((snapshot) => { // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console. return res.redirect(303, snapshot.ref); }); @@ -47,7 +47,7 @@ exports.addMessage = functions.https.onRequest((req, res) => { // Listens for new messages added to /messages/:pushId/original and creates an // uppercase version of the message to /messages/:pushId/uppercase // [START makeUppercaseTrigger] -exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onWrite(event => { +exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onWrite((event) => { // [END makeUppercaseTrigger] // [START makeUppercaseBody] // Grab the current value of what was written to the Realtime Database. @@ -61,4 +61,4 @@ exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').on // [END makeUppercaseBody] }); // [END makeUppercase] -// [END all] \ No newline at end of file +// [END all] diff --git a/spotify-auth/functions/index.js b/spotify-auth/functions/index.js index e98e27fdae..9efe2c6e54 100644 --- a/spotify-auth/functions/index.js +++ b/spotify-auth/functions/index.js @@ -24,7 +24,7 @@ const admin = require('firebase-admin'); const serviceAccount = require('./service-account.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), - databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com` + databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`, }); // Spotify OAuth 2 setup @@ -33,7 +33,7 @@ const SpotifyWebApi = require('spotify-web-api-node'); const Spotify = new SpotifyWebApi({ clientId: functions.config().spotify.client_id, clientSecret: functions.config().spotify.client_secret, - redirectUri: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html` + redirectUri: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`, }); // Scopes to request. @@ -91,7 +91,7 @@ exports.token = functions.https.onRequest((req, res) => { // Create a Firebase account and get the Custom Auth Token. return createFirebaseAccount(spotifyUserID, userName, profilePic, email, accessToken).then( - firebaseToken => { + (firebaseToken) => { // Serve an HTML page that signs the user in and updates the user profile. return res.jsonp({token: firebaseToken}); }); @@ -124,8 +124,8 @@ function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessTo displayName: displayName, photoURL: photoURL, email: email, - emailVerified: true - }).catch(error => { + emailVerified: true, + }).catch((error) => { // If user does not exists we create it. if (error.code === 'auth/user-not-found') { return admin.auth().createUser({ @@ -133,7 +133,7 @@ function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessTo displayName: displayName, photoURL: photoURL, email: email, - emailVerified: true + emailVerified: true, }); } throw error; @@ -142,7 +142,7 @@ function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessTo // Wait for all async tasks to complete, then generate and return a custom auth token. return Promise.all([userCreationTask, databaseTask]).then(() => { // Create a Firebase custom auth token. - return admin.auth().createCustomToken(uid) + return admin.auth().createCustomToken(uid); }).then((token) => { console.log('Created Custom token for UID "', uid, '" Token:', token); return token; diff --git a/stripe/functions/index.js b/stripe/functions/index.js index 5cabb44877..7fe5fd521c 100644 --- a/stripe/functions/index.js +++ b/stripe/functions/index.js @@ -21,33 +21,33 @@ const logging = require('@google-cloud/logging')(); admin.initializeApp(functions.config().firebase); -const stripe = require('stripe')(functions.config().stripe.token), - currency = functions.config().stripe.currency || 'USD'; +const stripe = require('stripe')(functions.config().stripe.token); +const currency = functions.config().stripe.currency || 'USD'; // [START chargecustomer] // Charge the Stripe customer whenever an amount is written to the Realtime database -exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite(event => { +exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite((event) => { const val = event.data.val(); // This onWrite will trigger whenever anything is written to the path, so // noop if the charge was deleted, errored out, or the Stripe API returned a result (id exists) if (val === null || val.id || val.error) return null; // Look up the Stripe customer id written in createStripeCustomer - return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then(snapshot => { + return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => { return snapshot.val(); - }).then(customer => { + }).then((customer) => { // Create a charge using the pushId as the idempotency key, protecting against double charges const amount = val.amount; const idempotency_key = event.params.id; let charge = {amount, currency, customer}; if (val.source !== null) charge.source = val.source; return stripe.charges.create(charge, {idempotency_key}); - }).then(response => { + }).then((response) => { // If the result is successful, write it back to the database return event.data.adminRef.set(response); - }).catch(error => { + }).catch((error) => { // We want to capture errors and render them in a user-friendly way, while // still logging an exception with Stackdriver - return event.data.adminRef.child('error').set(userFacingMessage(error)) + return event.data.adminRef.child('error').set(userFacingMessage(error)); }).then(() => { return reportError(error, {user: event.params.userId}); }); @@ -55,37 +55,37 @@ exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/ // [END chargecustomer]] // When a user is created, register them with Stripe -exports.createStripeCustomer = functions.auth.user().onCreate(event => { +exports.createStripeCustomer = functions.auth.user().onCreate((event) => { const data = event.data; return stripe.customers.create({ - email: data.email - }).then(customer => { + email: data.email, + }).then((customer) => { return admin.database().ref(`/stripe_customers/${data.uid}/customer_id`).set(customer.id); }); }); // Add a payment source (card) for a user by writing a stripe payment source token to Realtime database -exports.addPaymentSource = functions.database.ref('/stripe_customers/{userId}/sources/{pushId}/token').onWrite(event => { +exports.addPaymentSource = functions.database.ref('/stripe_customers/{userId}/sources/{pushId}/token').onWrite((event) => { const source = event.data.val(); if (source === null) return null; - return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then(snapshot => { + return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => { return snapshot.val(); - }).then(customer => { + }).then((customer) => { return stripe.customers.createSource(customer, {source}); - }).then(response => { + }).then((response) => { return event.data.adminRef.parent.set(response); - }, error => { - return event.data.adminRef.parent.child('error').set(userFacingMessage(error)) + }, (error) => { + return event.data.adminRef.parent.child('error').set(userFacingMessage(error)); }).then(() => { return reportError(error, {user: event.params.userId}); }); }); // When a user deletes their account, clean up after them -exports.cleanupUser = functions.auth.user().onDelete(event => { - return admin.database().ref(`/stripe_customers/${event.data.uid}`).once('value').then(snapshot => { +exports.cleanupUser = functions.auth.user().onDelete((event) => { + return admin.database().ref(`/stripe_customers/${event.data.uid}`).once('value').then((snapshot) => { return snapshot.val(); - }).then(customer => { + }).then((customer) => { return stripe.customers.del(customer.customer_id); }).then(() => { return admin.database().ref(`/stripe_customers/${event.data.uid}`).remove(); @@ -107,8 +107,8 @@ function reportError(err, context = {}) { const metadata = { resource: { type: 'cloud_function', - labels: { function_name: process.env.FUNCTION_NAME } - } + labels: {function_name: process.env.FUNCTION_NAME}, + }, }; // https://cloud.google.com/error-reporting/reference/rest/v1beta1/ErrorEvent @@ -116,15 +116,17 @@ function reportError(err, context = {}) { message: err.stack, serviceContext: { service: process.env.FUNCTION_NAME, - resourceType: 'cloud_function' + resourceType: 'cloud_function', }, - context: context + context: context, }; // Write the error log entry return new Promise((resolve, reject) => { - log.write(log.entry(metadata, errorEvent), error => { - if (error) { reject(error); } + log.write(log.entry(metadata, errorEvent), (error) => { + if (error) { + reject(error); +} resolve(); }); }); diff --git a/survey-app-update/functions/index.js b/survey-app-update/functions/index.js index 7883deb536..8a7bc37452 100644 --- a/survey-app-update/functions/index.js +++ b/survey-app-update/functions/index.js @@ -34,7 +34,7 @@ const LATEST_VERSION = '2.0'; /** * After a user has updated the app. Send them a survey to compare the app with the old version. */ -exports.sendAppUpdateSurvey = functions.analytics.event('app_update').onLog(event => { +exports.sendAppUpdateSurvey = functions.analytics.event('app_update').onLog((event) => { const uid = event.data.user.userId; const appVerion = event.data.user.appInfo.appVersion; @@ -43,7 +43,7 @@ exports.sendAppUpdateSurvey = functions.analytics.event('app_update').onLog(even // Fetch the email of the user. In this sample we assume that the app is using Firebase Auth and // has set the Firebase Analytics User ID to be the same as the Firebase Auth uid using the // setUserId API. - return admin.auth().getUser(uid).then(user => { + return admin.auth().getUser(uid).then((user) => { const email = user.email; const name = user.displayName; return sendSurveyEmail(email, name); @@ -62,7 +62,7 @@ function sendSurveyEmail(email, name) { subject: 'How did you like our new app?', text: `Hey ${name}, We've seen that you have upgraded to the new version of our app! It would be awesome if you could tell us how you like it. - Fill out our survey: ${LINK_TO_SURVEY}` + Fill out our survey: ${LINK_TO_SURVEY}`, }; return mailTransport.sendMail(mailOptions).then(() => { diff --git a/template-handlebars/functions/index.js b/template-handlebars/functions/index.js index a0ed2a3dd9..4b9b4e36b8 100644 --- a/template-handlebars/functions/index.js +++ b/template-handlebars/functions/index.js @@ -31,7 +31,7 @@ app.use(firebaseUser.validateFirebaseIdToken); app.get('/', (req, res) => { console.log('Signed-in user:', req.user); return res.render('user', { - user: req.user + user: req.user, }); }); diff --git a/text-moderation/functions/index.js b/text-moderation/functions/index.js index 00bf9fa2af..1d54324e93 100644 --- a/text-moderation/functions/index.js +++ b/text-moderation/functions/index.js @@ -21,7 +21,7 @@ const Filter = require('bad-words'); const badWordsFilter = new Filter(); // Moderates messages by lowering all uppercase messages and removing swearwords. -exports.moderator = functions.database.ref('/messages/{messageId}').onWrite(event => { +exports.moderator = functions.database.ref('/messages/{messageId}').onWrite((event) => { const message = event.data.val(); if (message && !message.sanitized) { @@ -36,7 +36,7 @@ exports.moderator = functions.database.ref('/messages/{messageId}').onWrite(even return event.data.adminRef.update({ text: moderatedMessage, sanitized: true, - moderated: message.text !== moderatedMessage + moderated: message.text !== moderatedMessage, }); } return null; @@ -79,4 +79,4 @@ function isShouting(message) { // and remove exclamation points. function stopShouting(message) { return capitalizeSentence(message.toLowerCase()).replace(/!+/g, '.'); -} \ No newline at end of file +} diff --git a/url-shortener/functions/index.js b/url-shortener/functions/index.js index 2708085caf..ce50182771 100644 --- a/url-shortener/functions/index.js +++ b/url-shortener/functions/index.js @@ -21,7 +21,7 @@ admin.initializeApp(functions.config().firebase); const request = require('request-promise'); // Shorten URL -exports.shortenUrl = functions.database.ref('/links/{linkID}').onWrite(event => { +exports.shortenUrl = functions.database.ref('/links/{linkID}').onWrite((event) => { const snapshot = event.data; if (typeof snapshot.val() !== 'string') { return null; @@ -35,25 +35,25 @@ function createShortenerRequest(sourceUrl) { method: 'POST', uri: `https://www.googleapis.com/urlshortener/v1/url?key=${functions.config().firebase.apiKey}`, body: { - longUrl: sourceUrl + longUrl: sourceUrl, }, json: true, - resolveWithFullResponse: true + resolveWithFullResponse: true, }; } function createShortenerPromise(snapshot) { const key = snapshot.key; const originalUrl = snapshot.val(); - return request(createShortenerRequest(originalUrl)).then(response => { + return request(createShortenerRequest(originalUrl)).then((response) => { if (response.statusCode === 200) { return response.body.id; } throw response.body; - }).then(shortUrl => { + }).then((shortUrl) => { return admin.database().ref(`/links/${key}`).set({ original: originalUrl, - short: shortUrl + short: shortUrl, }); }); -} \ No newline at end of file +} diff --git a/username-password-auth/functions/index.js b/username-password-auth/functions/index.js index b1fe7c9cb3..31a8840153 100644 --- a/username-password-auth/functions/index.js +++ b/username-password-auth/functions/index.js @@ -19,7 +19,7 @@ const functions = require('firebase-functions'); // CORS Express middleware to enable CORS Requests. const cors = require('cors')({ - origin: true + origin: true, }); // Firebase Setup @@ -27,7 +27,7 @@ const admin = require('firebase-admin'); const serviceAccount = require('./service-account.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), - databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com` + databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`, }); // We use Request to make the basic authentication request in our example. @@ -45,19 +45,19 @@ const basicAuthRequest = require('request'); exports.auth = functions.https.onRequest((req, res) => { const handleError = (username, error) => { console.error({ - User: username + User: username, }, error); return res.sendStatus(500); }; const handleResponse = (username, status, body) => { console.log({ - User: username + User: username, }, { Response: { Status: status, - Body: body - } + Body: body, + }, }); if (body) { return res.status(200).json(body); @@ -82,18 +82,18 @@ exports.auth = functions.https.onRequest((req, res) => { } // TODO(DEVELOPER): In production you'll need to update the `authenticate` function so that it authenticates with your own credentials system. - return authenticate(username, password).then(valid => { + return authenticate(username, password).then((valid) => { if (!valid) { return handleResponse(username, 401); // Invalid username/password } // On success return the Firebase Custom Auth Token. - return admin.auth().createCustomToken(username) - }).then(firebaseToken => { + return admin.auth().createCustomToken(username); + }).then((firebaseToken) => { return handleResponse(username, 200, { - token: firebaseToken + token: firebaseToken, }); - }).catch(error => { + }).catch((error) => { return handleError(username, error); }); }); @@ -109,15 +109,14 @@ exports.auth = functions.https.onRequest((req, res) => { * @returns {Promise} success or failure. */ function authenticate(username, password) { - // For the purpose of this example use httpbin (https://httpbin.org) and send a basic authentication request. // (Only a password of `Testing123` will succeed) const authEndpoint = `https://httpbin.org/basic-auth/${username}/Testing123`; const creds = { auth: { user: username, - pass: password - } + pass: password, + }, }; return new Promise((resolve, reject) => { basicAuthRequest(authEndpoint, creds, (error, response, body) => { @@ -134,4 +133,4 @@ function authenticate(username, password) { return resolve(true); }); }); -} \ No newline at end of file +} From c157cd4dd0e2d42db189b7eb52afc00c7c7bba1e Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Wed, 7 Feb 2018 19:08:20 -0800 Subject: [PATCH 15/16] added parans and removed extra function --- ffmpeg-convert-audio/functions/index.js | 2 +- isomorphic-react-app/functions/index.js | 26 ++++++++++++------------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/ffmpeg-convert-audio/functions/index.js b/ffmpeg-convert-audio/functions/index.js index 79e17a4351..96b7fc4fbf 100644 --- a/ffmpeg-convert-audio/functions/index.js +++ b/ffmpeg-convert-audio/functions/index.js @@ -61,7 +61,7 @@ function reencodeAsync(tempFilePath, targetTempFilePath) { * When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using * node-fluent-ffmpeg. */ -exports.generateMonoAudio = functions.storage.object().onChange(event => { +exports.generateMonoAudio = functions.storage.object().onChange((event) => { const object = event.data; // The Storage object. const fileBucket = object.bucket; // The Storage bucket that contains the file. diff --git a/isomorphic-react-app/functions/index.js b/isomorphic-react-app/functions/index.js index 54c463099f..05d8185598 100644 --- a/isomorphic-react-app/functions/index.js +++ b/isomorphic-react-app/functions/index.js @@ -42,19 +42,19 @@ app.get('/favicon.ico', (req, res) => { }); app.get('/:userId?', (req, res) => { - res.set('Cache-Control', 'public, max-age=60, s-maxage=180'); - if (req.params.userId) { - // client is requesting user-details page with userId - // load the data for that employee and its direct reports - return database.getEmployeeById(req.params.userId).then(resp => { - return renderApplication(req.url, res, resp); - }); - } else { - // index page. load data for all employees - return database.getAllEmployees().then(resp => { - return renderApplication(req.url, res, resp); - }); - } + res.set('Cache-Control', 'public, max-age=60, s-maxage=180'); + if (req.params.userId) { + // client is requesting user-details page with userId + // load the data for that employee and its direct reports + return database.getEmployeeById(req.params.userId).then((resp) => { + return renderApplication(req.url, res, resp); + }); + } else { + // index page. load data for all employees + return database.getAllEmployees().then((resp) => { + return renderApplication(req.url, res, resp); + }); + } }); exports.app = functions.https.onRequest(app); From 1d7cf4912374d424e051fe26313b2ea463679134 Mon Sep 17 00:00:00 2001 From: Tina Liang Date: Thu, 8 Feb 2018 17:16:56 -0800 Subject: [PATCH 16/16] last round of lint fixes --- image-sharp/functions/index.js | 2 +- instagram-auth/functions/index.js | 2 +- isomorphic-react-app/functions/index.js | 8 ++++---- linkedin-auth/functions/index.js | 2 +- moderate-images/functions/index.js | 2 +- quickstarts/thumbnails/functions/index.js | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/image-sharp/functions/index.js b/image-sharp/functions/index.js index c3d054d0fd..c56130001e 100644 --- a/image-sharp/functions/index.js +++ b/image-sharp/functions/index.js @@ -27,7 +27,7 @@ const THUMB_MAX_HEIGHT = 200; * When an image is uploaded in the Storage bucket We generate a thumbnail automatically using * Sharp. */ -exports.generateThumbnail = functions.storage.object().onChange(event => { +exports.generateThumbnail = functions.storage.object().onChange((event) => { const object = event.data; // The Storage object. const fileBucket = object.bucket; // The Storage bucket that contains the file. diff --git a/instagram-auth/functions/index.js b/instagram-auth/functions/index.js index 8b4208a72a..bde6faaf82 100644 --- a/instagram-auth/functions/index.js +++ b/instagram-auth/functions/index.js @@ -159,4 +159,4 @@ function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) console.log('Created Custom token for UID "', uid, '" Token:', token); return token; }); -} \ No newline at end of file +} diff --git a/isomorphic-react-app/functions/index.js b/isomorphic-react-app/functions/index.js index 05d8185598..0af375e89f 100644 --- a/isomorphic-react-app/functions/index.js +++ b/isomorphic-react-app/functions/index.js @@ -32,13 +32,13 @@ database.initializeApp(appConfig); // Helper function to get the markup from React, inject the initial state, and // send the server-side markup to the client const renderApplication = (url, res, initialState) => { - const html = ReactDOMServer.renderToString(ServerApp({url: url, context: {}, initialState, appConfig})); - const templatedHtml = template({body: html, initialState: JSON.stringify(initialState)}); - res.send(templatedHtml); + const html = ReactDOMServer.renderToString(ServerApp({url: url, context: {}, initialState, appConfig})); + const templatedHtml = template({body: html, initialState: JSON.stringify(initialState)}); + res.send(templatedHtml); }; app.get('/favicon.ico', (req, res) => { - return res.send(204); + return res.send(204); }); app.get('/:userId?', (req, res) => { diff --git a/linkedin-auth/functions/index.js b/linkedin-auth/functions/index.js index 6f3d46d9ec..0bf36ac0aa 100644 --- a/linkedin-auth/functions/index.js +++ b/linkedin-auth/functions/index.js @@ -157,4 +157,4 @@ function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessT console.log('Created Custom token for UID "', uid, '" Token:', token); return token; }); -} \ No newline at end of file +} diff --git a/moderate-images/functions/index.js b/moderate-images/functions/index.js index f8905069d7..80927fa67e 100644 --- a/moderate-images/functions/index.js +++ b/moderate-images/functions/index.js @@ -28,7 +28,7 @@ const fs = require('fs'); * When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision * API and if it is we blur it using ImageMagick. */ -exports.blurOffensiveImages = functions.storage.object().onChange(event => { +exports.blurOffensiveImages = functions.storage.object().onChange((event) => { const object = event.data; const file = gcs.bucket(object.bucket).file(object.name); diff --git a/quickstarts/thumbnails/functions/index.js b/quickstarts/thumbnails/functions/index.js index 9dcc8c68c0..df15bde524 100644 --- a/quickstarts/thumbnails/functions/index.js +++ b/quickstarts/thumbnails/functions/index.js @@ -98,4 +98,4 @@ exports.generateThumbnail = functions.storage.object().onChange((event) => { }).then(() => fs.unlinkSync(tempFilePath)); // [END thumbnailGeneration] }); -// [END generateThumbnail] \ No newline at end of file +// [END generateThumbnail]