Firebase transaction api call current data is null

后端 未结 3 742
时光说笑
时光说笑 2020-12-01 12:10

When I use transaction() to update a location, data at that location is returning null even though the location having some da

3条回答
  •  北海茫月
    2020-12-01 13:12

    Simply showing an example implementation to elaborate on @Kato accepted answer above with a custom upsert function:

      /**
       * Transactional insert or update record
       * @param  {String} type - object type (table or index) to build lookup path
       * @param  {String} id - object ID that will be concat with path for lookup
       * @param  {Object} data - new object (or partial with just edited fields)
       * @return {Object}       new version of object
       */
      const upsert = (type, id, data) => {
        return new Promise((resolve, reject) => {
          if (!type) {
            log.error('Missing db object type')
            reject(new TypeError('Missing db object type'))
          }
          if (!id) {
            log.error('Missing db object id')
            reject(new TypeError('Missing db object id'))
          }
          if (!data) {
            log.error('Missing db data')
            reject(new TypeError('Missing db data'))
          }
    
          // build path to resource
          const path = `${type}/${id}`
          log.debug(`Upserting record '${path}' to database`)
    
          try {
            const ref = service.ref(path)
            ref.transaction(record => {
              if (record === null) {
                log.debug(`Creating new record`) // TODO: change to debug
                return data
              } else if (record) {
                log.debug(`Updating existing record`) // TODO: change to debug
                const updatedRecord = Object.assign({}, record, data)
                return updatedRecord
              } else {
                return record
              }
            }, (error, committed, snapshot) => {
              if (error) {
                log.error(`Error upserting record in database`)
                log.error(error.message)
                reject(error)
              } else if (committed) {
                log.debug(`Saved update`)
              } else {
                log.debug(`Record unchanged`)
              }
    
              if (snapshot) {
                resolve(snapshot.val())
              } else {
                log.info(`No snapshot found in transaction so returning original data object`)
                resolve(data)
              }
            })
          } catch (error) {
            log.error(error)
            reject(error)
          }
        })
      }
    

提交回复
热议问题