【发布时间】:2020-05-19 23:52:24
【问题描述】:
我正在编写一个使用现有 API 的 Laravel API。我需要自己的“中间人”API,因为它会在发送请求之前插入敏感数据,因为我不想在客户端存储敏感数据。
我可以很好地获取数据,但我希望能够使用路由参数来访问返回的 JSON 对象的各种“维度”。
目前,如果我导航到 /get/status,我会收到如下所示的响应。
{
"fuelAmount": 8,
"fuelAmountLevel": 11,
"tyrePressure": {
"frontLeftTyrePressure": "Normal",
"frontRightTyrePressure": "Normal",
"rearLeftTyrePressure": "Normal",
"rearRightTyrePressure": "Normal",
"timestamp": "2020-05-19T20:10:49+0000"
},
"heater": {
"seatSelection": {
"frontDriverSide": false,
"frontPassengerSide": false,
"rearDriverSide": false,
"rearPassengerSide": false,
"rearMid": false
},
"status": "off",
"timer1": {
"time": "17:30",
"state": false
},
"timer2": {
"time": "00:00",
"state": false
},
"timestamp": "2020-05-19T11:28:19+0000"
},
}
我想做的是导航到get/status/fuelAmount,然后只取回fuelAmount。所以我只会得到8 作为回应。目前我能够做到这一点,但我不确定如何以有效的方式在多个层面上做到这一点。因为获得fuelAmount只是一个“更深层次”,我也希望能够做到/get/status/heater/timer1/time并且只得到17:30作为响应。
目前的代码是这样的
public function vehicleGet($vMethod, $dataKey= null) {
$response = Http::withHeaders([
// bunch of headers needed to successfully request data
])
->withBasicAuth("user", config('app.mySecret'))
->get($this->url);
if(isset($dataKey)) {
return $response[$dataKey];
}else {
return $response->json();;
}
}
Laravel 中的路线
Route::get("get/{vMethod}/{dataKey?}", "DashController@vehicleGet")->where('dataKey', '.*');
所以就像我说的,如果我转到/get/status/heater,我成功地请求了第 3 方 API 的 status 端点,我只能打印出 heater 数据。
{
"seatSelection": {
"frontDriverSide": false,
"frontPassengerSide": false,
"rearDriverSide": false,
"rearPassengerSide": false,
"rearMid": false
},
"status": "off",
"timer1": {
" time": "17:30",
" state": false
},
"timer2": {
"time": "00:00",
"state": false
},
"timestamp": "2020-05-19T11:28:19+0000"
}
但如果我转到/get/status/heater/timer1/,我会得到Undefined index: heater/timer1,因为显然初始 JSON 对象中不存在该键。
因此,我将不得不根据 URL 中的 dataKey 参数以某种方式向此返回语句 return $response[$dataKey] 添加更多键。我可以分解该字符串并使用每个单独的键获得一个数组,但我仍然需要以某种方式将每个键添加到 return 语句中..
我可以在路由中添加更多参数而不是使用单个通配符参数,但是我需要为每个可选参数编写一堆 if 语句,检查它是否已设置,如果是,请将其用作显示 JSON 数据时的键?
【问题讨论】: