Firebase Cloud功能onWrite触发多次触发

问题描述 投票:0回答:1

我正在我的网站上创建一个写入实时数据库的联系表单。使用云功能,我想通过向自己发送包含该联系人详细信息的电子邮件来响应数据库条目。

我已经确认我只发送一次有效载荷,数据被写入数据库完全正常。我遇到的问题是onWrite响应数据库的每一行输入,例如我发送姓名,电子邮件,公司和消息,因此,我的函数调用了4次。我不是要重写数据库,我知道这会执行另一次调用。每次调用都会收到一行数据作为单个值,我没有得到文档中“承诺”的所有值的对象。我也试过onCreate,甚至没有被调用。

我被误导了吗?这是预期的行为吗?任何帮助赞赏。

代码...

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendContactMessage = functions.database
  .ref('/messages/{pushKey}')
  .onWrite(event => {
    const snapshot = event.data;
    // Only send email for new messages.
    if (!snapshot.exists()) { return null; }

    const val = snapshot.val();

    console.log(val);
  });

我的班级发布到'消息'...

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
import * as firebase from 'firebase/app';

export interface Item { name: string; email: string; message: string; html: string; date: string }

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.scss']
})
export class ContactComponent {
      public rForm: FormGroup;
      public post: any;
      public message: string = '';
      public name: string = '';
      public company: string = '';
      public email: string = '';
      itemRef: AngularFireObject<any[]>;
      item;

  constructor(private fb: FormBuilder, public db: AngularFireDatabase) {
    this.createForm();
    this.itemRef = db.object('messages');
    this.item = this.itemRef.valueChanges();
  }

  createForm() {
    this.rForm = this.fb.group({
      name: [null, Validators.required],
      email: [null, Validators.compose([Validators.required, Validators.email])],
      message: [null, Validators.compose([Validators.required, Validators.minLength(15)])],
      validate: ''
    });
  }

  sendMessage(post) {

    this.name = post.name;
    this.email = post.email;
    this.message = post.message;

    const item: Item = {
      name: post.name,
      email: post.email,
      message: post.message,
      html: `You were contacted from your website by ${post.name}. They said "${post.message}". You can contact them back on ${post.email}`,
      date: Date()
    };

    this.itemRef.update(item);
  }
}
angular firebase google-cloud-functions nodemailer firebase-cloud-functions
1个回答
0
投票

我怀疑任何人都像我一样愚蠢,但我正在写我的数据库中的同一个位置。只有一个条目存在,所以我'更改'4项数据,因此我会触发4个onWrite事件。

我通过在唯一文件夹下的数据库中创建一个新条目来解决这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.