6.2.0 • Published 8 months ago

@capacitor-firebase/firestore v6.2.0

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
8 months ago

@capacitor-firebase/firestore

Unofficial Capacitor plugin for Firebase Cloud Firestore.^1

Installation

npm install @capacitor-firebase/firestore
npx cap sync

Add Firebase to your project if you haven't already (Android / iOS / Web).

Android

Variables

This plugin will use the following project variables (defined in your app’s variables.gradle file):

  • $firebaseFirestoreVersion version of com.google.firebase:firebase-firestore (default: 24.7.1)

Configuration

No configuration required for this plugin.

Demo

A working example can be found here: robingenz/capacitor-firebase-plugin-demo

Starter templates

The following starter templates are available:

Usage

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const addDocument = async () => {
  await FirebaseFirestore.addDocument({
    reference: 'users',
    data: { 
      first: 'Alan', 
      last: 'Turing', 
      born: 1912 
    },
  });
};

const setDocument = async () => {
  await FirebaseFirestore.setDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
    data: { 
      first: 'Alan', 
      last: 'Turing', 
      born: 1912 
    },
    merge: true,
  });
};

const getDocument = async () => {
  const { snapshot } = await FirebaseFirestore.getDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
  });
  return snapshot;
};

const updateDocument = async () => {
  await FirebaseFirestore.updateDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
    data: { 
      first: 'Alan', 
      last: 'Turing', 
      born: 1912 
    },
  });
};

const deleteDocument = async () => {
  await FirebaseFirestore.deleteDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
  });
};

const getCollection = async () => {
  const { snapshots } = await FirebaseFirestore.getCollection({
    reference: 'users',
    compositeFilter: {
      type: 'and',
      queryConstraints: [
        {
          type: 'where',
          fieldPath: 'born',
          opStr: '==',
          value: 1912,
        },
      ],
    },
    queryConstraints: [
      {
        type: 'orderBy',
        fieldPath: 'born',
        directionStr: 'desc',
      },
      {
        type: 'limit',
        limit: 10,
      },
    ],
  });
  return snapshots;
};

const getCollectionGroup = async () => {
  const { snapshots } = await FirebaseFirestore.getCollectionGroup({
    reference: 'users',
    compositeFilter: {
      type: 'and',
      queryConstraints: [
        {
          type: 'where',
          fieldPath: 'born',
          opStr: '==',
          value: 1912,
        },
      ],
    },
    queryConstraints: [
      {
        type: 'orderBy',
        fieldPath: 'born',
        directionStr: 'desc',
      },
      {
        type: 'limit',
        limit: 10,
      },
    ],
  });
  return snapshots;
};

const enableNetwork = async () => {
  await FirebaseFirestore.enableNetwork();
};

const disableNetwork = async () => {
  await FirebaseFirestore.disableNetwork();
};

const useEmulator = async () => {
  await FirebaseFirestore.useEmulator({
    host: '10.0.2.2',
    port: 9001,
  });
};

const addDocumentSnapshotListener = async () => {
  const callbackId = await FirebaseFirestore.addDocumentSnapshotListener(
    {
      reference: 'users/Aorq09lkt1ynbR7xhTUx',
    },
    (event, error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(event);
      }
    }
  );
  return callbackId;
};

const addCollectionSnapshotListener = async () => {
  const callbackId = await FirebaseFirestore.addCollectionSnapshotListener(
    {
      reference: 'users',
      compositeFilter: {
        type: 'and',
        queryConstraints: [
          {
            type: 'where',
            fieldPath: 'born',
            opStr: '==',
            value: 1912,
          },
        ],
      },
      queryConstraints: [
        {
          type: 'orderBy',
          fieldPath: 'born',
          directionStr: 'desc',
        },
        {
          type: 'limit',
          limit: 10,
        },
      ],
    },
    (event, error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(event);
      }
    }
  );
  return callbackId;
};

const addCollectionGroupSnapshotListener = async () => {
  const callbackId = await FirebaseFirestore.addCollectionGroupSnapshotListener(
    {
      reference: 'users',
      compositeFilter: {
        type: 'and',
        queryConstraints: [
          {
            type: 'where',
            fieldPath: 'born',
            opStr: '==',
            value: 1912,
          },
        ],
      },
      queryConstraints: [
        {
          type: 'orderBy',
          fieldPath: 'born',
          directionStr: 'desc',
        },
        {
          type: 'limit',
          limit: 10,
        },
      ],
    },
    (event, error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(event);
      }
    }
  );
  return callbackId;
};

const removeSnapshotListener = async (callbackId: string) => {
  await FirebaseFirestore.removeSnapshotListener({
    callbackId,
  });
};

const removeAllListeners = async () => {
  await FirebaseFirestore.removeAllListeners();
};

API

addDocument(...)

addDocument(options: AddDocumentOptions) => Promise<AddDocumentResult>

Adds a new document to a collection with the given data.

ParamType
optionsAddDocumentOptions

Returns: Promise<AddDocumentResult>

Since: 5.2.0


setDocument(...)

setDocument(options: SetDocumentOptions) => Promise<void>

Writes to the document referred to by the specified reference. If the document does not yet exist, it will be created.

ParamType
optionsSetDocumentOptions

Since: 5.2.0


getDocument(...)

getDocument<T extends DocumentData = DocumentData>(options: GetDocumentOptions) => Promise<GetDocumentResult<T>>

Reads the document referred to by the specified reference.

ParamType
optionsGetDocumentOptions

Returns: Promise<GetDocumentResult<T>>

Since: 5.2.0


updateDocument(...)

updateDocument(options: UpdateDocumentOptions) => Promise<void>

Updates fields in the document referred to by the specified reference.

ParamType
optionsUpdateDocumentOptions

Since: 5.2.0


deleteDocument(...)

deleteDocument(options: DeleteDocumentOptions) => Promise<void>

Deletes the document referred to by the specified reference.

ParamType
optionsDeleteDocumentOptions

Since: 5.2.0


writeBatch(...)

writeBatch(options: WriteBatchOptions) => Promise<void>

Execute multiple write operations as a single batch.

ParamType
optionsWriteBatchOptions

Since: 6.1.0


getCollection(...)

getCollection<T extends DocumentData = DocumentData>(options: GetCollectionOptions) => Promise<GetCollectionResult<T>>

Reads the collection referenced by the specified reference.

ParamType
optionsGetCollectionOptions

Returns: Promise<GetCollectionResult<T>>

Since: 5.2.0


getCollectionGroup(...)

getCollectionGroup<T extends DocumentData = DocumentData>(options: GetCollectionGroupOptions) => Promise<GetCollectionGroupResult<T>>

Reads the collection group referenced by the specified reference.

ParamType
optionsGetCollectionGroupOptions

Returns: Promise<GetCollectionGroupResult<T>>


clearPersistence()

clearPersistence() => Promise<void>

Clears the persistent storage. This includes pending writes and cached documents.

Must be called after the app is shutdown or when the app is first initialized.

Since: 5.2.0


enableNetwork()

enableNetwork() => Promise<void>

Re-enables use of the network.

Since: 5.2.0


disableNetwork()

disableNetwork() => Promise<void>

Disables use of the network.

Since: 5.2.0


useEmulator(...)

useEmulator(options: UseEmulatorOptions) => Promise<void>

Instrument your app to talk to the Firestore emulator.

ParamType
optionsUseEmulatorOptions

Since: 6.1.0


addDocumentSnapshotListener(...)

addDocumentSnapshotListener<T extends DocumentData = DocumentData>(options: AddDocumentSnapshotListenerOptions, callback: AddDocumentSnapshotListenerCallback<T>) => Promise<CallbackId>

Adds a listener for document snapshot events.

ParamType
optionsAddDocumentSnapshotListenerOptions
callbackAddDocumentSnapshotListenerCallback<T>

Returns: Promise<string>

Since: 5.2.0


addCollectionSnapshotListener(...)

addCollectionSnapshotListener<T extends DocumentData = DocumentData>(options: AddCollectionSnapshotListenerOptions, callback: AddCollectionSnapshotListenerCallback<T>) => Promise<CallbackId>

Adds a listener for collection snapshot events.

ParamType
optionsAddCollectionSnapshotListenerOptions
callbackAddCollectionSnapshotListenerCallback<T>

Returns: Promise<string>

Since: 5.2.0


addCollectionGroupSnapshotListener(...)

addCollectionGroupSnapshotListener<T extends DocumentData = DocumentData>(options: AddCollectionGroupSnapshotListenerOptions, callback: AddCollectionGroupSnapshotListenerCallback<T>) => Promise<CallbackId>

Adds a listener for collection group snapshot events.

ParamType
optionsAddCollectionGroupSnapshotListenerOptions
callbackAddCollectionGroupSnapshotListenerCallback<T>

Returns: Promise<string>

Since: 6.1.0


removeSnapshotListener(...)

removeSnapshotListener(options: RemoveSnapshotListenerOptions) => Promise<void>

Remove a listener for document or collection snapshot events.

ParamType
optionsRemoveSnapshotListenerOptions

Since: 5.2.0


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.

Since: 5.2.0


Interfaces

AddDocumentResult

PropTypeDescriptionSince
referenceDocumentReferenceThe reference of the newly added document.5.2.0

DocumentReference

PropTypeDescriptionSince
idstringThe document's identifier within its collection.5.2.0
pathstringThe path of the document.5.2.0

AddDocumentOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
dataDocumentDataAn object containing the data for the new document.5.2.0

DocumentData

SetDocumentOptions

PropTypeDescriptionDefaultSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
dataDocumentDataAn object containing the data for the new document.5.2.0
mergebooleanWhether to merge the provided data with an existing document.false5.2.0

GetDocumentResult

PropTypeDescriptionSince
snapshotDocumentSnapshot<T>The current document contents.5.2.0

DocumentSnapshot

PropTypeDescriptionSince
idstringThe document's identifier within its collection.5.2.0
pathstringThe path of the document.5.2.0
dataT | nullAn object containing the data for the document. Returns null if the document doesn't exist.5.2.0
metadataSnapshotMetadataMetadata about the snapshot, concerning its source and if it has local modifications.6.2.0

SnapshotMetadata

PropTypeDescriptionSince
fromCachebooleanTrue if the snapshot was created from cached data.6.2.0
hasPendingWritesbooleanTrue if the snapshot was created from pending write data.6.2.0

GetDocumentOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0

UpdateDocumentOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
dataDocumentDataAn object containing the data for the new document.5.2.0

DeleteDocumentOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0

WriteBatchOptions

PropTypeDescriptionSince
operationsWriteBatchOperation[]The operations to execute in the batch.6.1.0

WriteBatchOperation

PropTypeDescriptionSince
type'set' | 'update' | 'delete'The type of operation.6.1.0
referencestringThe reference as a string, with path components separated by a forward slash (/).6.1.0
dataDocumentDataAn object containing the data for the new document.6.1.0

GetCollectionResult

PropTypeDescriptionSince
snapshotsDocumentSnapshot<T>[]The documents in the collection.5.2.0

GetCollectionOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
compositeFilterQueryCompositeFilterConstraintThe filter to apply.5.2.0
queryConstraintsQueryNonFilterConstraint[]Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.5.2.0

QueryCompositeFilterConstraint

PropTypeDescriptionSince
type'and' | 'or'The type of the constraint.5.2.0
queryConstraintsQueryFilterConstraint[]The filters to apply.5.2.0

QueryFieldFilterConstraint

PropTypeDescriptionSince
type'where'The type of the constraint.5.2.0
fieldPathstringThe path to compare.5.2.0
opStrQueryOperatorThe operation string to apply.5.2.0
valueanyThe value for comparison.5.2.0

QueryOrderByConstraint

PropTypeDescriptionSince
type'orderBy'The type of the constraint.5.2.0
fieldPathstringThe path to compare.5.2.0
directionStrOrderByDirectionThe direction to sort by.5.2.0

QueryLimitConstraint

PropTypeDescriptionSince
type'limit' | 'limitToLast'The type of the constraint.5.2.0
limitnumberThe maximum number of items to return.5.2.0

QueryStartAtConstraint

PropTypeDescriptionSince
type'startAt' | 'startAfter'The type of the constraint.5.2.0
referencestringThe reference to start at or after as a string, with path components separated by a forward slash (/). Attention: This requires an additional document read.5.2.0

QueryEndAtConstraint

PropTypeDescriptionSince
type'endAt' | 'endBefore'The type of the constraint.5.2.0
referencestringThe reference as to end at or before as a string, with path components separated by a forward slash (/). Attention: This requires an additional document read.5.2.0

GetCollectionGroupResult

PropTypeDescriptionSince
snapshotsDocumentSnapshot<T>[]The documents in the collection.5.2.0

GetCollectionGroupOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
compositeFilterQueryCompositeFilterConstraintThe filter to apply.5.2.0
queryConstraintsQueryNonFilterConstraint[]Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.5.2.0

UseEmulatorOptions

PropTypeDescriptionDefaultSince
hoststringThe emulator host without any port or scheme. Note when using a Android Emulator device: 10.0.2.2 is the special IP address to connect to the 'localhost' of the host computer.6.1.0
portnumberThe emulator port.80806.1.0

AddDocumentSnapshotListenerOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0

AddCollectionSnapshotListenerOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
compositeFilterQueryCompositeFilterConstraintThe filter to apply.5.2.0
queryConstraintsQueryNonFilterConstraint[]Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.5.2.0

AddCollectionGroupSnapshotListenerOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).6.1.0
compositeFilterQueryCompositeFilterConstraintThe filter to apply.6.1.0
queryConstraintsQueryNonFilterConstraint[]Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.6.1.0

RemoveSnapshotListenerOptions

PropTypeSince
callbackIdCallbackId5.2.0

Type Aliases

QueryFilterConstraint

QueryFieldFilterConstraint | QueryCompositeFilterConstraint

QueryOperator

'<' | '<=' | '==' | '>=' | '>' | '!=' | 'array-contains' | 'array-contains-any' | 'in' | 'not-in'

QueryNonFilterConstraint

QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint

OrderByDirection

'desc' | 'asc'

AddDocumentSnapshotListenerCallback

(event: AddDocumentSnapshotListenerCallbackEvent<T> | null, error: any): void

AddDocumentSnapshotListenerCallbackEvent

GetDocumentResult<T>

CallbackId

string

AddCollectionSnapshotListenerCallback

(event: AddCollectionSnapshotListenerCallbackEvent<T> | null, error: any): void

AddCollectionSnapshotListenerCallbackEvent

GetCollectionResult<T>

AddCollectionGroupSnapshotListenerCallback

(event: AddCollectionGroupSnapshotListenerCallbackEvent<T> | null, error: any): void

AddCollectionGroupSnapshotListenerCallbackEvent

GetCollectionGroupResult<T>

Changelog

See CHANGELOG.md.

License

See LICENSE.

^1: This project is not affiliated with, endorsed by, sponsored by, or approved by Google LLC or any of their affiliates or subsidiaries.