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/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/.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/authenticated-json-api/functions/index.js b/authenticated-json-api/functions/index.js index 7e9f4e5bd7..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; - next(); - }).catch(error => { + return next(); + }).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(); - res.status(201).json({message: val.message, category: val.category}); - }).catch(error => { + 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,14 +80,14 @@ app.get('/messages', (req, res) => { return res.status(404).json({errorCode: 404, errorMessage: `category '${category}' not found`}); } - 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,15 +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 => { - 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()); - } else { - res.status(404).json({errorCode: 404, errorMessage: `message '${messageId}' not found`}); + 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`}); } - }).catch(error => { + return res.set('Cache-Control', 'private, max-age=300'); + }).catch((error) => { console.log('Error getting message details', messageId, error.message); res.sendStatus(500); }); @@ -115,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/.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/authorized-https-endpoint/functions/index.js b/authorized-https-endpoint/functions/index.js index e2d0cbaebf..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; - next(); - }).catch(error => { + return next(); + }).catch((error) => { console.error('Error while verifying Firebase ID token:', error); res.status(403).send('Unauthorized'); }); 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/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/.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/child-count/functions/index.js b/child-count/functions/index.js index 62d96cc4de..718e36eea1 100644 --- a/child-count/functions/index.js +++ b/child-count/functions/index.js @@ -20,33 +20,38 @@ 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'); - // Return the promise from countRef.transaction() so our function + 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; - } + return countRef.transaction((current) => { + return (current || 0) + increment; }).then(() => { - console.log('Counter updated.'); + return console.log('Counter updated.'); }); }); // 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'); - - // 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())); + .then((messagesData) => counterRef.set(messagesData.numChildren())); } + return null; }); 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/convert-images/functions/index.js b/convert-images/functions/index.js index 0e16f9e875..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)); @@ -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); @@ -64,8 +64,7 @@ exports.imageToJPG = functions.storage.object().onChange(event => { // 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(() => { @@ -77,5 +76,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/.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/coupon-on-purchase/functions/index.js b/coupon-on-purchase/functions/index.js index b716a7c9b3..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,14 +64,15 @@ 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".', + }, }; } // Send notifications to all tokens. return admin.messaging().sendToDevice(tokens, payload); } + return null; }); } @@ -83,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. @@ -98,14 +99,15 @@ 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".', + }, }; } // Send notifications to all tokens. return admin.messaging().sendToDevice(tokens, payload); } + return null; }); } @@ -115,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/.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/email-notifier/functions/index.js b/crashlytics-integration/email-notifier/functions/index.js index 68981c9da0..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(() => { - console.log('Successfully sent new issue email'); - }).catch(error => { + return console.log('Successfully sent new issue email'); + }).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(() => { - console.log('Successfully sent regressed issue email'); - }).catch(error => { + return console.log('Successfully sent regressed issue email'); + }).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(() => { - console.log('Successfully sent velocity alert email'); - }).catch(error => { + return console.log('Successfully sent velocity alert email'); + }).catch((error) => { console.error(error.toString()); }); }); 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/jira-issue/functions/index.js b/crashlytics-integration/jira-issue/functions/index.js index 2d5371f15a..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,9 +44,9 @@ 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\-]+)/); + 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 { @@ -61,8 +61,8 @@ 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 {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; @@ -113,11 +113,11 @@ 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`); }); }); -exports.createRegressedIssue = functions.crashlytics.issue().onRegressed(event => { +exports.createRegressedIssue = functions.crashlytics.issue().onRegressed((event) => { const data = event.data; const issueId = data.issueId; @@ -134,11 +134,11 @@ 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`); }); }); -exports.createVelocityAlert = functions.crashlytics.issue().onVelocityAlert(event => { +exports.createVelocityAlert = functions.crashlytics.issue().onVelocityAlert((event) => { const data = event.data; const issueId = data.issueId; @@ -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/.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/crashlytics-integration/slack-notifier/functions/index.js b/crashlytics-integration/slack-notifier/functions/index.js index a09460ee81..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; @@ -45,11 +45,11 @@ 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`); }); }); -exports.postOnRegressedIssue = functions.crashlytics.issue().onRegressed(event => { +exports.postOnRegressedIssue = functions.crashlytics.issue().onRegressed((event) => { const data = event.data; const issueId = data.issueId; @@ -64,11 +64,11 @@ 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`); }); }); -exports.postOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert(event => { +exports.postOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert((event) => { const data = event.data; const issueId = data.issueId; @@ -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/.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-old-child-nodes/functions/index.js b/delete-old-child-nodes/functions/index.js index 9ad19b8eba..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); }); - }); + }); 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/delete-unused-accounts-cron/functions/index.js b/delete-unused-accounts-cron/functions/index.js index d8c156d531..bdf2208bbe 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'; @@ -36,63 +36,63 @@ exports.accountcleanup = functions.https.onRequest((req, res) => { // 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) { - 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 => { - 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); }); } @@ -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/.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/developer-motivator/functions/index.js b/developer-motivator/functions/index.js index 2c2d121bf5..9a8cd510c7 100644 --- a/developer-motivator/functions/index.js +++ b/developer-motivator/functions/index.js @@ -26,15 +26,14 @@ 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); +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); }); /** @@ -44,14 +43,14 @@ 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 - } - }; +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, + }, + }; - admin.messaging().sendToDevice(deviceToken, payload); + admin.messaging().sendToDevice(deviceToken, payload); }); 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/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/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/exif-images/functions/index.js b/exif-images/functions/index.js index 86506574f0..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; @@ -41,31 +41,31 @@ 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); - }); - }); + 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(() => { + 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!'); }); }); 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/fcm-notifications/functions/index.js b/fcm-notifications/functions/index.js index 205e8be54e..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,29 +56,28 @@ 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. const tokens = Object.keys(tokensSnapshot.val()); // Send notifications to all tokens. - 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()); - } + 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()); } - }); - return Promise.all(tokensToRemove); + } }); + return Promise.all(tokensToRemove); }); }); 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/ffmpeg-convert-audio/functions/index.js b/ffmpeg-convert-audio/functions/index.js index 49e86275bb..96b7fc4fbf 100644 --- a/ffmpeg-convert-audio/functions/index.js +++ b/ffmpeg-convert-audio/functions/index.js @@ -26,21 +26,42 @@ 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. + */ +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); + }); +} /** * 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. @@ -52,7 +73,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. @@ -60,57 +81,57 @@ 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. 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.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); }); }); 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-firestore/functions/index.js b/fulltext-search-firestore/functions/index.js index 1457b93952..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(); @@ -51,37 +51,31 @@ 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; + ); + return res.sendStatus(403); } let idToken; - if ( - req.headers.authorization && - req.headers.authorization.startsWith('Bearer ') - ) { - console.log('Found 'Authorization' header'); + if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) { + console.log('Found \'Authorization\' header'); 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; - next(); - }) - .catch(error => { + return next(); + }).catch((error) => { console.error('Error while verifying Firebase ID token:', error); - res.status(403).send('Unauthorized'); + return res.status(403).send('Unauthorized'); }); } // [END get_firebase_user] @@ -93,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 @@ -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 @@ -109,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/.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/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/.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/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/.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/github-to-slack/functions/index.js b/github-to-slack/functions/index.js index 9b241541fb..7c60d5c922 100644 --- a/github-to-slack/functions/index.js +++ b/github-to-slack/functions/index.js @@ -30,23 +30,21 @@ exports.githubWebhook = functions.https.onRequest((req, res) => { // 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'); + .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(() => { - res.end(); - }).catch(error => { - console.error(error); - res.status(500).send('Something went wrong while posting the message to Slack.'); - }); - } else { + if (!secureCompare(signature, expectedSignature)) { 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!'); + 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.'); + }); }); /** @@ -58,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, }); } 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/google-sheet-sync/functions/index.js b/google-sheet-sync/functions/index.js index 89bed27d3e..9c11b5bf3a 100644 --- a/google-sheet-sync/functions/index.js +++ b/google-sheet-sync/functions/index.js @@ -19,15 +19,15 @@ 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); 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; @@ -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 @@ -69,18 +69,19 @@ 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; + return res.status(400).send(err); } - 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.'); + }); }); }); // 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, @@ -88,26 +89,27 @@ 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]], + }, }); -}); + } +); // 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 reject(err); } return resolve(response); }); - }).catch(() => reject()); + }); }); } @@ -116,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 @@ -132,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/.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-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/.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/image-sharp/functions/index.js b/image-sharp/functions/index.js index 4986ef7ea8..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. @@ -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,27 +47,27 @@ 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. 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}`; @@ -86,7 +86,8 @@ exports.generateThumbnail = functions.storage.object().onChange(event => { 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/.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/instagram-auth/functions/index.js b/instagram-auth/functions/index.js index 612cd10c27..bde6faaf82 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); } @@ -59,11 +59,15 @@ 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); - 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, - state: state + state: state, }); console.log('Redirecting to:', redirectUri); res.redirect(redirectUri); @@ -80,7 +84,7 @@ 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) { @@ -91,25 +95,29 @@ 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 => { - console.log('Auth code exchange result received:', 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. - 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. - 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}); - }); + // 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}); + return res.jsonp({ + error: error.toString, + }); } }); @@ -126,19 +134,18 @@ function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) // 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, - 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; @@ -147,9 +154,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/.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/isomorphic-react-app/functions/index.js b/isomorphic-react-app/functions/index.js index 885ddef30c..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', 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/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/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/.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/limit-children/functions/index.js b/limit-children/functions/index.js index 444265dc99..11e97b0a46 100644 --- a/limit-children/functions/index.js +++ b/limit-children/functions/index.js @@ -22,13 +22,13 @@ 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 = {}; - 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/.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/line-auth/functions/index.js b/line-auth/functions/index.js index 0ad331d3ed..0208efb514 100644 --- a/line-auth/functions/index.js +++ b/line-auth/functions/index.js @@ -32,15 +32,15 @@ function generateLineApiRequest(apiEndpoint, lineAccessToken) { return { url: apiEndpoint, headers: { - 'Authorization': `Bearer ${lineAccessToken}` + 'Authorization': `Bearer ${lineAccessToken}`, }, - json: true + json: true, }; } /** * 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. + * fetch LINE profile and create a new Firebase user with it. * * @returns {Promise} The Firebase user record in a promise. */ @@ -51,30 +51,30 @@ 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).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({ - uid: firebaseUid, - displayName: displayName, - photoURL: photoURL - }); - }); + 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; + + 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 + * Verify LINE access token and return a custom auth token allowing signing-in * the corresponding Firebase account. * * Here are the steps involved: @@ -91,26 +91,25 @@ 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 - if (response.channelId != functions.config().line.channelid) { + // TODO: consider !== here + if (response.channelId !== functions.config().line.channelid) { return Promise.reject(new Error('LINE channel ID mismatched')); } // 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; - }); + return admin.auth().createCustomToken(userRecord.uid); + }).then((token) => { + console.log('Created Custom token for UID "', userRecord.uid, '" Token:', token); + return token; }); } @@ -118,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,18 +125,18 @@ 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 => { + return verifyLineToken(reqToken) + .then((customAuthToken) => { const ret = { - firebase_token: customAuthToken + firebase_token: customAuthToken, }; - return res.status(200).send(ret); - }).catch(err => { + 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.' + 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/.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/linkedin-auth/functions/index.js b/linkedin-auth/functions/index.js index 339d95b47f..0bf36ac0aa 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']; @@ -51,7 +51,11 @@ 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); - 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()); }); }); @@ -66,7 +70,7 @@ 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,16 +98,20 @@ 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 => { - // Serve an HTML page that signs the user in and updates the user profile. - res.jsonp({token: firebaseToken}); + 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, }); + }); }); }); }); } catch (error) { - return res.jsonp({error: error.toString}); + return res.jsonp({ + error: error.toString, + }); } }); @@ -119,16 +127,15 @@ function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessT 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, { 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({ @@ -136,7 +143,7 @@ function createFirebaseAccount(linkedinID, displayName, photoURL, email, accessT displayName: displayName, photoURL: photoURL, email: email, - emailVerified: true + emailVerified: true, }); } throw error; @@ -145,9 +152,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/.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/message-translation/functions/index.js b/message-translation/functions/index.js index 9be750b742..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; + 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,11 +48,11 @@ 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}`) - .set({message: data.translations[0].translatedText, translated: true}); + .set({message: data.translations[0].translatedText, translated: true}); } throw response.body; }); 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/minimal-webhook/functions/index.js b/minimal-webhook/functions/index.js index 844506833f..cd3f034391 100644 --- a/minimal-webhook/functions/index.js +++ b/minimal-webhook/functions/index.js @@ -25,17 +25,17 @@ 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}`); } - console.log('SUCCESS! Posted', event.data.ref); + return console.log('SUCCESS! Posted', event.data.ref); }); }); 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/moderate-images/functions/index.js b/moderate-images/functions/index.js index 21ad975dab..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); @@ -38,13 +38,14 @@ 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); if (safeSearch.adult || safeSearch.violence) { return blurImage(object.name, object.bucket, object.metadata); } + return null; }); }); @@ -70,11 +71,11 @@ 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); fs.unlinkSync(tempLocalFile); - console.log('Deleted local file', filePath); + return console.log('Deleted local file', filePath); }); } 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/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/paypal/functions/index.js b/paypal/functions/index.js index 53f0734579..c039f6aa66 100644 --- a/paypal/functions/index.js +++ b/paypal/functions/index.js @@ -25,7 +25,7 @@ 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" }); /** @@ -34,56 +34,56 @@ paypal.configure({ * 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' - }, - // 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 - }; - }); - // 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(); - } - } - }); + // 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' + }, + // 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 + }; + }); + // 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(); + } + } + }); }); // 3.Complete the payment. Use the payer and payment IDs provided in the query string following the redirect. @@ -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/.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/presence-firestore/functions/index.js b/presence-firestore/functions/index.js index e4be40116e..c1981b00c5 100644 --- a/presence-firestore/functions/index.js +++ b/presence-firestore/functions/index.js @@ -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; - - // 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/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/email-users/functions/index.js b/quickstarts/email-users/functions/index.js index caa14c289d..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,8 +42,8 @@ const APP_NAME = 'Cloud Storage for Firebase quickstart'; * Sends a welcome email to new user. */ // [START onCreateTrigger] -exports.sendWelcomeEmail = functions.auth.user().onCreate(event => { -// [END onCreateTrigger] +exports.sendWelcomeEmail = functions.auth.user().onCreate((event) => { + // [END onCreateTrigger] // [START eventAttributes] const user = event.data; // The Firebase user. @@ -60,8 +60,8 @@ 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 => { -// [END onDeleteTrigger] +exports.sendByeEmail = functions.auth.user().onDelete((event) => { + // [END onDeleteTrigger] const user = event.data; const email = user.email; @@ -75,14 +75,14 @@ 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. 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); }); } @@ -90,13 +90,13 @@ function sendWelcomeEmail(email, displayName) { function sendGoodbyEmail(email, displayName) { const mailOptions = { from: `${APP_NAME} `, - to: email + to: email, }; // The user unsubscribed to the newsletter. 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/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/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/.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/thumbnails/functions/index.js b/quickstarts/thumbnails/functions/index.js index 7d269fc64f..df15bde524 100644 --- a/quickstarts/thumbnails/functions/index.js +++ b/quickstarts/thumbnails/functions/index.js @@ -30,8 +30,8 @@ const fs = require('fs'); * ImageMagick. */ // [START generateThumbnailTrigger] -exports.generateThumbnail = functions.storage.object().onChange(event => { -// [END generateThumbnailTrigger] +exports.generateThumbnail = functions.storage.object().onChange((event) => { + // [END generateThumbnailTrigger] // [START eventAttributes] const object = event.data; // The Storage object. @@ -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] @@ -75,9 +75,11 @@ 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 + destination: tempFilePath, }).then(() => { console.log('Image downloaded locally to', tempFilePath); // Generate a thumbnail using ImageMagick. @@ -88,8 +90,11 @@ 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 }); - // Once the thumbnail has been uploaded delete the local file to free up disk space. + 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] }); 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/time-server/functions/index.js b/quickstarts/time-server/functions/index.js index 88a0c9aeb3..839e833ff7 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; 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-firestore/functions/index.js b/quickstarts/uppercase-firestore/functions/index.js index 95a075fee4..85756cbad9 100644 --- a/quickstarts/uppercase-firestore/functions/index.js +++ b/quickstarts/uppercase-firestore/functions/index.js @@ -20,7 +20,7 @@ // 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] @@ -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] }); @@ -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 => { +exports.makeUppercase = functions.firestore.document('/messages/{documentId}').onCreate((event) => { // [END makeUppercaseTrigger] - // [START makeUppercaseBody] + // [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/.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/quickstarts/uppercase/functions/index.js b/quickstarts/uppercase/functions/index.js index 94ad65d291..26c3a818b1 100644 --- a/quickstarts/uppercase/functions/index.js +++ b/quickstarts/uppercase/functions/index.js @@ -20,7 +20,7 @@ // 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] @@ -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] }); @@ -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 => { +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] - }); + // [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/.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/spotify-auth/functions/index.js b/spotify-auth/functions/index.js index 25a6c45ed2..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. @@ -76,7 +76,7 @@ exports.token = functions.https.onRequest((req, res) => { } console.log('Received Access Token:', data.body['access_token']); Spotify.setAccessToken(data.body['access_token']); - + Spotify.getMe((error, userResults) => { if (error) { throw error; @@ -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; }); /** @@ -116,15 +117,15 @@ function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessTo // 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, { 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({ @@ -132,7 +133,7 @@ function createFirebaseAccount(spotifyID, displayName, photoURL, email, accessTo displayName: displayName, photoURL: photoURL, email: email, - emailVerified: true + emailVerified: true, }); } throw error; @@ -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/.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/stripe/functions/index.js b/stripe/functions/index.js index 6af9e2c1a5..7fe5fd521c 100644 --- a/stripe/functions/index.js +++ b/stripe/functions/index.js @@ -15,78 +15,77 @@ */ '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); -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) + // 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 => { - // Create a charge using the pushId as the idempotency key, protecting against double charges + }).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 => { - // 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}); - }); - } - ); + }).then((response) => { + // If the result is successful, write it back to the database + return event.data.adminRef.set(response); + }).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(() => { + return reportError(error, {user: event.params.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 => { - 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}); - }); + }).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}); }); }); // 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(); @@ -108,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 @@ -117,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/.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/survey-app-update/functions/index.js b/survey-app-update/functions/index.js index a9d8c12513..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,12 +43,13 @@ 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); }); } + return null; }); /** @@ -61,10 +62,10 @@ 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(() => { - 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/.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/template-handlebars/functions/firebaseUser.js b/template-handlebars/functions/firebaseUser.js index 494f1a64f0..18094028fd 100644 --- a/template-handlebars/functions/firebaseUser.js +++ b/template-handlebars/functions/firebaseUser.js @@ -26,14 +26,13 @@ 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(); }); }; @@ -46,7 +45,7 @@ function getIdTokenFromRequest(req, res) { // 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'); @@ -64,11 +63,11 @@ function getIdTokenFromRequest(req, res) { */ 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); }); } -exports.validateFirebaseIdToken = validateFirebaseIdToken; +exports.validateFirebaseIdToken = validateFirebaseIdToken; \ No newline at end of file diff --git a/template-handlebars/functions/index.js b/template-handlebars/functions/index.js index ef2bab6384..4b9b4e36b8 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(); @@ -29,8 +30,8 @@ app.use(firebaseUser.validateFirebaseIdToken); app.get('/', (req, res) => { console.log('Signed-in user:', req.user); - res.render('user', { - user: req.user + return res.render('user', { + user: req.user, }); }); 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/text-moderation/functions/index.js b/text-moderation/functions/index.js index 3446ae2ae7..1d54324e93 100644 --- a/text-moderation/functions/index.js +++ b/text-moderation/functions/index.js @@ -21,26 +21,26 @@ 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(); +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); + if (message && !message.sanitized) { + // 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 - }); - } + // 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/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/url-shortener/functions/index.js b/url-shortener/functions/index.js index dfe0ffc433..ce50182771 100644 --- a/url-shortener/functions/index.js +++ b/url-shortener/functions/index.js @@ -21,10 +21,10 @@ 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; + return null; } return createShortenerPromise(snapshot); }); @@ -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, }); }); } 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 + } +} diff --git a/username-password-auth/functions/index.js b/username-password-auth/functions/index.js index 89c4fd3106..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,24 +82,25 @@ 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 => { + }).catch((error) => { return handleError(username, error); }); }); } catch (error) { return handleError(username, error); } + return null; }); /** @@ -108,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) => {