Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions Node-1st-gen/authenticated-json-api/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@
'use strict';

const functions = require('firebase-functions/v1');
const admin = require('firebase-admin');
const { initializeApp, applicationDefault } = require('firebase-admin/app');
const { getAuth } = require('firebase-admin/auth');
const { getDatabase } = require('firebase-admin/database');

// Follow instructions to set up admin credentials:
// https://firebase.google.com/docs/functions/local-emulator#set_up_admin_credentials_optional
admin.initializeApp({
credential: admin.credential.applicationDefault(),
initializeApp({
credential: applicationDefault(),
// TODO: ADD YOUR DATABASE URL
databaseURL: undefined
});
Expand All @@ -44,7 +46,7 @@ const authenticate = async (req, res, next) => {
}
const idToken = req.headers.authorization.split('Bearer ')[1];
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken);
const decodedIdToken = await getAuth().verifyIdToken(idToken);
req.user = decodedIdToken;
next();
return;
Expand Down Expand Up @@ -74,7 +76,7 @@ app.post('/api/messages', async (req, res) => {

// @ts-ignore
const uid = req.user.uid;
await admin.database().ref(`/users/${uid}/messages`).push(data);
await getDatabase().ref(`/users/${uid}/messages`).push(data);

res.status(201).json({message, category});
} catch(error) {
Expand All @@ -94,8 +96,8 @@ app.get('/api/messages', async (req, res) => {
const uid = req.user.uid;
const category = `${req.query?.category ?? ''}`;

/** @type admin.database.Query */
let query = admin.database().ref(`/users/${uid}/messages`);
/** @type {import('firebase-admin/database').Query} */
let query = getDatabase().ref(`/users/${uid}/messages`);

if (category && ['positive', 'negative', 'neutral'].indexOf(category) > -1) {
// Update the query with the valid category
Expand Down Expand Up @@ -129,7 +131,7 @@ app.get('/api/message/:messageId', async (req, res) => {
try {
// @ts-ignore
const uid = req.user.uid;
const snapshot = await admin.database().ref(`/users/${uid}/messages/${messageId}`).once('value');
const snapshot = await getDatabase().ref(`/users/${uid}/messages/${messageId}`).once('value');

if (!snapshot.exists()) {
return res.status(404).json({errorCode: 404, errorMessage: `message '${messageId}' not found`});
Expand Down
7 changes: 4 additions & 3 deletions Node-1st-gen/convert-images/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@
'use strict';

const functions = require('firebase-functions/v1');
const admin = require('firebase-admin');
const { initializeApp } = require('firebase-admin/app');
const { getStorage } = require('firebase-admin/storage');
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');

admin.initializeApp();
initializeApp();

// File extension for the created JPEG files.
const JPEG_EXTENSION = '.jpg';
Expand Down Expand Up @@ -52,7 +53,7 @@ exports.imageToJPG = functions.storage.object().onFinalize(async (object) => {
return null;
}

const bucket = admin.storage().bucket(object.bucket);
const bucket = getStorage().bucket(object.bucket);
// Create the temp directory where the storage file will be downloaded.
await fs.promises.mkdir(tempLocalDir, { recursive: true });
// Download file from bucket.
Expand Down
12 changes: 7 additions & 5 deletions Node-1st-gen/coupon-on-purchase/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
'use strict';

const functions = require('firebase-functions/v1');
const admin = require('firebase-admin');
admin.initializeApp();
const { initializeApp } = require('firebase-admin/app');
const { getMessaging } = require('firebase-admin/messaging');
const { getDatabase } = require('firebase-admin/database');
initializeApp();

// [START all]
/**
Expand Down Expand Up @@ -70,7 +72,7 @@ async function sendCouponViaFCM(uid, userLanguage) {
}

// Send notifications to all tokens.
return admin.messaging().sendEachForMulticast({
return getMessaging().sendEachForMulticast({
notification: payload.notification,
tokens
});
Expand Down Expand Up @@ -107,7 +109,7 @@ async function sendHighValueCouponViaFCM(uid, userLanguage) {
}

// Send notifications to all tokens.
return admin.messaging().sendEachForMulticast({
return getMessaging().sendEachForMulticast({
notification: payload.notification,
tokens
});
Expand All @@ -121,7 +123,7 @@ async function sendHighValueCouponViaFCM(uid, userLanguage) {
* @param {string} uid The UID of the user.
*/
async function getDeviceTokens(uid) {
const snap = await admin.database().ref(`/users/${uid}/tokens`).once('value');
const snap = await getDatabase().ref(`/users/${uid}/tokens`).once('value');
if (snap.exists()) {
return Object.keys(snap.val());
}
Expand Down
9 changes: 5 additions & 4 deletions Node-1st-gen/delete-unused-accounts-cron/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
'use strict';

const functions = require('firebase-functions/v1');
const admin = require('firebase-admin');
admin.initializeApp();
const { initializeApp } = require('firebase-admin/app');
const { getAuth } = require('firebase-admin/auth');
initializeApp();
const PromisePool = require('es6-promise-pool').default;
// Maximum concurrent account deletions.
const MAX_CONCURRENT = 3;
Expand Down Expand Up @@ -45,7 +46,7 @@ function deleteInactiveUser(inactiveUsers) {
const userToDelete = inactiveUsers.pop();

// Delete the inactive user.
return admin.auth().deleteUser(userToDelete.uid).then(() => {
return getAuth().deleteUser(userToDelete.uid).then(() => {
return functions.logger.log(
'Deleted user account',
userToDelete.uid,
Expand All @@ -68,7 +69,7 @@ function deleteInactiveUser(inactiveUsers) {
* Returns the list of all inactive users.
*/
async function getInactiveUsers(users = [], nextPageToken) {
const result = await admin.auth().listUsers(1000, nextPageToken);
const result = await getAuth().listUsers(1000, nextPageToken);
// Find users that have not signed in in the last 30 days.
const inactiveUsers = result.users.filter(
user => Date.parse(user.metadata.lastRefreshTime || user.metadata.lastSignInTime) < (Date.now() - 30 * 24 * 60 * 60 * 1000));
Expand Down
9 changes: 5 additions & 4 deletions Node-1st-gen/developer-motivator/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@
*/
'use strict';

const admin = require('firebase-admin');
const { initializeApp } = require('firebase-admin/app');
const { getMessaging } = require('firebase-admin/messaging');
const functions = require('firebase-functions/v1');
const {defineSecret} = require('firebase-functions/params');
admin.initializeApp();
initializeApp();

// TODO: Make sure you configure the 'DEV_MOTIVATOR_DEVICE_TOKEN' secret.
const devMotivatorDeviceToken = defineSecret('DEV_MOTIVATOR_DEVICE_TOKEN');
Expand All @@ -37,7 +38,7 @@ exports.appinstalled = functions.runWith({secrets: [devMotivatorDeviceToken]}).a
}
};

return admin.messaging().send({token: devMotivatorDeviceToken.value(), notification: payload.notification});
return getMessaging().send({token: devMotivatorDeviceToken.value(), notification: payload.notification});
});

/**
Expand All @@ -56,5 +57,5 @@ exports.appremoved = functions.runWith({secrets: [devMotivatorDeviceToken]}).ana
}
};

return admin.messaging().send({token: devMotivatorDeviceToken.value(), notification: payload.notification});
return getMessaging().send({token: devMotivatorDeviceToken.value(), notification: payload.notification});
});
7 changes: 4 additions & 3 deletions Node-1st-gen/exif-images/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ const crypto = require('crypto');
const path = require('path');
const os = require('os');

const admin = require('firebase-admin');
admin.initializeApp();
const { initializeApp } = require('firebase-admin/app');
const { getDatabase } = require('firebase-admin/database');
initializeApp();
const { Storage } = require('@google-cloud/storage');
const spawn = require('child-process-promise').spawn;

Expand Down Expand Up @@ -54,7 +55,7 @@ exports.metadata = functions.storage.object().onFinalize(async (object) => {
// Save metadata to realtime datastore.
metadata = imageMagickOutputToObject(result.stdout);
const safeKey = makeKeyFirebaseCompatible(filePath);
await admin.database().ref(safeKey).set(metadata);
await getDatabase().ref(safeKey).set(metadata);
functions.logger.log('Wrote to:', filePath, 'data:', metadata);
// Cleanup temp directory after metadata is extracted
// Remove the file from temp directory
Expand Down
13 changes: 8 additions & 5 deletions Node-1st-gen/fcm-notifications/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@
'use strict';

const functions = require('firebase-functions/v1');
const admin = require('firebase-admin');
admin.initializeApp();
const { initializeApp } = require('firebase-admin/app');
const { getAuth } = require('firebase-admin/auth');
const { getDatabase } = require('firebase-admin/database');
const { getMessaging } = require('firebase-admin/messaging');
initializeApp();

/**
* Triggers when a user gets a new follower and sends a notification.
Expand Down Expand Up @@ -46,11 +49,11 @@ exports.sendFollowerNotification = functions.database.ref('/followers/{followedU
);

// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database()
const getDeviceTokensPromise = getDatabase()
.ref(`/users/${followedUid}/notificationTokens`).once('value');

// Get the follower profile.
const getFollowerProfilePromise = admin.auth().getUser(followerUid);
const getFollowerProfilePromise = getAuth().getUser(followerUid);

// The snapshot to the user's tokens.
let tokensSnapshot;
Expand Down Expand Up @@ -87,7 +90,7 @@ exports.sendFollowerNotification = functions.database.ref('/followers/{followedU
// Listing all tokens as an array.
tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
const {responses} = await admin.messaging().sendEachForMulticast({
const {responses} = await getMessaging().sendEachForMulticast({
notification: payload.notification,
tokens,
});
Expand Down
4 changes: 3 additions & 1 deletion Node-1st-gen/fulltext-search-firestore/functions/elastic.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ onInit(() => {
client = new Client({
cloud: {
id: elasticId.value(),
},
auth: {
username: elasticUsername.value(),
password: elasticPassword.value(),
}
},
});
});
// [END init_elastic]
Expand Down
7 changes: 4 additions & 3 deletions Node-1st-gen/fulltext-search-firestore/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,9 @@ exports.onNoteCreated = functions.runWith({secrets: [algoliaId, algoliaAdminKey]
// [END update_index_function]

// [START get_firebase_user]
const admin = require('firebase-admin');
admin.initializeApp();
const { initializeApp } = require('firebase-admin/app');
const { getAuth } = require('firebase-admin/auth');
initializeApp();

async function getFirebaseUser(req, res, next) {
functions.logger.log('Check if request is authorized with Firebase ID token');
Expand All @@ -73,7 +74,7 @@ async function getFirebaseUser(req, res, next) {
}

try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken);
const decodedIdToken = await getAuth().verifyIdToken(idToken);
functions.logger.log('ID Token correctly decoded', decodedIdToken);
req.user = decodedIdToken;
return next();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ onInit(() => {
client = new Typesense.Client({
'nodes': [{
'host': 'xxx.a1.typesense.net', // where xxx is the ClusterID of your Typesense Cloud cluster
'port': '443',
'port': 443,
'protocol': 'https'
}],
'apiKey': typesenseAdminApiKey.value(),
Expand Down
5 changes: 4 additions & 1 deletion Node-1st-gen/fulltext-search-firestore/public/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ function searchAlgoliaAuthenticated(query) {
return firebase.auth().currentUser.getIdToken()
.then(function(token) {
// The token is then passed to our getSearchKey Cloud Function
return fetch('https://us-central1-' + PROJECT_ID + '.cloudfunctions.net/getSearchKey/', {
const searchKeyUrl = new URL(
`https://us-central1-${PROJECT_ID}.cloudfunctions.net/getSearchKey/`
);
return fetch(searchKeyUrl, {
headers: { Authorization: 'Bearer ' + token }
});
})
Expand Down
7 changes: 4 additions & 3 deletions Node-1st-gen/fulltext-search/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
const functions = require('firebase-functions/v1');
const {onInit} = require('firebase-functions/v1/init');
const {defineSecret} = require('firebase-functions/params');
const admin = require('firebase-admin');
admin.initializeApp();
const { initializeApp } = require('firebase-admin/app');
const { getDatabase } = require('firebase-admin/database');
initializeApp();

// Authenticate to Algolia Database.
// TODO: Make sure you configure the `ALGOLIA_APP_ID` and `ALGOLIA_API_KEY` secrets.
Expand Down Expand Up @@ -62,5 +63,5 @@ exports.searchentry = functions.runWith({secrets: [algoliaAppId, algoliaApiKey]}
'/search/last_query_timestamp': Date.parse(context.timestamp),
};
updates[`/search/results/${key}`] = content;
return admin.database().ref().update(updates);
return getDatabase().ref().update(updates);
});
11 changes: 6 additions & 5 deletions Node-1st-gen/google-sheet-sync/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
const functions = require('firebase-functions/v1');
const {onInit} = require('firebase-functions/v1/init');
const {defineString, defineSecret} = require('firebase-functions/params');
const admin = require('firebase-admin');
admin.initializeApp();
const { initializeApp } = require('firebase-admin/app');
const { getDatabase } = require('firebase-admin/database');
initializeApp();
const {OAuth2Client} = require('google-auth-library');
const {google} = require('googleapis');

Expand Down Expand Up @@ -70,7 +71,7 @@ exports.oauthcallback = functions.runWith({secrets: [googleApiClientId, googleAp
try {
const { tokens } = await functionsOauthClient.getToken(code);
// Now tokens contains an access_token and an optional refresh_token. Save them.
await admin.database().ref(DB_TOKEN_PATH).set(tokens);
await getDatabase().ref(DB_TOKEN_PATH).set(tokens);
res.status(200).send('App successfully configured with new Credentials. '
+ 'You can now close this page.');
} catch (error) {
Expand Down Expand Up @@ -120,7 +121,7 @@ async function getAuthorizedClient() {
functionsOauthClient.setCredentials(oauthTokens);
return functionsOauthClient;
}
const snapshot = await admin.database().ref(DB_TOKEN_PATH).once('value');
const snapshot = await getDatabase().ref(DB_TOKEN_PATH).once('value');
oauthTokens = snapshot.val();
functionsOauthClient.setCredentials(oauthTokens);
return functionsOauthClient;
Expand All @@ -132,7 +133,7 @@ exports.testsheetwrite = functions.https.onRequest(async (req, res) => {
const random2 = Math.floor(Math.random() * 100);
const random3 = Math.floor(Math.random() * 100);
const ID = new Date().getUTCMilliseconds();
await admin.database().ref(`${watchedpathsDataPath.value()}/${ID}`).set({
await getDatabase().ref(`${watchedpathsDataPath.value()}/${ID}`).set({
firstColumn: random1,
secondColumn: random2,
thirdColumn: random3,
Expand Down
7 changes: 5 additions & 2 deletions Node-1st-gen/image-maker/functions/clock.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
* limitations under the License.
*/

const _ = require('lodash');

const getDefaultOpts = () => ({
strokes: {
Expand All @@ -39,7 +38,11 @@ const getY = (angle) => {
};

const clock = (ctx, colorOpts) => {
const colors = _.merge({}, getDefaultOpts(), colorOpts);
const defaultOpts = getDefaultOpts();
const colors = {
strokes: Object.assign({}, defaultOpts.strokes, colorOpts && colorOpts.strokes),
fills: Object.assign({}, defaultOpts.fills, colorOpts && colorOpts.fills),
};
let x, y, i;
const now = new Date();

Expand Down
Loading
Loading