Par*_*roi 7 javascript node.js firebase firebase-realtime-database google-cloud-functions
我已经坚持了几个月。我从函数中删除了一些次要细节,但没有什么大不了的。我有这个https云函数,该函数结束会话,然后使用endTime和startTime计算bill返回到客户端的值。
startTime 从实时Firebase数据库(会话启动程序函数放在那里)中检索。
我的代码段:
exports.endSession = functions.https.onRequest(async (req, res) => {
console.log("endSession() called.")
if(req.method == 'GET'){
bid = req.query.bid
session_cost = req.query.sessioncost
}else{
bid = req.body.bid
session_cost = req.body.sessioncost
}
start_time_ref = admin.database().ref("/online_sessions/").child(bid).child("start_time")
start_time_snapshot = await start_time_ref.once('value')
console.log("start_time_snapshot: "+start_time_snapshot.val())
start_time_snapshot = moment(start_time_snapshot.val(), 'dddd MMMM Do YYYY HH:mm:ss Z');
endDateTime = getDateTime()
console.log("startTime: " + start_time_snapshot.toString())
console.log("endTime: " + endDateTime.toString())
hour_difference = getHourDifference(start_time_snapshot, endDateTime)
bill = ride_cost * Math.ceil(hour_difference)
console.log("bill: "+bill)
var s_phone
sSessionlinks_ref = admin.database().ref('/sSessionlinks/')
sSessionlinks_snapshot = await sSessionlinks_ref.once('value')
sSessionlinks_snapshot.forEach((sid)=>{
if(sid.val() == bid){
s_phone = sid.key
}
})
s_fcm_token_ref = admin.database().ref("/s/").child(s_phone).child("FCM")
s_fcm_token_snapshot = await s_fcm_token_ref.once('value')
try{ // telling another client that session has ended.
await admin.messaging().send({
data: {
type: "sessionCompleted",
bill: bill.toString()
},
token: s_fcm_token_snapshot.val()
})
}catch(error){
}
//deleting this session from online sessions
online_session_ref = admin.database().ref('/online_sessions/').child(bid)
await online_session_ref.remove()
//puting this session as available
available_session_ref = admin.database().ref('/available_sessions/')
json = {}
json[bid] = s_phone
await available_session_ref.update(json) // session made available
res.status(200).send(bill.toString())
// here it *sometimes* returns 304 and then restarts but since i've already removed online_session_ref I cannot get startTime again because its removed with online_sessions so it fails.
// return
})
Run Code Online (Sandbox Code Playgroud)
第一次调用时。它正确地执行了所有计算,但响应为304。因此(我认为客户端)重新发送了请求,并再次调用了该函数,但是由于session被破坏了,因此它无法计算startTime。
为什么在首次调用时,即使所有计算正确进行,也返回304而不是200?这个问题不会一直发生。通常会在很长一段时间后调用此函数,但是我不确定。我不知道是什么原因造成的。
我使用过的辅助函数:
function getHourDifference(s, e){
return moment.duration(e.diff(s)).asHours()
}
function getDateTime(){
d = moment.utc().utcOffset('+0530')
return d
}
Run Code Online (Sandbox Code Playgroud)
当函数第一次结束时,文本有效载荷为 Function execution took 794 ms, finished with status code 304
当它第二次运行时(无法得到startTime原因,导致其在第一次运行中被删除。首先不应进行第二次运行。),有效载荷文本为Function execution took 234 ms, finished with status code 200(其值为200,但返回,NaN因为没有则无法进行计算startTime。
编辑:正如你们中的一些人问我要告诉函数如何被调用:
它是使用Volley从android应用程序调用的。确保参数不为空。调用该函数的代码段是:
// Setting the button's listeners.
endSessionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressDialog = new SweetAlertDialog(getContext(), SweetAlertDialog.PROGRESS_TYPE);
progressDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
progressDialog.setTitleText("Ending session...");
AlertDialog endDialog = new AlertDialog.Builder(getContext()).create();
endDialog.setTitle("End Session?");
Log.e("sessioncost", String.valueOf(session_cost));
endDialog.setButton(Dialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
progressDialog.show();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getContext());
String url = "https://us-central1-something-something.cloudfunctions.net/endSession?bid=" + bid + "&sessioncost=" + session_cost;
Log.e("end sesion button", url);
// Request a string response from the provided URL.
StringRequest endSessionRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(final String response) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Session Completed", Toast.LENGTH_LONG).show();
progressDialog = new SweetAlertDialog(getContext(), SweetAlertDialog.SUCCESS_TYPE);
progressDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
progressDialog.setTitleText("Session Completed: Bill");
progressDialog.setContentText("Please pay ?" + response + " to s.");
progressDialog.setCancelable(false);
progressDialog.show();
changeState('1');
bill_in_paise = Float.parseFloat(response) * 100;
Log.e("bill", bill_in_paise.toString());
progressDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismiss();
Intent intent = new Intent(getContext(), PaymentActivity.class);
intent.putExtra("amt", bill_in_paise.toString());
startActivityForResult(intent, REQUEST_CODE);
}
});
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
}// onErrorResnponse - END
});
// Add the request to the RequestQueue. Cuz volley is asyc af.
queue.add(endSessionRequest);
// VOLLEY REQUEST - END
}
});
endDialog.setButton(Dialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Session not cancelled. " + which, Toast.LENGTH_LONG).show();
}
});
endDialog.show();
}
}
}); // endSessionButton onclick - end
Run Code Online (Sandbox Code Playgroud)
更新:@tuledev通过解决方法帮助修复了304,但是问题仍然存在。即使状态码为200,仍然以某种方式再次调用了云功能,但我得到了一张NaN帐单。在这一点上,我不知道是什么原因造成的。
该304状态出现是因为响应与之前相同。Firebase云响应304并且客户端将获取缓存的数据。
为了防止出现状态,我们可以返回账单的304值+ ,或者使响应与之前的响应不同。uid
正如OP和我讨论的那样,问题304已经解决,但问题仍然存在。所以我认为问题出在客户端。
希望有人可以帮助他。
编辑:OP 这里,我将客户端代码更改为使用 okhttp 而不是 volley,经过 2 天的测试后一切似乎都很好。图莱德夫的答案确实解决了304,但即使200问题仍然存在。只需使用 okhttp 而不是 volley 即可。
| 归档时间: |
|
| 查看次数: |
473 次 |
| 最近记录: |