【发布时间】:2021-03-26 18:07:57
【问题描述】:
我在 TypeScript + Express 服务器中使用 Firebase 实时数据库 SDK 来创建 Rest API 后端。我有一个 React 前端,它使用 axios 从 API 端点获取数据。但是,每当我必须迭代子属性时,我也会感到头疼。
所以我创建了一个非常糟糕的代码来将这些 Firebase snapshots 转换为友好(或我认为是友好的)可读和可迭代的对象。
这是代码:
const form = snapshot.val();
form.id = snapshot.key;
form.steps = Object.keys(form.steps).map(stepKey => {
form.steps[stepKey].id = stepKey;
form.steps[stepKey].inputs = Object.keys(form.steps[stepKey].inputs).map(inputKey => {
form.steps[stepKey].inputs[inputKey].id = inputKey;
if (form.steps[stepKey].inputs[inputKey].conditions) {
form.steps[stepKey].inputs[inputKey].conditions = Object.keys(form.steps[stepKey].inputs[inputKey].conditions).map(conditionKey => {
form.steps[stepKey].inputs[inputKey].conditions[conditionKey].id = conditionKey;
return form.steps[stepKey].inputs[inputKey].conditions[conditionKey];
});
}
return form.steps[stepKey].inputs[inputKey];
});
return form.steps[stepKey];
});
result.data = form as Form;
我知道这很糟糕,但现在我得到了(再次,我认为它是)一个可读的对象,其中包含要迭代的子数组内容,而且我可以想到一种方法来制作一个动态执行此操作的函数。
"data": {
"author": "my@email.com",
"created": "2020-12-14T00:04:57.205Z",
"description": "test form",
"steps": [
{
"description": "test step",
"inputs": [
{
"helper": "",
"inputId": "-MNpzudIoPnBezm4D9sG",
"label": "input 1",
"id": "-MOTZ7FOiffGLTKXPgyG"
}
],
"position": 1,
"title": "First Step",
"id": "-MOTZ7FPzQaJ94NrZtAP"
}
],
"title": "A Test Form",
"id": "-MOTZ7FQ0v-tCs_sEAe2"
}
代替原来的内容(snapshot.val()):
"data": {
"author": "my@email.com",
"created": "2020-12-14T00:04:57.205Z",
"description": "test form",
"steps": {
"-MOTZ7FPzQaJ94NrZtAP": {
"description": "test step",
"inputs": {
"-MOTZ7FOiffGLTKXPgyG": {
"helper": "",
"inputId": "-MNpzudIoPnBezm4D9sG",
"label": "input 1"
}
},
"position": 1,
"title": "First Step"
}
},
"title": "A Testing Form"
}
所以我正在考虑一个递归函数,它将用snapshot.forEach() 迭代snapshot,并且每次hasChildren() 将snapshot.key 附加为id,然后可能返回snapshot.val()。但我对“重新发明轮子”并不是很感兴趣。
上面的错误代码是解决我的问题还是我应该尝试不同的解决方案?
【问题讨论】:
标签: node.js typescript firebase express firebase-realtime-database