Coder Social home page Coder Social logo

romainvialard / firebaseapp Goto Github PK

View Code? Open in Web Editor NEW
113.0 13.0 34.0 106 KB

Google Apps Script binding for Firebase Realtime Database

License: Apache License 2.0

JavaScript 100.00%
firebase firebase-realtime-database apps-script google-apps-script

firebaseapp's Introduction

FirebaseApp

The Google Apps Script binding for the Firebase Realtime Database

Install

Best it to copy the content of this file in your Google Apps Script project: https://github.com/RomainVialard/FirebaseApp/blob/master/src/Code.gs

You can also add it as a library, though this is not recommended.
https://developers.google.com/apps-script/guides/libraries
Library's script ID: 1VlYLzhwx0YEoxIe62eItLAZeobVt_l-GQUKt2MXXuBHFVsqBkl9C_yBB

Documentation / Reference

Class FirebaseApp

getDatabaseByUrl(url, optSecret)

Retrieves a database by url

  • Parameters:
    • urlstring — - the database url

    • [optSecret]string — - a Firebase app secret

  • Returns: Database — the Database found at the given URL

encodeAsFirebaseKey(string)

Returns a valid Firebase key from a given string Firebase Keys can't contain any of the following characters: . $ # [ ] / https://firebase.google.com/docs/database/usage/limits#data_tree https://groups.google.com/forum/#!msg/firebase-talk/vtX8lfxxShk/skzA5vQFdosJ

  • Parameters: stringstring — - the string to encode

  • Returns: string — the encoded string

decodeFirebaseKey(string)

Returns a decoded string from a Firebase key encoded by encodeAsFirebaseKey()

  • Parameters: stringstring — - the encoded Firebase key

  • Returns: string — the decoded string

signInWithIdp(firebaseConfig, idToken)

Signs in or signs up a user using credentials from an Identity Provider (IdP) - eg: google.com. https://cloud.google.com/identity-platform/docs/reference/rest/v1/accounts/signInWithIdp

  • Parameters:
  • Returns: object — the auth token granting access to firebase

Class Database

createAuthToken(userEmail, optAuthData, serviceAccountEmail, privateKey)

Generates an authorization token to firebase

  • Parameters:
    • userEmailstring — the email account of the user you want to authenticate
    • optAuthDataobject — key-pairs of data to be associated to this user.
    • serviceAccountEmailstring — the email of the service account used to generate this token
    • privateKeystring — the private key of this service account
  • Returns: object — the auth token granting access to firebase

createAuthTokenFromServiceAccount(userEmail, optCustomClaims)

Generates an authorization token to Firebase

  • Parameters:
    • userEmailstring — - the email account of the user you want to authenticate

    • optCustomClaimsobject — - key-pairs of data to be associated to this user (aka custom claims).

  • Returns: object — the auth token granting access to firebase

createLegacyAuthToken(userEmail, optCustomClaims)

Generates an authorization token to firebase

  • Parameters:
    • userEmailstring — the email account of the user you want to authenticate
    • optCustomClaimsobject — - key-pairs of data to be associated to this user (aka custom claims).
  • Returns: object — the auth token granting access to firebase

getData(path, optQueryParameters)

Returns the data at this path

  • Parameters:
    • pathstring — - the path where the data is stored

    • [optQueryParameters]OptQueryParameters — - a set of query parameters

  • Returns: object — the data found at the given path

getAllData(requests)

Returns data in all specified paths

  • Parameters: {Array.<string — FirebaseApp_.request>} requests - array of requests

  • Returns: object — responses to each requests

pushData(path, data, optQueryParameters)

Generates a new child location using a unique key

  • Parameters:
    • pathstring — - the path where to create a new child

    • dataobject — - the data to be written at the generated location

    • [optQueryParameters]OptQueryParameters — - a set of query parameters

  • Returns: string — the child name of the new data that was added

setData(path, data, optQueryParameters)

Write data at the specified path

  • Parameters:
    • pathstring — - the path where to write data

    • dataobject — - the data to be written at the specified path

    • [optQueryParameters]OptQueryParameters — - a set of query parameters

  • Returns: object — the data written

updateData(path, data, optQueryParameters)

Update specific children at the specified path without overwriting existing data

  • Parameters:
    • pathstring — - the path where to update data

    • dataobject — - the children to overwrite

    • [optQueryParameters]OptQueryParameters — a - set of query parameters

  • Returns: object — the data written

removeData(path, optQueryParameters)

Delete data at the specified path

  • Parameters:
    • pathstring — - the path where to delete data

    • [optQueryParameters]OptQueryParameters — - a set of query parameters

  • Returns: null

getUrlFromPath(path)

Gets the absolute URL from the specified path

  • Parameters: pathstring — - the path / location to convert to URL
  • Returns: string — an encoded URL that is ready to be put into a browser

#Tutorials https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase/tutorials

firebaseapp's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebaseapp's Issues

PushData without inserting unique subpath

Looking for a feature to be added. If the pushdata method could optionally push directly into the path.

Currently, if I use the pushdata method it will add a subpath with a unique id under the selected path. It would be great if that object information could be added directly under the specified path instead of creating a subPath with the unique id.

I could loop through to create a record every time but this will be very slow.

This could be useful if I need to add multiple spreadsheets to a single database but do not want to overwrite the information.

Using "error" as key in Firebase

Currently, if you have a key named "error" in Firebase, when fetching it, the lib return an error 200 (Error: 200 - [object Object]).

GAS V8 runtime bug

Switched to V8 Runtime and getting a bug where when, requesting to an endpoint which would normally return 'null' the whole script crashes with the 'Error connecting to Google Server'.

Well I loaded the library locally and this fix seems to do the job
baseClass_.getData = function (path, optQueryParameters) {
// Send request
// noinspection JSAnnotator
var [res] = FirebaseApp_._buildAllRequests([
{
method: 'get',
path: path,
optQueryParameters: optQueryParameters,
},
], this);

// Throw error
if (res instanceof Error) {
throw res;
}

if(res){
return res;
}
};

TLDR: dont return anything if the value to be returned is null.

optQueryParameters argument does not work in updateData

When I try to add query parameters to an updateData call, I get the following error:

Error: Querying related parameters not supported on this request type (line 322, file "Code", project "FirebaseApp")

Is Firebase not able to add query parameters to update calls and there is just an error in the documentation? Or is it possible, and there is a bug in the code?

By the way, I love this library. It's power and simplicity have allowed me to build a world of web apps for my employer. Thank you so much for all your hard work.

Library not found in Google App Script

Hi! I have tried using your library, but it is not found in Google App Script. Library ID has changed? I tried using the MYeP8ZEEt1ylVDxS7uyg9plDOcoke7-2l project key.

Thank you!

Append data to db without overwriting

First, just want to say thanks for all of the hard work on this. It works great.

My only concern is when writing data, I would like to have the option to disable overwriting. A good example is if you have a huge amount of data that will not fit in a Google sheet. The initial push to the realtime db works great but if I delete the information in that sheet and create new data in the sheet. I would like to append it to the db without overwriting. Is this possible?

If there is a work around for this already, I apologize.

Issue with optQueryParameters when using a string with only digits

I am using your FirebaseApp library as follow:

var r = base.getData("", { orderBy:"code", equalTo: code });
Assuming there are entries with the codes below, instead of valid results, I am getting these ...

var code = "12345"; // no results
var code = "03456"; // Error: Constraint index field must be a JSON primitive

The issue comes from line 249:
if (isNaN(optQueryParameters[key]) && typeof optQueryParameters[key] !== 'boolean') {
Because in both cases the function isNaN() returns false, considering both codes as numbers (that's how isNaN works as I understand), so it won't add the "" around the string value

But in this case the code values are strings with only digits, that can also have leading zeros

Is there a way to fix / workaround this situation?

Thanks in advance
Fausto

p.s.
I did a dirty hack to make it work, but not sure if it's the right approach

I just redefined isNaN as follow:

  FirebaseApp.isNaN = function(n) {
    return Number(parseFloat(n)) !== n;
  };

and it's working that way

Client authentication token generated by Service Account OAuth + FirebaseApp not valid.

I am having trouble and have narrowed down the issue to the auth token generated by .createAuthToken().

FirebaseApp.getDatabaseByUrl(fb_URL, service.getAccessToken())
                    .createAuthToken(Session.getEffectiveUser().getEmail())

When I use the Database Secret it will generate an authentication token that is usable client-side to make calls to Firebase, but for some reason an access token generated by a service account with OAuth2 doesn't make a valid authentication token.

I have also posted an issue here on StackOverflow with my code based on the tutorials mentioned in the readme.

As a side note, I love your work! It has helped me learn a lot about GAS over the years. Thank You!

getAllData data structure

Thanks for the great script! I used the library from the Google App Script and it works great!
But one thing I noticed is when calling getAllData, the returned data is not in proper json format. Instead of having colons, it has equal signs.

Here is an example return:
[{-LINN2XT9wdCMEQGhZ9C={firstName=myname, yourSalary=200000, position=ioio, salary=100000}, -LINBdoUX4-s793E-cDW={firstName=abcdsad, position=hahahhahha, salary=1223434}, -LINDhN0TNmOcP6Y6_Qq={firstName=yourname, yourSalary=2000000, position=senior leader}}]

Any clue what went wrong?

getData - optQueryParameters can't take "$key" for orderBy - "Error: 400 - Provided key index type is invalid, must be string"

I was having the same issue as #23 and saw the solution to use limitToFirst & startAt for pagination as per the docs. To use startAt however, you need to use orderBy. Since my data on Firebase is in the format

{
    "hash0": "very-long-string",
    "hash1": "very-long-string",
    "hash2": "very-long-string",
    ...
}

I wanted to use orderBy="$key", however I get the following error:

image

Actual code used:

  let base = FirebaseApp.getDatabaseByUrl(url, env.token);
  return base.getData("", {orderBy: `$key`, startAt: 0, limitToFirst: 5});

Omitting the second parameter on getData() entirely returns all the data, but since I have a lot of data it fails for the same reason as other users got in #23

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.