Utilize Firebase Realtime Database to generate new data entries using triggers

Hey there, to all the amazing folks at stackoverflow who have been supporting me over the years, I have a new question for you!

I've been delving into Android programming for quite some time now and I enjoy exploring different ways to optimize apps. Recently, I stumbled upon Firebase Realtime Database and its feature of triggering server-side entries with functions. I've watched numerous videos on Firebase, sifted through their pages, and even experimented with Typescript.

Unfortunately, my English skills are severely lacking and I'm struggling to find examples that can help me get a simple code snippet up and running. I managed to create a Node.js code, tested it with firebase emulators locally which worked fine, but encountered issues when deploying it to the Google server using "Firebase deploy". My main goal is to make an entry in another path after triggering an initial entry. The concept eludes me and I'm hoping someone can shed light on what could be wrong and how to rectify it.

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'
const serviceAccount = require('../serviceAccount.json')

let userId = "";


admin.initializeApp({
    credential: admin.credential.applicationDefault() ,
    databaseURL:`https://${serviceAccount.project_id}.firebasio.com`
});

// const db = admin.database();

// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript

 export const helloWorld = functions.https.onRequest((request, response) => {
     console.log("hallo world");
  response.send("Hello from Firebase!");
 });

 export const setPlayerInTeam = functions.database.ref('{userId}/team/{teamId}/allPlayer/{spielerId}/')
 .onCreate( (snapshot,context)=>{
    const original = snapshot.val();
    userId = context.params.userId;
    console.log('userId',userId);
    console.log('teamId',context.params.teamId);
    console.log('spielerId',context.params.spielerId);
    console.log('original.name',original.name);
    console.log('Updates',context.params.spielerId," "+context.params.teamId);  

    const adaNameRef = admin.database().ref();
       adaNameRef.child('test').push({ first: 'Ada', last: 'Lovelace' }).then(function() {
        console.log('Synchronization succeeded');
      })
      .catch(function(error) {
        console.log('Synchronization failed');
      });

      return adaNameRef;

 });

Experimenting with async produced the same result according to the Console feedback.

 .onCreate(async (snapshot,context)=>{
 ......
await  adaNameRef.child('test')

The Powershell Console output looks like this:

  userId TZBAxFGSgZPZBoYZz7F4MVm5MAP2
>  teamId -M797y0K4BBCEOa_nVoB
>  spielerId -M7skpftMOOF4QlEW2kv
>  original.name luigi
>  Updates -M7skpftMOOF4QlEW2kv  -M797y0K4BBCEOa_nVoB
i  functions: Finished "setPlayerInTeam" in ~1s
>  Synchronization succeeded

In the Firebase Console Log, I see the following:

Function execution started
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
userId TZBAxFGSgZPZBoYZz7F4MVm5MAP2 
teamId -M8e9ro1Dlb7VA9Pab4t
spielerId -M8e9ozdo0uU6NCXfG2z  
original.name Ayla  
Updates -M8e9ozdo0uU6NCXfG2z -M8e9ro1Dlb7VA9Pab4t   
Function execution took 1151 ms, finished with status: 'ok' 

No success, no errors?

Apologies for the rough English translation, everything was done using Google Translate. Thank you in advance!

Answer №1

Here is a custom code snippet I've put together for you to get started:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

//Setting up the App
admin.initializeApp(functions.config().firebase);

//Triggering the function when a userID is created
exports.capitalizeName = functions.database.ref('/hello/{userID}')
    .onCreate((snapshot, context) => {

      //Adding an entry in another path
      //Adjust the path as needed for your database
      admin.database().ref("/world").update({
        username: "JohnDoe123"
      });
    });

Wishing you the best of luck on your coding journey! :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing the currently operating WS server instance with NodeJS

After successfully setting up a basic REST API using NodeJS, ExpressJS, and routing-controllers, I also managed to configure a WebSocket server alongside the REST API by implementing WS. const app = express(); app.use(bodyParser.json({limit: "50mb"})); a ...

When transferring the code to the src folder, tRPC encounters issues and stops functioning

Currently, I am working on developing a basic Twitter clone using Next and TRPC. While tRPC is up and running smoothly, I am looking to streamline my code by consolidating it all within the src directory. However, upon moving everything, I encountered an i ...

Display the current date in YYYY/MM/DD format using a single method in React and TypeScript

Is there a better way to retrieve YYYY/MM/DD data using just one method? I attempted the following: date = created_at // from API const sendDate = `${String((date.getMonth() + 1)).padStart(2, '0')}${String(date.getDate()).padStart(2, '0&apos ...

Ensure Angular delays execution until my function provides a response

For my latest project, I'm working on a custom pipe that utilizes the Google Translation Service API. However, I've run into an issue where the returned value is always the original input before translation because the function finishes execution ...

Is there a possibility for the code following the await call to be executed in a random order if an async Vuex action is triggered twice?

const actions = { search: debounce( async ({ commit, dispatch, getters, rootGetters }, { page = 1 }) => { commit("setLoading", true); commit("setPage", page); console.log("Starting...") const ...

Error in TypeScript logEvent for Firebase Analytics

Currently utilizing firebase SDK version 8.0.2 and attempting to record a 'screen_view' event, encountering an error message stating: Error: Argument of type '"screen_view"' is not assignable to parameter of type '" ...

Using the <Field> component in Vee-validate ensures that your form will always be valid when submitted

Hello all, I am currently working on a Vue 3 project and utilizing vee-validate v4 for form validation. My forms are structured as follows <template> <div> <VForm v-slot="{ meta }" ref="form" > ...

Vanilla JavaScript error: Unable to access property

I am working on implementing a header with a logo and navigation that includes a menu toggle link for smaller viewports. My goal is to achieve this using Vanilla JS instead of jQuery. However, when I click on the menu toggle link, I encounter the followin ...

Executing the setDeleted loop causes changes to the entities which are then reflected in the saveChanges

My goal is to delete a hierarchy of objects: Customer->Orders->OrderItems->OrderItemOptions I attempted to set up a nested loop to perform the operations in the correct order - deleting child records before deleting parent records as required by ...

Toggle the visibility of a checkbox based on the JSON data

I have 4 check boxes that need to be dynamically displayed based on the value retrieved from my JSON. The JSON will only contain one checkbox name, and that specific checkbox should be shown to the user as checked. How can I achieve this functionality? Bel ...

Having difficulty leveraging npm modules in TypeScript

I recently switched from Babel to Typescript and am facing difficulties with importing a module from node_modules. The generated .js build does not include the code from the module I'm trying to import, specifically browser-cookies. I used yarn to in ...

Unable to establish a connection between the HTML element and the TypeScript variable

I'm facing an issue with my code where the function that worked perfectly for register and login is not functioning properly on the index page. Even though there seems to be no errors in the login and register functions, I have a form with an input s ...

Having trouble connecting Nextjs with ChromaDB?

I am encountering issues while trying to establish a connection with the Chromadb vector database in Nextjs. The objective is to store user-generated content in Chromadb. Below is the code snippet I am utilizing along with its dependencies: Dependencies V ...

Issue with Typescript typing for the onChange event

I defined my state as shown below: const [updatedStep, updateStepObj] = useState( panel === 'add' ? new Step() : { ...selectedStep } ); Additionally, I have elements like: <TextField ...

Encountering issues with vite build due to @types/react-router-dom package

I ran into an issue while developing my react app using Vite and TypeScript. Everything works fine when using Vite for development, but as soon as I switch to "tsc && vite build", I encounter numerous errors from @types/react-router-dom and @types/react-ro ...

The Firebase Node.js function encountered an error while trying to set a cookie: TypeError - the option "

UPDATE: Encountered an issue that appears to be a bug, so I have opened an issue here: https://github.com/firebase/firebase-functions/issues/653 After deploying a cloud function and attempting to handle a request while setting a cookie with the 'none ...

Should the PHP interface be exported to a Typescript interface, or should it be vice versa?

As I delve into Typescript, I find myself coding backend in PHP for my current contract. In recent projects, I have created Typescript interfaces for the AJAX responses generated by my backend code. This ensures clarity for the frontend developer, whether ...

How can we use Angular Table to automatically shift focus to the next row after we input a value in the last cell of the current row and press the Enter key

When the last cell of the first row is completed, the focus should move to the next row if there are no more cells in the current row. <!-- HTML file--> <tbody> <tr *ngFor="let row of rows;let i=index;" [c ...

Issue with Angular modal not opening as expected when triggered programmatically

I am working with the ng-bootstrap modal component import { NgbModal, ModalCloseReasons } from "@ng-bootstrap/ng-bootstrap"; When I click on a button, the modal opens as expected <button class="btn labelbtn accountbtn customnavbtn" ...

The superclass defines the type of the subclass

There is an abstract typescript class like this: abstract class Abstract { constructor (public parent?: Abstract) { } } Then, two subclasses are defined as follows: class Sub1 extends Abstract { } class Sub2 extends Abstract { } The issue aris ...