typescript管理REST调用和回调
我正在使用带有typescript的googlefirebase函数。我有一个关于更好的代码管理的基本问题。当前我的代码如下所示:typescript管理REST调用和回调,typescript,firebase,code-organization,Typescript,Firebase,Code Organization,我正在使用带有typescript的googlefirebase函数。我有一个关于更好的代码管理的基本问题。当前我的代码如下所示: export const on_command_ping = functions.database.ref("commands/ping/{id}").onWrite(async (change, context) => { if(instr == '/my-sr'){ const reoptions = { u
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
}
正如您在上面所看到的,这将很难在单个函数中管理所有内容。那么,如何组织这段代码,使每个rest调用都是基于if-else从上面调用的单独函数呢 您可以将代码放入函数的IF块中 例:
在你的代码
instr
中从来没有定义过。对不起,为了简短起见,我吃了一些与我的问题不相关的东西。
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
}