几个月来我一直坚持这个。我从函数中删除了一些次要细节,但没有什么大不了的。我有这个 https 云函数,可以结束 session ,然后使用 endTime 和 startTime 计算 bill,然后将其返回给客户端。
startTime 从实时 firebase 数据库( session 启动函数放在那里)中获取。
我的代码片段:
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
})
第一次调用时。它正确地进行了所有计算,但以 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
}
当函数第一次结束时,文本有效载荷是函数执行耗时 794 毫秒,完成状态代码 304
当它第二次运行时(它无法获取 startTime 因为它在第一次运行时被删除了。首先不应该有第二次运行。),有效负载文本是 函数执行耗时 234 毫秒,完成时状态代码为 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
更新:@tuledev 通过变通方法帮助修复了 304,但问题仍然存在。即使状态代码为 200,云函数也会以某种方式再次调用,我收到了 NaN 账单。目前我不知道是什么原因造成的。
最佳答案
304状态是因为响应和前面一样。 Firebase 云响应 304,客户端将获取缓存数据。
为了防止304状态,我们可以返回账单的值+uid,或者让响应与之前的不同。
正如 OP 和我讨论的那样,304 已解决,但问题仍然存在。所以我认为问题出在客户端。
希望有人能帮助他。
编辑:OP 在这里,我将客户端代码更改为使用 okhttp 而不是 volley,经过 2 天的测试,一切似乎都很好。 Tuledev 的回答确实修复了 304 但即使在 200 之后问题仍然存在。只需使用 okhttp 而不是 volley。
关于javascript - Firebase云函数返回304错误然后重启,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55068764/
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我有一个奇怪的问题:我在rvm上安装了rubyonrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案
我有这样的哈希trial_hash={"key1"=>1000,"key2"=>34,"key3"=>500,"key4"=>500,"key5"=>500,"key6"=>500}我按值降序排列:my_hash=trial_hash.sort_by{|k,v|v}.reverse我现在是这样理解的:[["key1",1000],["key4",500],["key5",500],["key6",500],["key3",500],["key2",34]]但我希望当值相同时按键的升序排序。我该怎么做?例如:上面的散列将以这种方式排序:[["key1",1000],["key3",500
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c