0

I use a Cloud Function to generate a short unique URL on a record on the 'onWrite' event, and save it. This works well, but when I save a record from my Ember app using EmberFire, I do get a model back as an argument to a callback, but the URL of this model is undefined. Is there a way to return this back to the client? Or do I need to query the record to get the generated URL?

This is how my Cloud Function code looks:

exports.generateUrl = functions.database.ref('/tournaments/{tid}')
  .onWrite(event => {
    if (event.data.previous.exists()) {
      return;
    }
    if (!event.data.exists()) {
      return;
    }

    const url = shortid.generate();

    return event.data.ref.update({ url });
  });

Here is my component that saves data through form submission. I'm using an add-on called ember-changeset to handle some validations, but this shouldn't be related to the issue.

export default Ember.Component.extend({

  submit(e) {
    e.preventDefault();

    let snapshot = this.changeset.snapshot();

    return this.changeset
      .cast(Object.keys(this.get('schema')))
      .validate()
      .then(() => {
        if (this.changeset.get('isValid')) {
          return this.changeset
            .save()
            .then((result) => {
                // Here, result.get('url') is undefined.
            })
        }
      })
  }
});
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
CookieEater
  • 2,237
  • 3
  • 29
  • 54

1 Answers1

0

If you have a function that writes new data back to a location in the database after a write, you'll have to keep listening to that location on the client in order to get that data back. Don't use a one-time read (once()), use a persistent listener (on()), and in that listener, make sure you're getting the URL or whatever you expect to be generated by the function. Then remove that listener if you don't need it any more.

(Sorry, I don't know Ember or what abstractions it provides around Realtime Database - I'm giving you the plain JavaScript API methods you'd use on a reference.)

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441