Skip to content

LeadDreamer/firebase-wrapper

Repository files navigation

view on npm

@leaddreamer/firebase-wrapper

A set of helper-wrapper functions around firebase firestore, storage and auth. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another.

Modules

FirebaseWrapper

A set of helper-wrapper functions around firebase firestore, storage and auth. all-in-one wrapper for a solid subset of CLIENT-SIDE Firebase functions, with a consistent interface. There is a parallel set for ADMIN-SIDE functions as well. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another. NOTE: Most helpers return PROMISE.REJECT if no documents are returned. it is assumed projects using this library might want to have an explicitly error trap for such events.

FirebaseAuthWrapper/authAdmin

A set of helpers around Firebase admin SDK auth. Specific to use in Cloud Functions

FirebaseAuthWrapper/authClient

A set of helper-wrapper functions around firebase firestore, storage and auth. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another.

FirebaseCloudFunctionsWrapper

A set of helper-wrapper functions around firebase firestore, storage and auth. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another.

FirebaseFirestoreWrapper

A set of helper-wrapper functions around firebase firestore, storage and auth. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another.

FirebaseStorageWrapper

A set of helper-wrapper functions around firebase firestore, storage and auth. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another.

FirebaseStorageAdminEmulator

A set of helper-wrapper functions around firebase storage Intent is to treat Firestore as a hierarchical record-oriented database and Storage as a parallel structure originally conceived to port from one database to another.

Constants

PAGINATE_INIT : number
PAGINATE_PENDING : number
PAGINATE_UPDATED : number
PAGINATE_END : number
PAGINATE_DEFAULT : number
PAGINATE_CHOICES : Array.number

Typedefs

PagingStatus : PAGINATE_INIT | PAGINATE_PENDING | PAGINATE_UPDATED | PAGINATE_DEFAULT

FirebaseWrapper

A set of helper-wrapper functions around firebase firestore, storage and auth. all-in-one wrapper for a solid subset of CLIENT-SIDE Firebase functions, with a consistent interface. There is a parallel set for ADMIN-SIDE functions as well. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another. NOTE: Most helpers return PROMISE.REJECT if no documents are returned. it is assumed projects using this library might want to have an explicitly error trap for such events.

module.exports(firebase, config, thislogger) ⇒ ⏏

all-in-one wrapper for a solid subset of CLIENT-SIDE Firebase functions, with a consistent interface. There is a parallel set for ADMIN-SIDE functions as well. Call/initialize with Firebase Configuration settings in an object as described below

Kind: Exported function
Returns: none

Param Type Description
firebase Firebase Local (client or server) version of firebase app
config FirebaseConfigObject Firebase Admin object
thislogger callback Local (client or server) version of a (console) logger

Example

//this specifically loads ALL the subsections, specifically for
//the Browser.  See later (tbd) notes for NodeJS

import FirebaseWrapper from "@leaddreamer/firebase-wrapper";
FirebaseWrapper(config); //see below
export * from "@leaddreamer/firebase-wrapper";

module.exports~FirebaseConfigObject : Object

only authDomain, databaseURL and storageBucket are present when called from a cloud environment

Kind: inner typedef of module.exports
Properties

Name Type Description
apiKey string required api Key from Firebase Console,
appId string required app ID from Firebase Console
projectId string required Firebase projectID from Firebase console
authDomain string (optional) auth domain from Firebase Console
databaseURL string (optional) Firestore database URL from Firebase console
storageBucket: string (optional) URL of Firestore Storage Bucket
messagingSenderId: string (optional) ID for Messaing service from Firebase Console
measurementId: string (optional) Analytics/Measurement ID from Firebase Console
mapsAPIKey string (optional) App ID for Google Maps API, from Google

FirebaseAuthWrapper/authAdmin

A set of helpers around Firebase admin SDK auth. Specific to use in Cloud Functions

module.exports(firebase) ⏏

Initializes the administrative Auth service of the provided firebase app. Also instantiates various constants and helper functions

Kind: Exported function

Param Type
firebase firebase

module.exports.getUser(userID) ⇒ Promise.userData

asynchronously fetches user data from Firestore Authentication

Kind: static method of module.exports

Param Type
userID string

module.exports.DeleteUser(userID) ⇒ Promise.void

deletes a single user from the authentication system, identified by user ID

Kind: static method of module.exports

Param Type
userID string

module.exports.setCustomClaims(uid, customClaim) ⇒ Promise.object

sets custom claims on user object - overwrites other needed settings

Kind: static method of module.exports

Param Type Description
uid string user ID
customClaim Object claims object, less than 1000 Bytes. null clears

module.exports.addCustomClaims(uid, customClaim) ⇒ Promise.object

adds/merges to new claims to user customClaims

Kind: static method of module.exports

Param Type Description
uid string user ID
customClaim Object claims object to be merged with existing claims

module.exports.clearCustomClaims(uid) ⇒ Promise.void

removes all current customClaims on user (sets to null)

Kind: static method of module.exports

Param Type Description
uid string user ID

module.exports.PageUsers(pageSize, pageToken) ⇒ Promise.Array.object

pages through the full list of users. Woefully inefficient.

Kind: static method of module.exports

Param Type Description
pageSize number default 1000
pageToken object default null

FirebaseAuthWrapper/authClient

A set of helper-wrapper functions around firebase firestore, storage and auth. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another.

Example

import * as firebase from "firebase/app";
import "firebase/auth";
import FirebaseAuth from "@leaddreamer/firebase-wrapper/FirebaseAuthWrapper";
//the next is optional - if you want the React component
import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";
import {config} from "wherever-you-put-it";

((myconfig) {
try {
  firebase.app();
} catch (err) {
  firebase.initializeApp(myconfig);
}
FirebaseAuth(firebase, StyledFirebaseAuth);
})(config)

module.exports(firebase, thisLogger) ⏏

Initializes the Auth service of the provided firebase app. Also instantiates various constants and helper functions

Kind: Exported function

Param Type Description
firebase firebase provided firebase app (allows use between client & server)
thisLogger callback passed logging function (allows use between client & server)

module.exports.FirebaseAuth : object

FirebaseAuth instance for various Login/Logout calls

Kind: static property of module.exports

module.exports.fetchToken(user) ⇒ Promise.Token

fetches our specific custom claim values from firebase auth

Kind: static method of module.exports
Fulfil: Returns a user token object
Reject: returns err

Param Type
user FirebaseAuthUser

module.exports.fetchJWT(user) ⇒ Promise.<JWT>

Fetch a JWT token for authenticated signed requests

Kind: static method of module.exports
Fulfil: Returnsa JWT token
Reject: returns an err

Param Type
user FirebaseAuthUser

module.exports.refreshAuthUser() ⇒ Promise.void

triggers an update of the Firebase Auth user object. A listener can be set to monitor these changes

Kind: static method of module.exports

module.exports.doCreateUserWithEmailAndPassword(email, password) ⇒ Promise.<UserCredential>

Creates AND SIGNS IN an authenticated user with the provided email and password Creates a new user account associated with the specified email address and password. On successful creation of the user account, this user will also be signed in to your application. User account creation can fail if the account already exists or the password is invalid. Note: The email address acts as a unique identifier for the user and enables an email-based password reset. This function will create a new user account and set the initial user password.

Kind: static method of module.exports

Param Type
email string
password string

module.exports.doSignInWithEmailAndPassword(email, password) ⇒ Promise.<UserCredential>

SIGNS IN an existing authenticated user with the provided email and password Creates a new user account associated with the specified email address and password. On successful creation of the user account, this user will also be signed in to your application. User account creation can fail if the account already exists or the password is invalid. Note: The email address acts as a unique identifier for the user and enables an email-based password reset. This function will create a new user account and set the initial user password.

Kind: static method of module.exports

Param Type
email string
password string

module.exports.doSignInWithGoogle(googleProvider) ⇒ Promise.<UserCredential>

Kind: static method of module.exports

Param Type
googleProvider GoogleProvider

module.exports.doSignInWithFacebook(facebookProvider) ⇒ Promise.<UserCredential>

Kind: static method of module.exports

Param Type
facebookProvider FacebookProvider

module.exports.doSignInWithTwitter(twitterProvider) ⇒ Promise.<UserCredential>

Kind: static method of module.exports

Param Type
twitterProvider TwitterProvider

module.exports.doSignOut() ⇒ Promise.void

Kind: static method of module.exports

module.exports.doPasswordReset() ⇒ Promise.void

Kind: static method of module.exports

module.exports.doSendEmailVerification() ⇒ Promise.void

Kind: static method of module.exports

module.exports.doPasswordUpdate(password) ⇒ Promise.void

Kind: static method of module.exports

Param Type
password string

module.exports.createAnonymousUser() ⇒ Promise.<UserCredential>

Kind: static method of module.exports

module.exports.attachAuthUserListener(next) ⇒ function

Kind: static method of module.exports
Returns: function - unsubscribe function

Param Type
next AuthChangeProcess

module.exports.setPersistence() ⇒ Promise.void

Kind: static method of module.exports

module.exports~ID : Array.string

codes for 3rd party Auth providers

Kind: inner property of module.exports

module.exports~AdditionalUserInfo : object

Kind: inner typedef of module.exports
Properties

Name Type
isNewUser boolean
profile object
providerId string
username string

module.exports~AuthCredential : class

Kind: inner typedef of module.exports
Properties

Name Type
providerId string
signInMethod string
toJSON method
fromJSON method

module.exports~GetIdToken ⇒ Promise.<string>

Returns a JSON Web Token (JWT) used to identify the user to a Firebase service. Returns the current token if it has not expired. Otherwise, this will refresh the token and return a new one.

Kind: inner typedef of module.exports

Param Type
forceRefresh boolean

module.exports~Delete ⇒ Promise.<void>

Kind: inner typedef of module.exports

module.exports~User : object

See https://firebase.google.com/docs/reference/js/v8/firebase.User

Kind: inner typedef of module.exports
Properties

Name Type Description
displayName string | null
email string | null
emailVerified boolean
IsAnonymous boolean
metadata UserMetadata
multiFactor MultiFactorUser
phoneNumber string | null
photoURL string | null
providerData UserInfo
providerId string
refreshToken string
tenantId string | null The current user's tenant ID. This is a read-only property, which indicates the tenant ID used to sign in the current user. This is null if the user is signed in from the parent project.
uid string The user's unique ID.
delete Delete
getIdToken GetIdToken

module.exports~UserCredential : object

Kind: inner typedef of module.exports
Properties

Name Type
additionalUserInfo AdditionalUserInfo
credential AuthCredential
operationType "signin" | "link" | "reauthenticate"
user "User"

module.exports~AuthChangeProcess ⇒ Promise.void

Kind: inner typedef of module.exports

Param Type
user User

FirebaseCloudFunctionsWrapper

A set of helper-wrapper functions around firebase firestore, storage and auth. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another.

module.exports(firebase, config, thisLogger) ⇒ Promise.<(object|void)>

Initializes the Auth service of the provided firebase app. Also instantiates various constants and helper functions

Kind: Exported function

Param Type Description
firebase firebase provided firebase app (allows use between client & server)
config object configuration object to detect client/server use
config.appId string missing parameter indicates server
thisLogger callback passed logging function (allows use between client & server)

Example

import * as firebase from "firebase/app";
import "firebase/functions";
import FirebaseFunctions from "@leaddreamer/firebase-wrapper/FirebaseCloudFunctionsWrapper";
import {config} from "whereever-you-put-it";

((myconfig) {
try {
  firebase.app();
} catch (err) {
  firebase.initializeApp(myconfig);
}
FirebaseFunctions(firebase);
})(config)

module.exports.CloudFunctions() ⇒ Promise

Creates the FUNCTION refered to by the passed name. Said function can then be called for the desired results. SYNCHRONOUS

Kind: static method of module.exports
Fulfil: result as returns from call
Reject: err as returned from call
Example

result = await CloudFunctions("MyGloriousFunction")(argumentToFunction);

module.exports.treeFromParams(Params) ⇒ Map

Cloud Function specific - processes a Params list from a firestore function to create a reference/Id "tree"

Kind: static method of module.exports

Param Type
Params object

FirebaseFirestoreWrapper

A set of helper-wrapper functions around firebase firestore, storage and auth. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another.

module.exports(firebase, config, thisLogger) ⇒ Promise.<(object|void)>

Initializes the Firestore service of the provided firebase app. Also instantiates various constants and helper functions

Kind: Exported function

Param Type Description
firebase firebase provided firebase app (allows use between client & server)
config object configuration object to detect client/server use
config.appId string missing parameter indicates server
thisLogger callback passed logging function (allows use between client & server)

Example

import * as firebase from "firebase/app";
import "firebase/firestore";
import FirebaseFirestore from "@leaddreamer/firebase-wrapper/FirebaseFirestoreWrapper";
import {config} from "whereever-you-put-it";

((myconfig) {
try {
  firebase.app();
} catch (err) {
  firebase.initializeApp(myconfig);
}
FirebaseFirestore(firebase);
})(config)

module.exports.timestamp

class for a Firestore timestamp processor

Kind: static property of module.exports

module.exports.MAX_CONCURRENCY

maximum concurrent writes

Kind: static constant of module.exports

module.exports.RecordFromSnapshot(documentSnapshot) ⇒ Record

returns an internal record structure from a firestore Document snapshot

Kind: static method of module.exports

Param Type
documentSnapshot DocumentSnapshot

module.exports.RecordsFromSnapshot(querySnapshot) ⇒ Array.Record

returns an array of internal record structures from a firestore Query snapshot

Kind: static method of module.exports

Param Type
querySnapshot QuerySnapshot

module.exports.createUniqueReference(tablePath, refPath) ⇒ DocumentReference

Creates a DocumentReference document to the collection referenced in parameter tablePath (relative to optional refPath). This is can be useful for Transactions and Batches, which can only get(), set() or update() existing documents. Tricksie!

Kind: static method of module.exports
Returns: DocumentReference - Firestore Document Reference

Param Type Description
tablePath string string representing a valid path to a collection to create the new document in, relative to a document reference passed in
refPath string an optional valid document reference to start the table path

module.exports.writeRecord(tablePath, data, parentRefPath, batch, mergeOption) ⇒ Promise.Record

Writes a Firestore record to collection indicated by tablePath relative to option DocumentReference refPath

Kind: static method of module.exports
Fulfil: document record
Reject: error message

Param Type Description
tablePath string string representing a valid path to a collection to create or update the document in, relative to a document reference passed in
data Record Data/Record object to write to database
parentRefPath string an optional valid document reference to start the table path
batch WriteBatch | Transaction optional chain token to include this operation as part of an Atomic Transaction
mergeOption boolean whether to merge into existing data; default TRUE

module.exports.writeRecordByRefPath(data, refPath, Transaction, mergeOption) ⇒ Promise.<Record>

Writes given data object (or map) to the given documentReference

Kind: static method of module.exports
Returns: Promise.<Record> - data record as written

Param Type Description
data Record Object/Map to be written back to the Firestore
refPath string DocumentReference to write document to
Transaction WriteBatch | Transaction Optional Transaction to enclose this action in
mergeOption boolean whether to merge into existin data; default TRUE

module.exports.writeBack(data, Transaction, mergeOption) ⇒ Promise.Record

Writes a local-schema document back to the Firestore. Assume object/map came from the firestore

Kind: static method of module.exports
Returns: Promise.Record - record as written.

Param Type Description
data Record Object/Map to be written back to the Firestore
data.refPath string required to be present
Transaction WriteBatch | Transaction Optional Transaction to enclose this action in
mergeOption boolean whether to merge into existin data; default TRUE

module.exports.updateRecord(record, parent, tablePath, batch, mergeOption) ⇒ Promise.Record

Kind: static method of module.exports
Fulfil: document record
Reject: error message

Param Type Description
record Record Data/Record object to write to database
parent Record | null an optional valid parent document with reference to start the table path
parent.refPath string | null
tablePath string | null string representing a valid path to a collection to create or update the document in, relative to a document reference - can only be null if data is from database.
batch WriteBatch | Transaction | null optional chain token to include this operation as part of an Atomic Transaction
mergeOption boolean | null whether to merge into existing data; default TRUE

module.exports.collectRecords(tablePath, refPath) ⇒ Promise.<Array.<Record>>

query for a SET of records

Kind: static method of module.exports

Param Type Description
tablePath string string representing path ro requested collection
refPath string string representing a path to the relative PARENT of the requested collection

module.exports.collectRecordsByFilter(tablePath, refPath, filterArray, sortArray, limit) ⇒ Promise.<Array.<Record>>

returns an array of documents from Firestore

Kind: static method of module.exports

Param Type Description
tablePath string a properly formatted string representing the requested collection - always an ODD number of elements
refPath string (optional) allows "table" parameter to reference a sub-collection of an existing document reference (I use a LOT of structured collections)
filterArray Array.filterObject an array of filterObjects The array is assumed to be sorted in the correct order - i.e. filterArray[0] is added first; filterArray[length-1] last returns data as an array of objects (not dissimilar to Redux State objects) with both the documentID and documentReference added as fields.
sortArray Arrayt.sortObject a 2xn array of sort (i.e. "orderBy") conditions
limit number limit result to this number (if at all)

module.exports.collectRecordsInGroup(tableName) ⇒ Promise.<Array.<Record>>

query for a SET of records from a COLLECTIONGROUP - all collections of a similar name, regardless of parents. It is up to the User to ensure these are at a similar level/structure - Firestore just matches the name

Kind: static method of module.exports

Param Type Description
tableName string string describing the NAME of the collection group desired

module.exports.collectRecordsInGroupByFilter(tableName, filterArray) ⇒ Promise.<Array.<Record>>

queries for Records from a CollectionGroup, filtered by the passed array of filterObjects

Kind: static method of module.exports

Param Type Description
tableName string string describing the Name of the collectiongroup
filterArray Array.filterObject array of objects describing filter operations

module.exports.fetchRecord(tablePath, Id, refPath, batch) ⇒ Promise.<(Record|WriteBatch|Transaction)>

retrieve a record from the Firestore. If a Batch object is passed, returns a chained Btahc object

Kind: static method of module.exports

Param Type Description
tablePath string path to the enclosing collection
Id string Id of the specific document requested
refPath string optional document reference to base tablePath from
batch WriteBatch | Transaction optional batch reference

module.exports.fetchRecordByRefPath(docRefPath, batch) ⇒ Promise.<Record>

fetches a single record from the database, using just a refPath to identify the document

Kind: static method of module.exports

Param Type Description
docRefPath string string identifying the full path to the requested document
batch WriteBatch | Transaction object for collecting batched operations

module.exports.fetchRecordByFilter(table, [filterArray], refPath, batch) ⇒ Promise.<(Record|WriteBatch|Transaction)>

fetches a SINGLE record from the database, using just a filter to identify the document. DANGEROUSLY assumes the filter identifies a SINGLE document, even if the query always returns an array

Kind: static method of module.exports

Param Type Description
table string a properly formatted string representing the requested collection - always an ODD number of elements
[filterArray] filterObject array of objects describing filter operations
refPath string optional document reference to base tablePath from
batch WriteBatch | Transaction optional batch reference

module.exports.fetchRecordInGroupByFilter(table, [filterArray], batch) ⇒ Promise.<(Record|WriteBatch|Transaction)>

fetches a SINGLE record from the database, using just a filter to identify the document. DANGEROUSLY assumes the filter identifies a SINGLE document, even if the query always returns an array

Kind: static method of module.exports

Param Type Description
table string a properly formatted string representing the requested collection - always an ODD number of elements
[filterArray] filterObject array of objects describing filter operations
batch WriteBatch | Transaction optional batch reference

module.exports.deleteRecord(record, table, parentRefPath, batch) ⇒ void

deletes a record from the database. Checkis if record is FROM the data (has refPath) or if if only Id (so supporting parts are needed)

Kind: static method of module.exports

Param Type Description
record Record
table Record | null
parentRefPath string | null optional document reference to base tablePath from
batch WriteBatch | Transaction | null

module.exports.deleteRecordInParts(table, record, parentRefPath, batch) ⇒ Promise.<(Record|WriteBatch|Transaction)>

deletes a single record from the database

Kind: static method of module.exports

Param Type Description
table string string naming the parent collection of the document
record Record
parentRefPath string optional document reference to base tablePath from
batch WriteBatch | Transaction optional batch reference

module.exports.deleteRecordByRefPath(docRefPath, batch) ⇒ Promise.<(Record|WriteBatch|Transaction)>

deletes a single record from the database

Kind: static method of module.exports

Param Type Description
docRefPath string string identifying the full path to the requested document
batch WriteBatch | Transaction optional batch reference

module.exports.updateRecordFields(recordUpdate) ⇒ Promise.<Record>

update record by fields - Allows use of FieldPath options such as .delete(). Only specifically referenced fields will be affected. Assumes the originating docRef is passed as refPath: field

Kind: static method of module.exports

Param Type Description
recordUpdate Record object of field:value entries to update.
recordUpdate.refPath string full path to document/record

module.exports.updateRecordByRefPath(docRefPath, data, batch) ⇒ Promise.<(Record|WriteBatch|Transaction)>

Kind: static method of module.exports

Param Type Description
docRefPath string full path to document to update
data Record Record of values to update
data.Id string document Id of record
batch WriteBatch | Transaction batching object

module.exports.writeArrayValue(fieldName, fieldValue, docRefPath, batch) ⇒ Promise.<(Record|WriteBatch|Transaction)>

adds a new value to a firestore record array entry

Kind: static method of module.exports

Param Type Description
fieldName string the string name of the array to be updated
fieldValue any the value to add to the array
docRefPath string the reference path for the document to be updated
batch WriteBatch | Transaction optional - used to chain transactions

module.exports.localBatchReturn(incomingBatch, internalBatch) ⇒ WriteBatch | Transaction

Kind: static method of module.exports
Returns: WriteBatch | Transaction - WriteBatch, Transaction or Void

Param Type Description
incomingBatch WriteBatch | Transaction a batching object passed into the subroutine Internal Transaction will be added to the incoming batch
internalBatch WriteBatch | Transaction a batching object as built in the routine, built on the incomingBatch if it exists

Example

export const suboperation = (data, batch = null) => {
 let myBatch = batch || openWriteBatch(); //note short circuit
 //stuff that happens in the routine
 writeRecord(table, data, parent, myBatch);
 writeRecord(otherTable, otherData, otherParent, myBatch);
 return localBatchReturn(batch, myBatch);
}

module.exports.runTransaction(updateFunction) ⇒ Promise.object

creates and runs a series of record operations (executed in the param function) as an atomic operation. A transation object is passed to the callback parameter

Kind: static method of module.exports
Returns: Promise.object - a promise with the result of updateFunction
Category: Batch

Param Type Description
updateFunction callback callback function that expects a Transaction token as it's sole argument. either all the included/chained record operations will succeed, or none

module.exports.openWriteBatch() ⇒ WriteBatch

Creates a WriteBatch object to collect actions for Batch writing to backend

Kind: static method of module.exports
Returns: WriteBatch - object that operations are added to for a bulk operation
Category: Batch

module.exports.closeWriteBatch(batch) ⇒ Promise.<void>

Dispatches an asynchronous Closure to submit Batch

Kind: static method of module.exports
Category: Batch

Param Type Description
batch WriteBatch WriteBatch to close

module.exports.openBulkWriter() ⇒ BulkWriter

Creates a bulkWriter object to collect actions for Bulk writing to backend offers parallel operations, writes only, does NOT check for contentions, admin/Node-side only.

Kind: static method of module.exports
Returns: BulkWriter - object that operations are added to for a bulk operation
Category: Batch

module.exports.closeBulkWriter(bulkWriter) ⇒ Promise.<void>

Dispatches an asynchronous Closure to complete BulkWriter

Kind: static method of module.exports
Category: Batch

Param Type Description
bulkWriter BulkWriter bulkWriter to close

module.exports.documentId : Object

a fieldPath value to represent the document Id - WARNING Google Firestore has a bug, and this actually represents the FULL PATH to the document

Kind: static constant of module.exports
Category: FieldPath

module.exports.deleteFieldValue : Object

a sentinel value used to delete a field during an update operation

Kind: static constant of module.exports
Category: FieldValue

module.exports.serverTimestampFieldValue : Object

a sentinel value to set a field to a server-generated timestamp during set(0 or update())

Kind: static constant of module.exports
Category: FieldValue

module.exports.incrementFieldValue(n) ⇒ sentinelValue

return a sentinel to incrment/decrement a field

Kind: static method of module.exports
Returns: sentinelValue - a sentinel value
Category: FieldValue

Param Type Description
n number If either the operand or the current field value uses floating point precision, all arithmetic follows IEEE 754 semantics. If both values are integers, values outside of JavaScript's safe number range (Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER) are also subject to precision loss. Furthermore, once processed by the Firestore backend, all integer operations are capped between -2^63 and 2^63-1. If the current field value is not of type number, or if the field does not yet exist, the transformation sets the field to the given value.

module.exports.decrementFieldValue(n) ⇒


return a sentinel to decrment/decrement a field NOT REALLY A FIREBASE FUNCTION Fire base has only increment; we implement this for legibility

Kind: static method of module.exports
Returns: a sentinel value
Category: FieldValue

Param Description
n If either the operand or the current field value uses floating point precision, all arithmetic follows IEEE 754 semantics. If both values are integers, values outside of JavaScript's safe number range (Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER) are also subject to precision loss. Furthermore, once processed by the Firestore backend, all integer operations are capped between -2^63 and 2^63-1. If the current field value is not of type number, or if the field does not yet exist, the transformation sets the field to the given value.

module.exports.arrayRemoveFieldValue(arrayElements) ⇒ sentinelValue

returns a sentinel to remove elements from array field

Kind: static method of module.exports
Returns: sentinelValue - a sentinel value
Category: FieldValue

Param Type Description
arrayElements any REST expanded list of elements to remove

module.exports.arrayUnionFieldValue(arrayElements) ⇒ sentinelValue

return a sentinel to add/join elements to array field

Kind: static method of module.exports
Returns: sentinelValue - a sentinel value
Category: FieldValue

Param Type Description
arrayElements any REST expanded list of elements to add

module.exports.ListenRecords(tablePath, refPath, dataCallback, errCallback) ⇒ Unsubscribe

sets up a listener for changes to a single record

Kind: static method of module.exports
Returns: Unsubscribe - function to be called to release subscription
Category: Listeners

Param Type Description
tablePath string string describing relative path to document
refPath string string describing path to parent document
dataCallback CollectionListener function to be called with changes to record
errCallback callback function to be called when an error occurs in listener

module.exports.ListenQuery(tablePath, refPath, dataCallback, errCallback, filterArray, sortArray) ⇒ Unsubscribe

Sets up a listener to a query

Kind: static method of module.exports
Returns: Unsubscribe - function to be called to release subscription
Category: Listeners

Param Type Description
tablePath string Name (or pathname) of table to query too - may be sub-collection of optional reference
refPath string An optional Firestore DocumentReference. If present, the "table" parameter above is relative to this reference
dataCallback CollectionListener callback function with query results
errCallback callback callback function with error results
filterArray Array.filterObject a 3xn array of filter(i.e. "where") conditions
sortArray Array.sortObject an (optional) 2xn array of sort (i.e. "orderBy") conditions

module.exports.ListenCollectionGroupRecords(tablePath, refPath, dataCallback, errCallback) ⇒ Unsubscribe

sets up a listener for changes to a collectionGroup

Kind: static method of module.exports
Returns: Unsubscribe - function to be called to release subscription
Category: Listeners

Param Type Description
tablePath string string describing relative path to document
refPath string string describing path to parent document
dataCallback CollectionListener function to be called with changes to record
errCallback callback function to be called when an error occurs in listener

module.exports.ListenCollectionGroupQuery(table, dataCallback, errCallback, filterArray, sortArray) ⇒ Unsubscribe

sets up a listener for changes to a collectionGroup by query

Kind: static method of module.exports
Returns: Unsubscribe - function to be called to release subscription
Category: Listeners

Param Type Description
table string string describing the name of a collectionGroup
dataCallback CollectionListener function to be called with changes to record
errCallback callback function to be called when an error occurs in listener
filterArray Array.filterObject a 3xn array of filter(i.e. "where") conditions
sortArray Array.sortObject an (optional) 2xn array of sort (i.e. "orderBy") conditions

module.exports.ListenRecord(tablePath, Id, refPath, dataCallback, errCallback) ⇒ Unsubscribe

Listen to changes to a single record

Kind: static method of module.exports
Returns: Unsubscribe - function to be called to release subscription
Category: Listeners

Param Type Description
tablePath string string describing relative path to requested record
Id string string of Id of requested document
refPath string string od full path to parent document
dataCallback RecordListener callback to handle changes to requested document
errCallback callback callback to handle error reporting and operations

module.exports.PaginateFetch

constructs an object to paginate through large Firestore Tables

Kind: static class of module.exports
Category: Paginator

new exports.PaginateFetch(table, filterArray, sortArray, refPath, limit)
Param Type Default Description
table string a properly formatted string representing the requested collection - always an ODD number of elements
filterArray array an (optional) 3xn array of filter(i.e. "where") conditions The array is assumed to be sorted in the correct order - i.e. filterArray[0] is added first; filterArray[length-1] last returns data as an array of objects (not dissimilar to Redux State objects) with both the documentID and documentReference added as fields.
sortArray array a 2xn array of sort (i.e. "orderBy") conditions
refPath string null (optional) allows "table" parameter to reference a sub-collection of an existing document reference (I use a LOT of structured collections)
limit number page size

paginateFetch.limit : number

current limit of query results

Kind: instance property of PaginateFetch

paginateFetch.Query : Query

underlying query for fetch

Kind: instance property of PaginateFetch

paginateFetch.status : PagingStatus

current status of pagination -1 pending; 0 uninitialized; 1 updated;

Kind: instance property of PaginateFetch

paginateFetch.PageForward() ⇒ Promise.<Array.Record>

executes the query again to fetch the next set of records

Kind: instance method of PaginateFetch
Returns: Promise.<Array.Record> - returns an array of records - the next page

paginateFetch.PageBack() ⇒ Promise.<Array.Record>

executes the query again to fetch the previous set of records

Kind: instance method of PaginateFetch
Returns: Promise.<Array.Record> - returns an array of records - the next page

module.exports.PaginateGroupFetch

constructs an object to paginate through large Firestore Tables

Kind: static class of module.exports
Category: Paginator

new exports.PaginateGroupFetch(group, [filterArray], [sortArray], limit)
Param Type Default Description
group string a properly formatted string representing the requested collection - always an ODD number of elements
[filterArray] filterObject an (optional) 3xn array of filter(i.e. "where") conditions The array is assumed to be sorted in the correct order - i.e. filterArray[0] is added first; filterArray[length-1] last
[sortArray] sortObject a 2xn array of sort (i.e. "orderBy") conditions
limit number (optional) page size

paginateGroupFetch.limit : number

current limit basis for listener query

Kind: instance property of PaginateGroupFetch

paginateGroupFetch.status : PagingStatus

current status of listener -1 pending; 0 uninitialized; 1 updated;

Kind: instance property of PaginateGroupFetch

paginateGroupFetch.PageForward() ⇒ Promise.<Array.Record>

executes the query again to fetch the next set of records

Kind: instance method of PaginateGroupFetch
Returns: Promise.<Array.Record> - returns data as an array of objects (not dissimilar to Redux State objects) with both the documentID and documentReference added as fields.

paginateGroupFetch.PageBack() ⇒ Promise.<Array.Record>

executes the query again to fetch the previous set of records

Kind: instance method of PaginateGroupFetch
Returns: Promise.<Array.Record> - returns data as an array of objects (not dissimilar to Redux State objects) with both the documentID and documentReference added as fields.

module.exports.PaginatedListener

Creates an object to allow for paginating a listener for table read from Firestore. REQUIRES a sorting choice; masks some subscribe/unsubscribe action for paging forward/backward

Kind: static class of module.exports
Category: Paginator

new exports.PaginatedListener(tablePath, refPath, dataCallback, errCallback, limit, filterArray, sortArray)
Param Type Default Description
tablePath string a properly formatted string representing the requested collection - always an ODD number of elements
refPath refPath (optional) allows "table" parameter to reference a sub-collection of an existing document reference (I use a LOT of structured collections)
dataCallback RecordListener returns data as an array of objects (not dissimilar to Redux State objects) with both the documentID and documentReference added as fields.
errCallback RecordListener
limit number (optional) pagesize
filterArray Array.filterObject an (optional) 3xn array of filter(i.e. "where") conditions The array is assumed to be sorted in the correct order - i.e. filterArray[0] is added first; filterArray[length-1] last
sortArray Array.sortObject a 2xn array of sort (i.e. "orderBy") conditions

paginatedListener.tablePath : string

table path at base of listener query, relative to original refPath

Kind: instance property of PaginatedListener

paginatedListener.filterArray : filterObject

array of filter objects for listener query

Kind: instance property of PaginatedListener

paginatedListener.sortArray : sortObject

array of sort objects for listener query

Kind: instance property of PaginatedListener

paginatedListener.refPath : string

refPath as basis for listener query

Kind: instance property of PaginatedListener

paginatedListener.limit : number

current limit basis for listener query

Kind: instance property of PaginatedListener

paginatedListener.dataCallback : RecordListener

current dataCallback of listener query

Kind: instance property of PaginatedListener

paginatedListener.errCallback : callback

current errCallback of listener query

Kind: instance property of PaginatedListener

paginatedListener.status : number

current status of listener

Kind: instance property of PaginatedListener

paginatedListener._setQuery() ⇒ Query

reconstructs the basis query

Kind: instance method of PaginatedListener

paginatedListener.PageForward() ⇒ Unsubscribe

resets the listener query to the next page of results. Unsubscribes from the current listener, constructs a new query, and sets it as the new listener

Kind: instance method of PaginatedListener
Returns: Unsubscribe - returns the unsubscriber function (for lifecycle events)

paginatedListener.PageBack() ⇒ Unsubscribe

resets the listener query to the next page of results. Unsubscribes from the current listener, constructs a new query, and sets it
as the new listener

Kind: instance method of PaginatedListener
Returns: Unsubscribe - returns the unsubscriber function (for lifecycle events)

paginatedListener.ChangeLimit(newLimit) ⇒ Unsubscribe

sets page size limit to new value, and restarts the paged listener

Kind: instance method of PaginatedListener
Returns: Unsubscribe - returns the unsubscriber function (for lifecycle events)

Param Type
newLimit number

paginatedListener.ChangeFilter([filterArray]) ⇒ Unsubscribe

changes the filter on the subscription This has to unsubscribe the current listener, create a new query, then apply it as the listener

Kind: instance method of PaginatedListener
Returns: Unsubscribe - returns the unsubscriber function (for lifecycle events)

Param Type Description
[filterArray] filterObject an array of filter descriptors

paginatedListener.unsubscribe()

IF unsubscribe function is set, run it.

Kind: instance method of PaginatedListener

module.exports.ownerFilter(owner, queryFilter) ⇒ filterObject

Contructs a filter that selects only the "owner" section of a collectionGroup query - in other words, descendents of a particular top=level document. This takes advantage of Firestore's indexing, which "names"/indexes all documents using the FULL PATH to the document, starting from the top-most, i.e.: TOP_COLLECTION/{dociId}/NEXT_COLLECTION/{docId}/NEXT_NEXT_COLLECTION/{etc} This functions knowns NOTHING about the actual schema; it simply uses the path of the indicated "owner" as starting portion of ALL the "child" documents of the owner. It also takes advantage of the strictly alpha-numeric nature of the path string. As such, ALL children paths strings MUST be "greater than" the owner bare path, and MUST be LESS THAN the alpha-numerically "next" value: e.g. if the "owner" path is TOP_COLLECTION/abcdefg, then

/TOP_COLLECTION/abcdefh > name > //TOP_COLLECTION/abcdefg (assuming LEXICAL SORT) IMPORTANT NOTE: Because this filter uses an INEQUALITY, .sortBy() conditions are not supported

Kind: static method of module.exports
Category: Tree Slice

Param Type Description
owner Record
queryFilter filterObject additional filter parameters

module.exports.listenSlice(owner, collectionName, dataCallback, errCallback) ⇒ Unsubscribe

Uses the ownerFilter (above) to establish a listener to "just" the parts of a collectionGroup that are descendants of the passed "owner" record.

Kind: static method of module.exports
Returns: Unsubscribe - function to be called to release subscription
Category: Tree Slice

Param Type Description
owner Record
owner.refPath string string representing the full path to the Firestore document.
collectionName string name of the desired collectionGroup
dataCallback RecordListener function to be called with changes to record
errCallback RecordListener function to be called when an error occurs in listener

module.exports.fetchSlice(owner, collectionName) ⇒ Promise.Array.Record

Wrapper around database fetch, using ownerFilter above to select/fetch just an "owner" parent document's descendants from a collectionGroup

Kind: static method of module.exports
Returns: Promise.Array.Record - response
Category: Tree Slice

Param Type Description
owner Record
owner.refPath string string representing the full path to the Firestore document.
collectionName string name of the desired collectionGroup

module.exports.querySlice(owner, collectionName, filterArray) ⇒ Promise.Array.Record

Wrapper around database fetch, using ownerFilter above to select/fetch just an "owner" parent document's descendants from a collectionGroup

Kind: static method of module.exports
Returns: Promise.Array.Record - response
Category: Tree Slice

Param Type Description
owner Record
owner.refPath string string representing the full path to the Firestore document.
collectionName string name of the desired collectionGroup
filterArray Array.filterObject filter parameters

module.exports.listenQuerySlice(owner, collectionName, filterArray, dataCallback, errCallback) ⇒ callback

Uses the ownerFilter (above) to establish a listener to "just" the parts of a collectionGroup that are descendants of the passed "owner" record.

Kind: static method of module.exports
Returns: callback - function to be called to release subscription
Category: Tree Slice

Param Type Description
owner Record
owner.refPath string string representing the full path to the Firestore document.
collectionName string name of the desired collectionGroup
filterArray Array.filterObject filter parameters
dataCallback RecordListener function to be called with changes to record
errCallback callback function to be called when an error occurs in listener

module.exports.ownerType(record) ⇒ string

Returns the "type" (collection name) of the top-most parent of a record, derived from the refPath

Kind: static method of module.exports
Returns: string - the collection name
Category: Tree Slice

Param Type
record Record

module.exports.ownerId(record) ⇒ string

Returns the Id (documentId) of the top-most parent of a record, derived from the refPath

Kind: static method of module.exports
Returns: string - the Id
Category: Tree Slice

Param Type
record Record

module.exports.ownerRefPath(record) ⇒ string

Returns the Id (documentId) of the top-most parent of a record, derived from the refPath

Kind: static method of module.exports
Returns: string - the Id
Category: Tree Slice

Param Type
record Record

module.exports.ownerByChild(record) ⇒ Record

Returns the bare owner record reference to the parent (root) of a provided child

Kind: static method of module.exports
Returns: Record - reference to the parent (root) record
Category: Tree Slice

Param Type Description
record Record child record

module.exports.ownerByOwnerType(ownerId, ownerType) ⇒ Record

returns the minimal reference record from an Id and "type"

Kind: static method of module.exports
Returns: Record - reference to the parent (root) record
Category: Tree Slice

Param Type
ownerId string
ownerType string

module.exports.fetchOwner(record) ⇒ Document

returns the record for the top-most parent of a record, derived from the refPath

Kind: static method of module.exports
Category: Tree Slice

Param Type
record Record

module.exports.typedPaginatedListener ⇐ PaginatedListener

Kind: static class of module.exports
Extends: PaginatedListener
Category: Typed

new exports.typedPaginatedListener(type, parent, pageSize, dataCallback, errCallback)

Implements a PaginatedListener using type syntax

Param Type Description
type string the "type" (CollectionName) for this record
parent RecordObject the (optional) parent for this record (i.e. a sub-type)
parent.refPath string the only required part of a parent record
pageSize number the page size requested
dataCallback CollectionListener the callback where data is returned
errCallback callback callback for errors

module.exports.recordType(record) ⇒ string

Returns the "type" (collection name) the passed record is stored in, derived from the refPath

Kind: static method of module.exports
Returns: string - the collection name
Category: Typed

Param Type
record Record

module.exports.recordId(record) ⇒ string

Returns the Id (documentId) of the passed record derived from the refPath

Kind: static method of module.exports
Returns: string - the Id
Category: Typed

Param Type
record Record

module.exports.typedWrite(data, parent, type, batch) ⇒ Promise.ChainType

optionally batched record update - abstracts batch process from specific types

Kind: static method of module.exports
Returns: Promise.ChainType - WriteBatch, Transaction or Void
Category: Typed

Param Type Description
data Record the data object/record to update. This will create a new one if it doesn't exist
parent Record parent object (if any) this belongs to
parent.refPath string full path to parent document
type string name of type of object - i.e. the sub-collection name
batch WriteBatch | Transaction batching object. Transaction will be added to the batch

module.exports.typedWriteByTree(data, tree, type, batch) ⇒ Promise.ChainType

optionally batched record update - abstracts batch process from specific types

Kind: static method of module.exports
Returns: Promise.ChainType - WriteBatch, Transaction or Void
Category: Typed

Param Type Description
data Record the data object/record to update. This will create a new one if it doesn't exist
tree ArtistTree Object with properties of refPath segments
type string name of type of object - i.e. the sub-collection name
batch WriteBatch | Transaction batching object. Transaction will be added to the batch

module.exports.typedWriteByChild(data, tree, type, batch) ⇒ Promise.ChainType

optionally batched record update - abstracts batch process from specific types

Kind: static method of module.exports
Returns: Promise.ChainType - WriteBatch, Transaction or Void
Category: Typed

Param Type Description
data Record the data object/record to update. This will create a new one if it doesn't exist
tree ArtistTree Object with properties of refPath segments
type string name of type of object - i.e. the sub-collection name
batch WriteBatch | Transaction batching object. Transaction will be added to the batch

module.exports.typedCreate(data, parent, type, batch) ⇒ Promise.ChainType

Creates a new document reference of the indicated type, and writes it to the backend. Specific intent is when the Id needs to be pre-specified, or shared outside this function. Normal writing action will silently create a new document, which has to then be found by query

Kind: static method of module.exports
Returns: Promise.ChainType - WriteBatch, Transaction or Void
Category: Typed

Param Type Description
data Record the data object/record to create. This will create a new one if it doesn't exist
parent Record parent object (if any) this belongs to
parent.refPath string full path to parent document
type string name of type of object - i.e. the sub-collection name
batch WriteBatch | Transaction batching object. Transaction will be added to the batch

module.exports.treeFromChild(child) ⇒ RecordTree

Extracts a tree of document ID's from a child document (assumes is a child)

Kind: static method of module.exports
Category: Typed

Param Type Description
child Record document (regardless of depth) of a tree
child.refPath string

module.exports.typedTablePathFromTree(tree, type, branchType) ⇒ string

Builds a refPath down to a desired collection/type from an existing RecordTree Map.

Kind: static method of module.exports
Returns: string - constructed TablePath (collection)
Category: Typed

Param Type Description
tree RecordTree
type string
branchType string a collection name to start branching from. This is in case tree was built from a sister collection/document

module.exports.typedRefPathFromTree(tree, type) ⇒ string

Builds a refPath down to a desired collection/type from an existing RecordTree Map.

Kind: static method of module.exports
Returns: string - constructed refPath (document)
Category: Typed

Param Type
tree RecordTree
type string

module.exports.typedIdFromChild(child, type)

Looks up a "tree" to find the Id of the document at the requested collection level ("type")

Kind: static method of module.exports
Category: Typed

Param Type Description
child Record document (regardless of depth) of a tree
child.refPath string
type string name of desired type/collection level in tree

module.exports.typedTablePathFromChild(child, type) ⇒ string

Builds a refPath up to a desired collection/type from an existing child in a tree

Kind: static method of module.exports
Returns: string - constructed refPath (collection)
Category: Typed

Param Type Description
child Record document (regardless of depth) of a tree
child.refPath string
type string

module.exports.typedRefPathFromChild(child, type) ⇒ string

Builds a refPath up to a desired collection/type from an existing child in a tree

Kind: static method of module.exports
Returns: string - constructed refPath (document)
Category: Typed

Param Type Description
child Record document (regardless of depth) of a tree
child.refPath string
type string

module.exports.typedFetchFromChild(child, refPath, type, batch) ⇒ Promise.<RecordObject>

function to fetch a document from "up" the collection/document tree of a child document

Kind: static method of module.exports
Category: Typed

Param Type Description
child Record assumed to be an object in a collection/document Tree
refPath string
type string type/collection to fetch parent document from
batch ChainType optional batch object to chain

module.exports.typedFetchFromTree(tree, refPath, type, batch) ⇒ Promise.<RecordObject>

function to fetch a document from "up" the collection/document tree of a child document

Kind: static method of module.exports
Category: Typed

Param Type Description
tree RecordTree assumed to be an object in a collection/document Tree
refPath string
type string type/collection to fetch parent document from
batch WriteBatch | Transaction optional batch object to chain

module.exports.typedCollectFromTree(tree, type, batch) ⇒ Promise.<Array.Record>

function to collect documents from "up" the collection/document tree of a child document

Kind: static method of module.exports
Category: Typed

Param Type Description
tree RecordTree assumed to be an object in a collection/document Tree
type string type/collection to fetch parent document from
batch WriteBatch | Transaction optional batch object to chain

module.exports.typedCollectFromChild(child, type, batch)

function to collect documents from "up" the collection/document tree of a child document

Kind: static method of module.exports
Category: Typed

Param Type Description
child Record assumed to be an object in a collection/document Tree
type string type/collection to fetch parent document from
batch WriteBatch | Transaction optional batch object to chain

module.exports.typedListener(type, parent, type, dataCallback, errCallback) ⇒ callback

Uses the ownerFilter (above) to establish a listener to "just" the parts of a collectionGroup that are descendants of the passed "owner" record.

Kind: static method of module.exports
Returns: callback - function to be called to release subscription
Category: Typed

Param Type Description
type string name of type of object - i.e. the sub-collection name
parent Record parent object (if any) this belongs to
parent.refPath string full path to parent document
type string name of the desired collectionGroup
dataCallback CollectionListener function to be called with changes to record
errCallback callback function to be called when an error occurs in listener

module.exports~dbReference(refPath) ⇒ DocumentReference

generates a document reference from a path if passed; else returns the db base reference

Kind: inner method of module.exports

Param Type Description
refPath string Path to base actions from. May be null

module.exports~createRefFromPath(docPath, refPath) ⇒ DocumentReference

Creates a DocumentReference from relative docPath and an (optional) absolute refPath

Kind: inner method of module.exports

Param Type Default
docPath string
refPath refPath

module.exports~filterQuery(query, filterArray) ⇒ Query

builds and returns a query built from an array of filter (i.e. "where") conditions

Kind: inner method of module.exports
Returns: Query - Firestore Query object

Param Type Default Description
query Query collectionReference or Query to build filter upong
filterArray Array.filterObject an (optional) 3xn array of filter(i.e. "where") conditions

module.exports~sortQuery(query, sortArray) ⇒

builds and returns a query built from an array of filter (i.e. "where") conditions

Kind: inner method of module.exports
Returns: Firestore Query object

Param Type Default Description
query Query collectionReference or Query to build filter upong
sortArray Array.sortObject an (optional) 2xn array of sort (i.e. "orderBy") conditions

module.exports~limitQuery(query, limit) ⇒ Query

builds and returns a query built from an array of filter (i.e. "where") conditions

Kind: inner method of module.exports
Returns: Query - Firestore Query object

Param Type Default Description
query Query collectionReference or Query to build filter upong
limit number an (optional) 2xn array of sort (i.e. "orderBy") conditions

module.exports~ListenRecordsCommon(reference, dataCallback, errCallback) ⇒ function

Kind: inner method of module.exports
Returns: function - function to be called to release subscription

Param Type Description
reference DocumentReference
dataCallback RecordListener
errCallback callback function to be called when an error occurs in listener

module.exports~Record : object

common properties of our database records

Kind: inner typedef of module.exports
Properties

Name Type Description
Id string Id of the document as stored in Firestore May be null for new objects
refPath string string representing the full path to the Firestore document. May be blank for new documents to be saved.

module.exports~filterObject : Object

Kind: inner typedef of module.exports
Properties

Name Type
fieldRef string
opStr string
value any

module.exports~RecordListener : function

Kind: inner typedef of module.exports

Param Type
documentSnapshot DocumentSnapshot

module.exports~Unsubscribe : function

Kind: inner typedef of module.exports

module.exports~CollectionListener : function

Kind: inner typedef of module.exports

Param Type
querySnapshot QuerySnapshot

FirebaseStorageWrapper

A set of helper-wrapper functions around firebase firestore, storage and auth. Intent is to treat Firestore as a hierarchical record-oriented database; originally conceived to port from one database to another.

FirebaseStorageWrapper.paginateListing

A class to manage paging through a listing of storage references

Kind: static class of FirebaseStorageWrapper

new exports.paginateListing(storageReference, limit)

constructs an object to paginate through large Firestore Tables

Param Type
storageReference StorageReference
limit number

paginateListing.PageForward() ⇒ Promise.<Array.StorageReference>

executes the query again to fetch the next set of records

Kind: instance method of paginateListing
Returns: Promise.<Array.StorageReference> - returns an array of records - the next page

FirebaseStorageWrapper.makeStorageRefFromRecord(record, key, filename) ⇒ StorageReference

This function is part of a storage scheme that uses parallel structures between Firestore collection/documents and Storage paths. The concept here is all Storage items are part of/belong to Firestore documents. The function takes a document record, and combines it with optional key and filename to construct a '/' separated path to a stored item, , and returns a Storage reference to that item. Note this simply makes the Storage Ref - it does not carry out any operations

Kind: static method of FirebaseStorageWrapper
Returns: StorageReference - a Firestore Storage Reference

Param Type Description
record string A firestore document Record - the '/' separated collection/ document path is used as the path to the stored item.
key string An optional string identifying the specific field stored item is associated with
filename string an optional name to be associated with the stored item.

FirebaseStorageWrapper.listReference(storageReference, optionsObject) ⇒ Promise.<ListResult>

Kind: static method of FirebaseStorageWrapper

Param Type Description
storageReference StorageReference a storage reference to a "directory", not a file. More accurate to state that it is treated as a directory, since such niceties are a Firestore convention, not a physical reality
optionsObject ListOptions

FirebaseStorageWrapper.makeFileURLFromRecord(record, key, filename) ⇒ Promise.<string>

This function is part of a storage scheme that uses parallel structures between Firestore collection/documents and Storage paths. The concept here is all Storage items are part of/belong to Firestore documents. This function takes a document record, and combines it with optional key and filename to construct a '/' separated path to a stored item, , and returns a URL that can be used to access that item. Note this simply makes the URL - it does not carry out any operations

Kind: static method of FirebaseStorageWrapper
Fulfil: string a "long-lived" URL to access the file.
Reject: string

Param Type Description
record RecordObject A firestore document Record - the '/' separated collection/ document path is used as the path to the stored item.
key string An optional string identifying the specific field an stored item is associated with
filename string an optional name to be associated with the stored item.

FirebaseStorageWrapper.makePrivateURLFromRecord(record, key) ⇒ string

This function is part of a storage scheme that uses parallel structures between Firestore collection/documents and Storage paths. The concept here is all Storage items are part of/belong to Firestore documents. This function takes a document record, and combines it with optional key, to construct a '/' separated path to a stored item, , and returns a URL that can be used to access that item. Note this simply makes the URL - it does not carry out any operations

Kind: static method of FirebaseStorageWrapper
Returns: string - The resulting Security-Rule-compliant URL

Param Type Description
record RecordObject A firestore document Record - the '/' separated collection/ document path is used as the path to the stored item.
key string An optional string identifying the specific field an stored item is associated with

FirebaseStorageWrapper.makePrivateURLFromReference(reference, key) ⇒ string

This function is part of a storage scheme that uses parallel structures between Firestore collection/documents and Storage paths. The concept here is all Storage items are part of/belong to Firestore documents. This function takes a document record, and combines it with optional key, to construct a '/' separated path to a stored item, , and returns a URL that can be used to access that item. Note this simply makes the URL - it does not carry out any operations

Kind: static method of FirebaseStorageWrapper
Returns: string - The resulting Security-Rule-compliant URL

Param Type Description
reference StorageReference A firestore document Record - the '/' separated collection/ document path is used as the path to the stored item.
key string An optional string identifying the specific field an stored item is associated with

FirebaseStorageWrapper.makePrivateURLFromPath(fullPath) ⇒ string

This function is part of a storage scheme that uses parallel structures between Firestore collection/documents and Storage paths. The concept here is all Storage items are part of/belong to Firestore documents. This function takes a full path to a Storage object and turns it into URL. If "type"is not included, the URL will return the metadata, not the contents. Note this simply makes the URL - it does not carry out any operations

Kind: static method of FirebaseStorageWrapper
Returns: string - constructed Security-Rule-compliant URL

Param Type Description
fullPath string required path to the stored item.

FirebaseStorageWrapper.getDefaultImageURL(key) ⇒ string

Kind: static method of FirebaseStorageWrapper

Param Type Description
key string name/key of default image file

FirebaseStorageWrapper.getURLFromFilePath(filePath) ⇒ string

Kind: static method of FirebaseStorageWrapper

Param Type
filePath string

FirebaseStorageWrapper.dataURLToBlob(dataURL) ⇒ Object

Kind: static method of FirebaseStorageWrapper
Returns: Object - {ext: extension, base64: data}

Param Type
dataURL object

FirebaseStorageWrapper~FirebaseStorageWrapper(firebase)

Initializes the Auth service of the provided firebase app. Also instantiates various constants and helper functions

Kind: inner method of FirebaseStorageWrapper

Param Type
firebase firebase

Example

import * as firebase from "firebase/app";
import "firebase/storage";
import FirebaseStorage from "@leaddreamer/firebase-wrapper/FirebaseStorageWrapper";
import {config} from "whereever-you-put-it";

((myconfig) {
try {
  firebase.app();
} catch (err) {
  firebase.initializeApp(myconfig);
}
FirebaseStorage(firebase);
})(config);

FirebaseStorageWrapper~storeBlobByRecord(blob, record, key, filename) ⇒ UploadTask

Firestore's document sizes can be limited - 1MB - so our system stores larger digital "blobs" in a parallel Firestore Storage.

Kind: inner method of FirebaseStorageWrapper
Returns: UploadTask - Firestore Storage UploadTask Object

Param Type Description
blob blob A data blob in DataURI format to store in Storage
record RecordObject A firestore document Record - the '/' separated collection/ document path is used as the path to the stored item.
key string An optional string identifying the specific field an stored item is associated with
filename string an optional name to be associated with the stored item.

FirebaseStorageWrapper~storeDataURLByRecord(dataURL, record, key, filename) ⇒ UploadTask

Firestore's document sizes can be limited - 1MB - so our system stores larger digital "blobs" in a parallel Firestore Storage.

Kind: inner method of FirebaseStorageWrapper
Returns: UploadTask - Firestore Storage UploadTask Object

Param Type Description
dataURL dataURL A data blob in DataURI format to store in Storage
record RecordObject A firestore document Record - the '/' separated collection/ document path is used as the path to the stored item.
key string An optional string identifying the specific field an stored item is associated with
filename string an optional name to be associated with the stored item.

FirebaseStorageWrapper~ListOptions : object

Kind: inner typedef of FirebaseStorageWrapper
Properties

Name Type Description
maxResults number If set, limits the total number of prefixes and items to return. The default and maximum maxResults is 1000.
pageToken string The nextPageToken from a previous call to list(). If provided, listing is resumed from the previous position.

FirebaseStorageWrapper~ListResult : object

Kind: inner typedef of FirebaseStorageWrapper
Properties

Name Type
items Array.StorageReference
prefixes Array.StorageReference
nextPageToken string

FirebaseStorageWrapper~PaginateList : object

Kind: inner typedef of FirebaseStorageWrapper
Properties

Name Type
storageReference StorageReference
status number
limit number
listOptions ListOptions

FirebaseStorageWrapper~File : object

Kind: inner typedef of FirebaseStorageWrapper
Properties

Name Type Description
metadata FileMetadata
acl object
name string //various methods

FirebaseStorageWrapper~FileMetadata : object

Kind: inner typedef of FirebaseStorageWrapper
Properties

Name Type Description
kind string:"storage#object"
id string
selfLink string
name string
bucket string
generation long
metageneration long
contentType string
timeCreated datetime
updated datetime
customTime datetime
timeDeleted datetime
temporaryHold boolean
eventBasedHold boolean
retentionExpirationTime datetime
storageClass string
timeStorageClassUpdated datetime
size ulong
md5Hash string
mediaLink string
contentEncoding string
contentDisposition string
contentLanguage string
cacheControl string
metadata object Custom metadata key:value pairs
metadata.firebaseStorageDownloadTokens string
metadata.key string
[acl] objectAccessControls
owner object
owner.entity string
owner.entityId string
crc32c string
componentCount integer
etag string
customerEncryption object
customerEncryption.encryptionAlgorithm string
customerEncryption.keySha256 string
kmsKeyName string

FirebaseStorageAdminEmulator

A set of helper-wrapper functions around firebase storage Intent is to treat Firestore as a hierarchical record-oriented database and Storage as a parallel structure originally conceived to port from one database to another.

FirebaseStorageAdminEmulator~adminRef

Kind: inner class of FirebaseStorageAdminEmulator

new adminRef(bucket, path)

Create a class that emulates a Firebase Storage storageRef using Firebase Admin Cloud Storage Functions. This is not an exact replica, but one with similar static members and methods. Intended for use with a higher-level Wrapper library This returns an object that has many of the same members and methods as a Firebase storageRef, but only in conjunction with the methods here, and likely only with the "wrapper" it is defined for.

Param Type Description
bucket StorageBucket A bucket instance
path string a string representing the "path" to the intended target document

adminRef.fileRef : storageRef

used to affect file operations to emulate Firebase Storage functions

Kind: instance property of adminRef

adminRef.fullPath : string

Full path, including file name

Kind: instance property of adminRef

adminRef.name : string

filename portion only

Kind: instance property of adminRef

adminRef.bucket : string

name of containing bucket

Kind: instance property of adminRef

adminRef.parent : storageRef

Cloud Storage object don't really have a parent or root

Kind: instance property of adminRef

adminRef.storage : storageApp

app instance

Kind: instance property of adminRef

adminRef.metadata : string

access token

Kind: instance property of adminRef

adminRef.child(path) ⇒ Promise.<StorageRefEmulation>

creates and returns a new adminRef object from existin path

Kind: instance method of adminRef

Param Type Description
path string a relative path from the existing storageRef to create child

adminRef.delete() ⇒ Promise.<void>

Deletes the referenced storage item

Kind: instance method of adminRef

adminRef.getDownloadURL() ⇒ Promise.<string>

Generates a long-lived (essentially permanent until revoked) Public-Access URL for a storage item in FIREBASE (not Cloud Storage) format

Kind: instance method of adminRef

adminRef.getToken() ⇒ Promise.<string>

Fetches (or creates as needed) a unique token for a storage object

Kind: instance method of adminRef

adminRef.getMetadata() ⇒ Promise.<FileMetadata>

Fetches the FileMetadata for the storage object. Custom/Client metadata is located in FileMetadata.metadata

Kind: instance method of adminRef

adminRef.put(data, metadata) ⇒ Promise.<object>

puts a block of data (and optional metadata) into storage at location specified by adminRef

Kind: instance method of adminRef

Param Type Default
data blob
metadata object

adminRef.putString(dataString, stringFormat, metadata) ⇒ Promise.<object>

puts a string (possibly encoded data) into a storage file described by the provided reference.

Kind: instance method of adminRef

Param Type Default
dataString string
stringFormat string null
metadata FileMetadata

FirebaseStorageAdminEmulator~FirebaseStorageAdminEmulator(firebase)

Initializes the Storage service of the provided firebase app. Also instantiates various constants and helper functions. This is a WRAPPER around CLOUD STORAGE (admin) functions to emulate FIREBASE functionality, keeping a similar API between client & cloud code. NOTE: admin "references" ARE NOT the same as client references, and are NOT interchangeable. Do not mix client & admin code (not actually possible in this wrapper)

Kind: inner method of FirebaseStorageAdminEmulator

Param Type
firebase firebase

PAGINATE_INIT : number

Kind: global constant
Category: Paginate Constants

PAGINATE_PENDING : number

Kind: global constant
Category: Paginate Constants

PAGINATE_UPDATED : number

Kind: global constant
Category: Paginate Constants

PAGINATE_END : number

Kind: global constant
Category: Paginate Constants

PAGINATE_DEFAULT : number

Kind: global constant
Category: Paginate Constants

PAGINATE_CHOICES : Array.number

Kind: global constant
Category: Paginate Constants

Kind: global typedef
Category: Paginate Constants


© 2020-2021 Tracy Hall

About

Created with CodeSandbox

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published