skip to Main Content

Is there or will there be modular Firebase Admin Database functions i.e. update(), get(), set(), ref() etc.? Maybe there is a workaround?

Else I would have to code equal functions twice, like "craftBuilding()" on server (admin) and one for client.

Tried to:

import { getDatabase, ref, set, update, child, onChildAdded } from 'firebase-admin/database';

Error:

The requested module ‘firebase-admin/database’ does not provide an export named ‘ref’

I expected to be able to use firebase rtdb functions like on client-side, to not code identical functions twice.

2

Answers


  1. Since Firebase Admin is namespaced, ref is available after you initialize.

    import { ref, update, set } from '@path/yourAdminFunctions';
    
    var admin = require("firebase-admin");
    
    // Initialize Admin SDK
    
    var db = admin.database();
    export db;
    
    const dbReference = ref("your reference here");
    const IDSnapFromQuery = query(dbReference, ["ID", "==", 10]);
    

    You could modularize it yourself by creating functions for the operations you require in a separate file:

    import { db } from '@path/yourMainFile';
    
    export function ref(databaseReference) {
      return db.ref(databaseReference);
    };
    
    // for query pass in the db.ref instance you're using
    export function query(dbReference, queryParams) {
      // identify what query params are e.g. ID == 10 in this example
      // note that you will have to code the queryParams filter, I have left it out
    
      dbReference
        .orderByChild('ID')
        .equalTo(10).on('child_added',
      (snapshot) => {
        return snapshot;
      });
    }
    
    // do the same for update, set etc
    

    You can read more on the admin SDK documentation.

    Login or Signup to reply.
  2. The Admin SDK is not totally modular yet but has some function such a getDatabase() starting V10.

    import { getDatabase } from 'firebase-admin/database';
    // TODO: Initialize Admin SDK
    
    const db = getDatabase();
    
    // usage
    const ref = db.ref('../../..')
    

    I would recommend using latest version of the SDK along with the existing syntax but use newer modular imports.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search