我正在将Google Firebase函数与打字稿一起使用。我有一个关于更好的代码管理的基本问题。目前,我的代码如下所示:
export const on_command_ping = functions.database.ref("commands/ping/{id}").onWrite(async (change, context) => {
if(instr == '/my-sr'){
const reoptions = {
uri: baseUrl + '/serviceRequests',
headers: {
'Authorization': "Basic " + btoa(username + ":" + password)
},
json:true
};
const result = await rp.get(reoptions)
.then(function(resp){
console.log("got the response dude:" + JSON.stringify(resp))
const options = {
uri: respUrl,
method: "POST",
json: true,
body: { "attachments": [{
"fallback": "Sorry failed to get response"}]
}
}
return rp(options);
}));
}else if(instr == '/my-oher-stuff'){
//another REST call
}
正如您在上面看到的那样,很难用一个功能来管理所有内容。因此,如何组织此代码,以便每个其余调用都是基于if-else从上面调用的单独函数。
答案 0 :(得分:1)
您可以将代码放在函数内的IF块内。
例如:
export const on_command_ping = functions.database.ref("commands/ping/{id}").onWrite(async (change, context) => {
if (instr == '/my-sr') {
return function1(change, context)
}
else if (instr == '/my-oher-stuff') {
return function2(change, context)
}
else {
return function3(change, context)
}
});
function function1(change, context) {
const reoptions = {
uri: baseUrl + '/serviceRequests',
headers: {
'Authorization': "Basic " + btoa(username + ":" + password)
},
json: true
};
const result = await
rp.get(reoptions)
.then(function (resp) {
console.log("got the response dude:" + JSON.stringify(resp))
const options = {
uri: respUrl,
method: "POST",
json: true,
body: {
"attachments": [{
"fallback": "Sorry failed to get response"
}]
}
}
return rp(options);
}));
}
function function2(change, context) {
//Some code here
}
function function3(change, context) {
//Some code here
}