本文整理汇总了TypeScript中firebase-functions.firestore类的典型用法代码示例。如果您正苦于以下问题:TypeScript firestore类的具体用法?TypeScript firestore怎么用?TypeScript firestore使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了firestore类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: while
let nextUrl = meta.nextUrl
// Check if nextUrl is taken
let exists = (await db.collection('links').doc(nextUrl).get()).exists;
while (exists) {
// Incremement nextUrl until we find an open link
nextUrl = base62Encode(base62Decode(nextUrl) + 1);
exists = (await db.collection('links').doc(nextUrl).get()).exists;
}
// Update db with new nextUrl
await db.doc('meta/meta').update({nextUrl: nextUrl});
}
export const onLinkCreateIncrementNextUrl =
functions.firestore.document('links/{linkId}')
.onCreate(async (_snapshot, _context) => {
await updateNextUrl();
});
export const callableIncrementNextUrl =
functions.https.onCall(async (_data, _context) => {
await updateNextUrl();
})
// Increment the hit count for the given short link. If the hits field does not
// exist on the link, it is created. If a v1Hits field exists on the link
// (legacy hit count), then its value is added to the hits field and the v1Hits
// field is deleted.
// This function is NOT idempotent.
async function incrementHitCount(short: string) {
示例2: await
import * as admin from 'firebase-admin';
import { addDays, differenceInMilliseconds } from 'date-fns';
import * as functions from 'firebase-functions';
import { URL } from 'url';
import config from '../config';
import onesignalAxios from '../singleton/onesignalAxios';
import storageBucket from '../singleton/storageBucket';
const onChatMessageCreated = functions.firestore
.document('chats/{chatId}/messages/{messageId}')
.onCreate(async (change, context) => {
const chatMessageDoc = change;
const chatMessageDocData = change.data();
const chatMessageType = chatMessageDocData['type'];
const chatRef = chatMessageDoc.ref.parent.parent;
await chatRef.update({
lastChatMessage: chatMessageDoc.ref,
lastMessageCreatedAt: admin.firestore.FieldValue.serverTimestamp(),
});
const userDoc = await (chatMessageDocData['from'] as admin.firestore.DocumentReference).get();
const userId = userDoc.id;
const userData = userDoc.data();
const userName = userData['name'];
const userImageUrl = new URL(userData['imageUrl']);
let body = '';
if (chatMessageType == 'TEXT') {
示例3:
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
import config from '../config';
import onesignalAxios from '../singleton/onesignalAxios';
import firestore from '../singleton/firestore';
const onFriendshipDeleted = functions.firestore
.document('users/{userId}/friendships/{friendshipId}')
.onDelete(async (change, context) => {
const heroId = context.params.userId;
const heroRef = firestore.collection('users').doc(heroId);
const changeData = change.data();
const opponentRef = changeData['user'];
const chatRef = changeData['chat'];
if (!(opponentRef instanceof admin.firestore.DocumentReference)) {
console.warn('The operation has been suspended. Because data.user was supposed to be a reference.');
return;
}
if (!(chatRef instanceof admin.firestore.DocumentReference)) {
console.warn('The operation has been suspended. Because data.chat was supposed to be a reference.');
return;
}
const opponentFriendshipDocs = await opponentRef.collection('friendships').where('user', '==', heroRef).limit(1).get();
if (opponentFriendshipDocs.empty) {
console.warn('The operation has been suspended. Because the opponent doesn\'t have the friendship with the requester.');
示例4: countWords
const db = admin.firestore();
export async function countWords(dictionaryId): Promise<any> {
const dictionaryRef = db.doc(`dictionaries/${dictionaryId}`);
const queriedWordCount = await dictionaryRef.collection('words')
.get().then(snap => {
return snap.size;
})
return dictionaryRef.update({
wordCount: queriedWordCount
});
}
export const increaseWordCount = functions.firestore
.document('dictionaries/{dictionaryId}/words/{wordId}')
.onCreate(async (snapshot, context) => {
const dictionaryId = context.params.dictionaryId;
const dictionaryRef = db.doc(`dictionaries/${dictionaryId}`);
const dictionarySnap = await dictionaryRef.get();
const dictionaryData = dictionarySnap.data();
if (dictionaryData.wordCount) {
return dictionaryRef.update({
wordCount: dictionaryData.wordCount + 1
})
} else {
return countWords(dictionaryId);
}
示例5: parseInt
import * as functions from 'firebase-functions';
import { isEqual, reduce } from 'lodash'
/**
* Summerize the score treating X as 10.
*
* @param total
* @param shot
*/
const sumShots = (total: number, shot: any) => total + (typeof shot == 'string' && shot.toLowerCase() == 'x' ? 10 : parseInt(shot));
const sumScore = (results, value, key) => {
return results + value.score
}
export const roundCreated = functions.firestore
.document('sessions/{sessionId}/round/{roundId}')
.onCreate((snap, context) => {
const data = snap.data();
const score = data.shots.reduce(sumShots, 0)
const updateData = {scores : {}}
updateData.scores[snap.id] = { type: data.type, score: score }
return snap.ref.parent.parent.set(updateData, {merge: true})
});
export const calculateScore = functions.firestore
.document('sessions/{sessionId}')
.onUpdate((change, context) => {
const prev = change.before.data();
const next = change.after.data();
示例6: getProjectDocument
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { checkEventType } from './check-event-type';
const firestore = admin.firestore();
/**
* Appends project info when new documents are written to the `users/{userUid}/todos` collection with a project assigned to the document(s).
* Note that this affects documents which are created/deleted/updated.
*/
export const appendProjectMetadata = functions.firestore.document('users/{userUid}/todos/{todoUid}')
.onWrite((change, context) => {
const beforeDoc = change.before;
const afterDoc = change.after;
let projectDoc: admin.firestore.DocumentReference;
/**
* Retrieves the project document assigned to the todo document
* @param todoDoc The todo document to check
* @return A document reference, or null if the todo document doesn't exist
*/
function getProjectDocument(todoDoc: FirebaseFirestore.DocumentSnapshot): FirebaseFirestore.DocumentReference {
if (todoDoc.exists) {
if (typeof todoDoc.data()['project'] === 'string') {
// Using deprecated approach
return firestore.doc(`users/${context.params['userId']}/todoProjects/${todoDoc.data()['project']}`);
} else {
// The field is probably a document reference
return todoDoc.data()['project'] as FirebaseFirestore.DocumentReference;
}
} else {
示例7:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
exports.newVehicleNotification = functions.firestore
.document('notifications')
.onCreate(async event => {
const data = event.data();
const userId = data.userId;
const message = data.message;
const board = data.board;
//Notification content
const payload = {
notification: {
title: `Notificação: Placa ${board}`,
body: message,
icon: 'https://goo.gl/Fz9nrQ'
}
}
// ref to the parent document
const db = admin.firestore();
const devicesRef = db.collection('devices').where('userId', '==', userId);
//get users tokens and send notifications
const devices = await devicesRef.get();
示例8: notifyWatch
.collection('institutions')
.doc('uchicago')
.collection('grades')
.doc(key)
.set({
course: record['course'],
section: record['section'],
term: record['term'],
gpa: record['gpa'],
tenure: record['tenure'],
});
});
type Params = {
course: string;
term: string;
section: string;
};
const SECTION_PATH =
'institutions/uchicago/courses/{course}/terms/{term}/sections/{section}';
export const watches = functions.firestore
.document(SECTION_PATH)
.onWrite(event => {
notifyWatch(
event.params as Params,
event.data.previous.data(),
event.data.data(),
);
});
示例9: Error
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
import config from '../config';
import onesignalAxios from '../singleton/onesignalAxios';
const onChatCreated = functions.firestore
.document('chats/{chatId}')
.onCreate(async (change) => {
const chatDoc = change;
const chatDocData = chatDoc.data();
const userRefs: admin.firestore.DocumentReference[] = chatDocData['members'];
if (!Array.isArray(userRefs)) {
throw new Error();
}
if (userRefs.some((memberRef) => !(memberRef instanceof admin.firestore.DocumentReference))) {
throw new Error();
}
const tagsEachUserRef = new Map<admin.firestore.DocumentReference, string[]>();
const deviceDocsEachUserRef = new Map<admin.firestore.DocumentReference, admin.firestore.DocumentSnapshot[]>();
for (const userRef of userRefs) {
const otherUserRefs = userRefs.filter(ur => ur !== userRef);
tagsEachUserRef.set(userRef, otherUserRefs.map(otherUserRef => `chats/${chatDoc.id}?without=${otherUserRef.id}`));
}
await Promise.all(userRefs.map(async userRef => {
const deviceDocs = (await userRef.collection('devices').get()).docs;
示例10: require
'use strict';
import cbor = require('cbor');
import * as admin from "firebase-admin";
import * as functions from 'firebase-functions';
import { runInDebugContext } from 'vm';
import { DeviceManager } from './devices';
// create a device manager instance with a registry id, optionally pass a region
const dm = new DeviceManager('config-demo');
// start cloud function
exports.configUpdate = functions.firestore
// assumes a document whose ID is the same as the deviceid
.document('device-configs/{deviceId}')
.onWrite((change: functions.Change<admin.firestore.DocumentSnapshot>, context?: functions.EventContext) => {
if (context) {
console.log(context.params.deviceId);
// get the new config data
const configData = change.after.data();
return dm.updateConfig(context.params.deviceId, configData);
} else {
throw(Error("no context from trigger"));
}
})
exports.configUpdateBinary = functions.firestore