How to use @google-cloud/firestore - 10 common examples

To help you get started, we’ve selected a few @google-cloud/firestore examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ablehq / firestore-explorer / firebase-proxy / src / controllers / LocalHelper.ts View on Github external
import { LocalQuery } from "../models/Commands";
import { Firestore } from "@google-cloud/firestore";
const grpc = require("@grpc/grpc-js");
// Create a new client
const firestore = new Firestore({
  servicePath: "localhost",
  port: 8080,
  projectId: "firebase-explorer-test",
  sslCreds: grpc.credentials.createInsecure(),
  customHeaders: {
    Authorization: "Bearer owner"
  }
});

export const handleLocalQuery = async (query: LocalQuery) => {
  let data: { [key: string]: any } = {};
  const db = firestore;
  const result = await db.doc("movies/60756").get();
  const collections = await result.ref.listCollections();
  console.log(collections);
  data["success"] = true;
github GoogleCloudPlatform / nodejs-getting-started / bookshelf / books / firestore.js View on Github external
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// [START bookshelf_firestore_client]
const {Firestore} = require('@google-cloud/firestore');

const db = new Firestore();
const collection = 'Book';

// [END bookshelf_firestore_client]

// Lists all books in the database sorted alphabetically by title.
async function list(limit, token) {
  const snapshot = await db
    .collection(collection)
    .orderBy('title')
    .startAfter(token || '')
    .limit(limit)
    .get();

  if (snapshot.empty) {
    return {
      books: [],
github mozilla / fxa / packages / fxa-event-broker / bin / workerDev.ts View on Github external
const queueParts = Config.get('serviceNotificationQueueUrl').split('/');
    const queueName = queueParts[queueParts.length - 1];
    const sqs = new SQS();
    const queues = await sqs.listQueues().promise();

    if (!queues.QueueUrls || !queues.QueueUrls.includes(queueName)) {
      await sqs
        .createQueue({
          QueueName: queueName
        })
        .promise();
    }

    // Utilize the local firestore emulator if we were told to use it
    if (firestoreEnabled && NODE_ENV === 'development') {
      const fstore = new Firestore({
        customHeaders: {
          Authorization: 'Bearer owner'
        },
        port: 8006,
        projectId: 'fx-event-broker',
        servicePath: 'localhost',
        sslCreds: grpc.credentials.createInsecure()
      });
      db = new FirestoreDatastore(firestoreConfig, fstore);
    }
  } catch (err) {
    logger.error('Error loading application:', { err });
    process.exit(1);
  }

  const capabilityService = new ClientCapabilityService(
github kevlened / fireway / src / index.js View on Github external
proxyWritableMethods(dryrun, stats);

    if (!storageBucket && projectId) {
        storageBucket = `${projectId}.appspot.com`;
    }
    
    const providedApp = app;
    if (!app) {
        app = admin.initializeApp({
            projectId,
            storageBucket
        });
    }

    // Use Firestore directly so we can mock for dryruns
    const firestore = new Firestore({projectId});

    const collection = firestore.collection('fireway');

    // Get the latest migration
    const result = await collection
        .orderBy('installed_rank', 'desc')
        .limit(1)
        .get();
    const [latestDoc] = result.docs;
    const latest = latestDoc && latestDoc.data();

    if (latest && !latest.success) {
        throw new Error(`Migration to version ${latest.version} using ${latest.script} failed! Please restore backups and roll back database and code!`);
    }

    let installed_rank;
github googleapis / nodejs-firestore / samples / quickstart.js View on Github external
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// [START firestore_quickstart]
const {Firestore} = require('@google-cloud/firestore');

// Create a new client
const firestore = new Firestore();

async function quickstart() {
  // Obtain a document reference.
  const document = firestore.doc('posts/intro-to-firestore');

  // Enter new data into the document.
  await document.set({
    title: 'Welcome to Firestore',
    body: 'Hello World',
  });
  console.log('Entered new data into the document');

  // Update an existing document.
  await document.update({
    body: 'My first Firestore app',
  });
github firebase / extensions / firestore-counter / functions / lib / controller.js View on Github external
let [reshard, slices] = ShardedCounterController.balanceWorkers(shardingInfo);
                if (reshard) {
                    console.log("Resharding workers, new workers: " +
                        slices.length +
                        " prev num workers: " +
                        query.docs.length);
                    query.docs.forEach((snap) => t.delete(snap.ref));
                    slices.forEach((slice, index) => {
                        t.set(this.workersRef.doc(ShardedCounterController.encodeWorkerKey(index)), {
                            slice: slice,
                            timestamp: firestore_1.FieldValue.serverTimestamp(),
                        });
                    });
                    t.set(this.controllerDocRef, {
                        workers: slices,
                        timestamp: firestore_1.FieldValue.serverTimestamp(),
                    });
                }
                else {
                    // Check workers that haven't updated stats for over 90s - they most likely failed.
                    let failures = 0;
                    query.docs.forEach((snap) => {
                        if (timestamp / 1000 - snap.updateTime.seconds > 90) {
                            t.set(snap.ref, { timestamp: firestore_1.FieldValue.serverTimestamp() }, { merge: true });
                            failures++;
                        }
                    });
                    console.log("Detected " + failures + " failed workers.");
                    t.set(this.controllerDocRef, { timestamp: firestore_1.FieldValue.serverTimestamp() }, { merge: true });
                }
            }));
        });
github GoogleCloudPlatform / serverless-photosharing-workshop / functions / image-analysis / nodejs / index.js View on Github external
// determining if the picture is safe to show
        const safeSearch = response.safeSearchAnnotation;
        const isSafe = ["adult", "spoof", "medical", "violence", "racy"].every(k =>
            !['LIKELY', 'VERY_LIKELY'].includes(safeSearch[k]));
        console.log(`Safe? ${isSafe}`);

        // if the picture is safe to display, store it in Firestore
        if (isSafe) {
            const pictureStore = new Firestore().collection('pictures');

            const doc = pictureStore.doc(filename);
            await doc.set({
                labels: labels,
                color: colorHex,
                created: Firestore.Timestamp.now()
            }, {merge: true});

            console.log("Stored metadata in Firestore");
        }
    } else {
        throw new Error(`Vision API error: code ${response.error.code}, message: "${response.error.message}"`);
    }
};
github GoogleCloudPlatform / nodejs-getting-started / sessions / index.js View on Github external
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

const {Firestore} = require('@google-cloud/firestore');
const express = require('express');
const session = require('express-session');

const app = express();
const {FirestoreStore} = require('@google-cloud/connect-firestore');

app.use(
  session({
    store: new FirestoreStore({
      dataset: new Firestore({
        kind: 'express-sessions',
      }),
    }),
    secret: 'my-secret',
    resave: false,
    saveUninitialized: true,
  })
);

const greetings = [
  'Hello World',
  'Hallo Welt',
  'Ciao Mondo',
  'Salut le Monde',
  'Hola Mundo',
];
github mozilla / fxa / packages / fxa-event-broker / lib / db / firestore.ts View on Github external
constructor(config: FirestoreDbSettings, firestore?: Firestore) {
    this.prefix = config.prefix;
    if (firestore) {
      this.db = firestore;
    } else {
      // keyFilename takes precedence over credentials
      if (config.keyFilename) {
        delete config.credentials;
      }
      this.db = new Firestore(config);
    }
  }
github IanMitchell / aquarius / src / lib / database / index.js View on Github external
const database = (() => {
  log('Connecting to Firebase...');

  try {
    const firestore = new Firestore({
      projectId: process.env.FIREBASE_PROJECT,
      keyFilename: path.join(
        __dirname,
        `../../../${process.env.FIREBASE_KEYFILE}`
      ),
    });

    const methods = Object.create(null);

    // Inspired my Mongoist
    return new Proxy(firestore, {
      get: (obj, prop) => {
        const fbProp = obj[prop];

        // Cache, lazily
        if (typeof fbProp === 'function') {