通过 REST 将数组推送到 Firebase API

Pushing array to Firebase via REST API

问题

How do I (with a single HTTP request to the REST API) write an array to Firebase and give each array element a (non-integer) unique ID?

As described here.


数据

我要写的数据如下所示。

数据到write.js
myArray = [ {"user_id": "jack", "text": "Ahoy!"},
            {"user_id": "jill", "text": "Ohai!"} ];

目标

完成后,我希望我的 Firebase 如下所示。

我的-firebase.firebaseio.com
{
  "posts": {
    "-JRHTHaIs-jNPLXOQivY": { // <- unique ID (non-integer)
      "user_id": "jack",
      "text": "Ahoy!"
    },
    "-JRHTHaKuITFIhnj02kE": { // <- unique ID (non-integer)
      "user_id": "jill",
      "text": "Ohai!"
    }
  }
}

希望它看起来像下面这样...

我的反firebase.firebaseio.com
// NOT RECOMMENDED - use push() instead!
{
  "posts": {
    "0": {  // <- ordered array index (integer)
      "user_id": "jack",
      "text": "Ahoy!"
    },
    "1": {  // <- ordered array index (integer)
      "user_id": "jill",
      "text": "Ohai!"
    }
  }
}

I note this page where it says:

[...] if all of the keys are integers, and more than half of the keys between 0 and the maximum key in the object have non-empty values, then Firebase will render it as an array.

代码

因为我想在单个 HTTP 请求中执行此操作,所以我想避免迭代数组中的每个元素,而是想在单个请求中推送一个批处理。

换句话说,我想做这样的事情:

pseudocode.js
curl -X POST -d '[{"user_id": "jack", "text": "Ahoy!"},
                  {"user_id": "jill", "text": "Ohai!"}]' \
                  // I want some type of batch operation here
  'https://my-firebase.firebaseio.com/posts.json'

但是,当我这样做时,我得到的正是我上面描述的我不想要的(即顺序整数键)。

我想避免做这样的事情:

反pseudocode.js
for(i=0; i<=myArray.length; i++;){ // I want to avoid iterating over myArray
  curl -X POST -d '{"user_id": myArray[i]["user_id"],
                    "text": myArray[i]["text"]}' \
    'https://my-firebase.firebaseio.com/posts.json'
}

是否可以实现我所描述的?如果可以,怎么做?

我认为没有办法按照 OP 中的描述使用 Firebase API 来执行此操作。

但是,可以使用如下服务器脚本来完成:

  1. 遍历每个数组元素。
  2. 为每个元素分配一个唯一的 ID(由服务器脚本生成)。
  3. 创建一个 return 对象,键是唯一 ID,值是相应的数组元素。
  4. 使用 patch 方法通过单个 HTTP 请求将对象写入 Firebase。因为 post 为整个对象本身创建了一个新的 Firebase 生成的 ID。然而,patch 没有;它直接写入父节点。
script.js
var myObject = {},
i = myArray.length;
while(i--){
  var key = function(){ /* return unique ID */ }();
  myObject[key] = myArray[i];
}
curl -X PATCH -d JSON.stringify(myObject) \
'https://my-firebase.firebaseio.com/posts.json'

仅当您使用 POST 时,Firebase 才会生成唯一 ID。如果您使用 PATCH,则不会生成唯一 ID。

因此对于给定的情况,将需要使用一些服务器/客户端代码来迭代以将数据保存在 firebase 中。

伪代码:

For each array 
   curl -X POST -d 
       "user_id": "jack",
       "text": "Ahoy!" 
    'https://my-firebase.firebaseio.com/posts.json'
Next

您使用 POST 的决定是正确的。导致数字索引作为键的是因为您的有效负载是一个数组。每当你 post/put 和数组时,键总是索引。 Post 如果你想让服务器为你生成密钥,你的对象一个一个。