How to use firebase-admin

Comprehensive firebase-admin code examples:

How to use firebase-admin.instanceId:

316
317
318
319
320
321
322
323
324
325
326
327
  }
  return search;
}


function isProduction() {
  const projectId = firebase.instanceId().app.options.projectId;
  return projectId.includes('production');
}


function removeHtml(str) {

How to use firebase-admin.g:

240
241
242
243
244
245
246
247
248
249
case 'DD/MM/YYYY':
  // e.g. 30/11/2022 (ref: https://momentjs.com/docs/#/displaying/format/)
  value = value.toLocaleDateString();
  break;
case 'date-hour-minute':
  // e.g. Wednesday, 30 November, 2022 at 13:00
  value = `${value.toLocaleDateString('en-GB', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })} at ${value.toLocaleTimeString('en-GB', { hour: '2-digit', minute:'2-digit', hour12: false })}`;
  break;
default:
  value = toDateString(value);

How to use firebase-admin.initializeApp:

44
45
46
47
48
49
50
51
52
53
54
55


console.log(`UDMI version ${UDMI_VERSION}, functions ${FUNCTIONS_VERSION_MIN}:${FUNCTIONS_VERSION_MAX}`);
console.log(`Deployed by ${version.deployed_by} at ${version.deployed_at}`);


if (useFirestore) {
  admin.initializeApp(functions.config().firebase);
} else {
  console.log('No FIREBASE_CONFIG defined');
}
const firestore = useFirestore ? admin.firestore() : null;

How to use firebase-admin.messaging:

92
93
94
95
96
97
98
99
100
101
        "sendername": "Nuevo reporte (USUARIO)",
        "message": 'idk',
    }
}

return admin.messaging().sendToDevice(listaTokens, payload).then((response) => {
    console.log('Se enviaron todas las notificaciones');

}).catch((err) => {
    console.log(err);

How to use firebase-admin.database:

150
151
152
153
154
155
156
157
158
159
  This includes chat data in the Firestore and Realtime database.
*/
exports.deleteChat = functions.runWith({ timeoutSeconds: 540, memory: '2GB' }).database.ref('/presence/{topic}/chats/{chatID}/{uid}/active').onUpdate(async (change, context) => {
  //function fires when a users active value has changed
  if (change.after.val() == false) {//user has gone offline
    const database = admin.database();
    const chatID = context.params.chatID;
    const usersID = context.params.uid;
    const topic = context.params.topic
    let opponentActive; //set to false if there is no opponent

How to use firebase-admin.storage:

81
82
83
84
85
86
87
88
89
90
91
92
	credential: admin.credential.cert(serviceAccount),
	storageBucket: 'csi-innovations.appspot.com'
});


//firebase bucket
var bucket = admin.storage().bucket();


//function to upload file
async function uploadFile(filepath, filename) {
	await bucket.upload(filepath, {

How to use firebase-admin.auth:

70
71
72
73
74
75
76
77
78
79
batch.update(admin.firestore().doc('PERRINNMessages/'+messageId),{chatImageUrlMedium:chatImageData.imageUrlMedium||messageData.chatImageUrlMedium||null},{create:true})

//user data
let emails=messageData.emails||userPreviousMessageData.emails||{}
if(emails.auth==undefined){
  const userRecord=await admin.auth().getUser(user)
  if(userRecord)emails.auth=userRecord.toJSON().email
}
if(emails.auth&&userPreviousMessageData.emails&&(emails.auth!=userPreviousMessageData.emails.auth))await admin.auth().updateUser(user,{email:emails.auth})
messageData.createdTimestamp=messageData.createdTimestamp||userPreviousMessageData.createdTimestamp||now

How to use firebase-admin.credential:

76
77
78
79
80
81
82
83
84
85
86
87
	client_x509_cert_url: process.env.CERT_URL
};


//initialize firebase app
admin.initializeApp({
	credential: admin.credential.cert(serviceAccount),
	storageBucket: 'csi-innovations.appspot.com'
});


//firebase bucket

How to use firebase-admin.firestore:

48
49
50
51
52
53
54
55
56
57
58
if (useFirestore) {
  admin.initializeApp(functions.config().firebase);
} else {
  console.log('No FIREBASE_CONFIG defined');
}
const firestore = useFirestore ? admin.firestore() : null;


const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});