1 /*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "napi_util.h"
17
18 #include "securec.h"
19 #include "string_ex.h"
20
21 #include "country_code.h"
22 #include "common_utils.h"
23 #include "geo_address.h"
24 #include "location_log.h"
25 #include "locator_proxy.h"
26 #include "request_config.h"
27
28 namespace OHOS {
29 namespace Location {
30 static constexpr int MAX_BUF_LEN = 100;
31 static constexpr int MIN_WIFI_SCAN_TIME = 5000;
32 const uint32_t MAX_ADDITION_SIZE = 100;
33
UndefinedNapiValue(const napi_env & env)34 napi_value UndefinedNapiValue(const napi_env& env)
35 {
36 napi_value result;
37 NAPI_CALL(env, napi_get_undefined(env, &result));
38 return result;
39 }
40
SatelliteStatusToJs(const napi_env & env,const std::shared_ptr<SatelliteStatus> & statusInfo,napi_value & result)41 void SatelliteStatusToJs(const napi_env& env,
42 const std::shared_ptr<SatelliteStatus>& statusInfo, napi_value& result)
43 {
44 napi_value satelliteIdsArray;
45 napi_value cn0Array;
46 napi_value altitudesArray;
47 napi_value azimuthsArray;
48 napi_value carrierFrequenciesArray;
49 napi_value additionalInfoArray;
50 napi_value satelliteConstellationArray;
51 int svNum = statusInfo->GetSatellitesNumber();
52 SetValueDouble(env, "satellitesNumber", svNum, result);
53 if (svNum >= 0) {
54 NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, svNum, &satelliteIdsArray));
55 NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, svNum, &cn0Array));
56 NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, svNum, &altitudesArray));
57 NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, svNum, &azimuthsArray));
58 NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, svNum, &carrierFrequenciesArray));
59 NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, svNum, &satelliteConstellationArray));
60 NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, svNum, &additionalInfoArray));
61 uint32_t idx1 = 0;
62 for (int index = 0; index < svNum; index++) {
63 napi_value value = nullptr;
64 NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, statusInfo->GetSatelliteIds()[index], &value));
65 NAPI_CALL_RETURN_VOID(env, napi_set_element(env, satelliteIdsArray, idx1, value));
66 NAPI_CALL_RETURN_VOID(env,
67 napi_create_double(env, statusInfo->GetCarrierToNoiseDensitys()[index], &value));
68 NAPI_CALL_RETURN_VOID(env, napi_set_element(env, cn0Array, idx1, value));
69 NAPI_CALL_RETURN_VOID(env, napi_create_double(env, statusInfo->GetAltitudes()[index], &value));
70 NAPI_CALL_RETURN_VOID(env, napi_set_element(env, altitudesArray, idx1, value));
71 NAPI_CALL_RETURN_VOID(env, napi_create_double(env, statusInfo->GetAzimuths()[index], &value));
72 NAPI_CALL_RETURN_VOID(env, napi_set_element(env, azimuthsArray, idx1, value));
73 NAPI_CALL_RETURN_VOID(env, napi_create_double(env, statusInfo->GetCarrierFrequencies()[index], &value));
74 NAPI_CALL_RETURN_VOID(env, napi_set_element(env, carrierFrequenciesArray, idx1, value));
75 NAPI_CALL_RETURN_VOID(env,
76 napi_create_int32(env, statusInfo->GetSatelliteAdditionalInfoList()[index], &value));
77 NAPI_CALL_RETURN_VOID(env, napi_set_element(env, additionalInfoArray, idx1, value));
78 NAPI_CALL_RETURN_VOID(env,
79 napi_create_int32(env, statusInfo->GetConstellationTypes()[index], &value));
80 NAPI_CALL_RETURN_VOID(env, napi_set_element(env, satelliteConstellationArray, idx1, value));
81 idx1++;
82 }
83 SetValueStringArray(env, "satelliteIds", satelliteIdsArray, result);
84 SetValueStringArray(env, "carrierToNoiseDensitys", cn0Array, result);
85 SetValueStringArray(env, "altitudes", altitudesArray, result);
86 SetValueStringArray(env, "azimuths", azimuthsArray, result);
87 SetValueStringArray(env, "carrierFrequencies", carrierFrequenciesArray, result);
88 SetValueStringArray(env, "satelliteConstellation", satelliteConstellationArray, result);
89 SetValueStringArray(env, "satelliteAdditionalInfo", additionalInfoArray, result);
90 }
91 }
92
LocationsToJs(const napi_env & env,const std::vector<std::unique_ptr<Location>> & locations,napi_value & result)93 void LocationsToJs(const napi_env& env, const std::vector<std::unique_ptr<Location>>& locations, napi_value& result)
94 {
95 if (locations.size() > 0) {
96 for (unsigned int index = 0; index < locations.size(); index++) {
97 napi_value value;
98 LocationToJs(env, locations[index], value);
99 NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, value));
100 }
101 }
102 }
103
LocationToJs(const napi_env & env,const std::unique_ptr<Location> & locationInfo,napi_value & result)104 void LocationToJs(const napi_env& env, const std::unique_ptr<Location>& locationInfo, napi_value& result)
105 {
106 SetValueDouble(env, "latitude", locationInfo->GetLatitude(), result);
107 SetValueDouble(env, "longitude", locationInfo->GetLongitude(), result);
108 SetValueDouble(env, "altitude", locationInfo->GetAltitude(), result);
109 SetValueDouble(env, "accuracy", locationInfo->GetAccuracy(), result);
110 SetValueDouble(env, "speed", locationInfo->GetSpeed(), result);
111 SetValueInt64(env, "timeStamp", locationInfo->GetTimeStamp(), result);
112 SetValueDouble(env, "direction", locationInfo->GetDirection(), result);
113 SetValueInt64(env, "timeSinceBoot", locationInfo->GetTimeSinceBoot(), result);
114 napi_value additionArray;
115 uint32_t additionSize = static_cast<uint32_t>(locationInfo->GetAdditionSize());
116 additionSize = additionSize > MAX_ADDITION_SIZE ? MAX_ADDITION_SIZE : additionSize;
117 std::vector<std::string> additions = locationInfo->GetAdditions();
118 SetValueInt64(env, "additionSize", additionSize, result);
119 NAPI_CALL_RETURN_VOID(env,
120 napi_create_array_with_length(env, additionSize, &additionArray));
121 for (uint32_t index = 0; index < std::min(additionSize, static_cast<uint32_t>(additions.size())); index++) {
122 napi_value value;
123 NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, additions[index].c_str(),
124 NAPI_AUTO_LENGTH, &value));
125 NAPI_CALL_RETURN_VOID(env, napi_set_element(env, additionArray, index, value));
126 }
127 SetValueStringArray(env, "additions", additionArray, result);
128 if (locationInfo->GetIsSystemApp() != 0) {
129 SetValueBool(env, "isFromMock", locationInfo->GetIsFromMock(), result);
130 }
131 napi_value additionMap = CreateJsMap(env, locationInfo->GetAdditionsMap());
132 SetValueStringMap(env, "additionsMap", additionMap, result);
133 SetValueDouble(env, "altitudeAccuracy", locationInfo->GetAltitudeAccuracy(), result);
134 SetValueDouble(env, "speedAccuracy", locationInfo->GetSpeedAccuracy(), result);
135 SetValueDouble(env, "directionAccuracy", locationInfo->GetDirectionAccuracy(), result);
136 SetValueInt64(env, "uncertaintyOfTimeSinceBoot", locationInfo->GetUncertaintyOfTimeSinceBoot(), result);
137 SetValueInt32(env, "sourceType", locationInfo->GetLocationSourceType(), result);
138 napi_value poiJsObj = CreatePoiInfoJsObj(env, locationInfo->GetPoiInfo());
139 SetValuePoi(env, "poi", poiJsObj, result);
140 }
141
BluetoothScanResultToJs(const napi_env & env,const std::unique_ptr<BluetoothScanResult> & bluetoothScanResult,napi_value & result)142 void BluetoothScanResultToJs(const napi_env& env, const std::unique_ptr<BluetoothScanResult>& bluetoothScanResult,
143 napi_value& result)
144 {
145 SetValueUtf8String(env, "deviceId", bluetoothScanResult->GetDeviceId().c_str(), result);
146 SetValueUtf8String(env, "deviceName", bluetoothScanResult->GetDeviceName().c_str(), result);
147 SetValueInt64(env, "rssi", bluetoothScanResult->GetRssi(), result);
148 SetValueBool(env, "connectable", bluetoothScanResult->GetConnectable(), result);
149 SetValueArrayBuffer(env, "data", bluetoothScanResult->GetData(), result);
150 }
151
PoiToJs(const napi_env & env,const std::unique_ptr<Location> & locationInfo,napi_value & result)152 void PoiToJs(const napi_env& env, const std::unique_ptr<Location>& locationInfo, napi_value& result)
153 {
154 napi_value poiJsObj = CreatePoiInfoJsObj(env, locationInfo->GetPoiInfo());
155 result = poiJsObj;
156 }
157
CreatePoiInfoJsObj(const napi_env & env,const PoiInfo & poiInfo)158 napi_value CreatePoiInfoJsObj(const napi_env& env, const PoiInfo& poiInfo)
159 {
160 napi_value jsObject = nullptr;
161 if (poiInfo.poiArray.size() == 0) {
162 napi_get_undefined(env, &jsObject);
163 return jsObject;
164 }
165 NAPI_CALL(env, napi_create_object(env, &jsObject));
166 napi_value jsArray = nullptr;
167 NAPI_CALL(env, napi_create_array(env, &jsArray));
168 size_t index = 0;
169 for (auto poi : poiInfo.poiArray) {
170 napi_value jsPoiObject = nullptr;
171 NAPI_CALL(env, napi_create_object(env, &jsPoiObject));
172 napi_value jsValue = nullptr;
173
174 NAPI_CALL(env, napi_create_string_utf8(env, poi.id.c_str(), NAPI_AUTO_LENGTH, &jsValue));
175 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "id", jsValue));
176 NAPI_CALL(env, napi_create_double(env, poi.confidence, &jsValue));
177 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "confidence", jsValue));
178 NAPI_CALL(env, napi_create_string_utf8(env, poi.name.c_str(), NAPI_AUTO_LENGTH, &jsValue));
179 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "name", jsValue));
180 NAPI_CALL(env, napi_create_double(env, poi.latitude, &jsValue));
181 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "latitude", jsValue));
182 NAPI_CALL(env, napi_create_double(env, poi.longitude, &jsValue));
183 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "longitude", jsValue));
184 NAPI_CALL(env, napi_create_string_utf8(env, poi.administrativeArea.c_str(), NAPI_AUTO_LENGTH, &jsValue));
185 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "administrativeArea", jsValue));
186 NAPI_CALL(env, napi_create_string_utf8(env, poi.subAdministrativeArea.c_str(), NAPI_AUTO_LENGTH, &jsValue));
187 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "subAdministrativeArea", jsValue));
188 NAPI_CALL(env, napi_create_string_utf8(env, poi.locality.c_str(), NAPI_AUTO_LENGTH, &jsValue));
189 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "locality", jsValue));
190 NAPI_CALL(env, napi_create_string_utf8(env, poi.subLocality.c_str(), NAPI_AUTO_LENGTH, &jsValue));
191 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "subLocality", jsValue));
192 NAPI_CALL(env, napi_create_string_utf8(env, poi.address.c_str(), NAPI_AUTO_LENGTH, &jsValue));
193 NAPI_CALL(env, napi_set_named_property(env, jsPoiObject, "address", jsValue));
194
195 napi_value jsIndex = nullptr;
196 NAPI_CALL(env, napi_create_uint32(env, index, &jsIndex));
197 NAPI_CALL(env, napi_set_property(env, jsArray, jsIndex, jsPoiObject));
198
199 index++;
200 }
201 NAPI_CALL(env, napi_set_named_property(env, jsObject, "poiArray", jsArray));
202 napi_value jsTimestamp = nullptr;
203 NAPI_CALL(env, napi_create_int64(env, poiInfo.timestamp, &jsTimestamp));
204 NAPI_CALL(env, napi_set_named_property(env, jsObject, "timestamp", jsTimestamp));
205 return jsObject;
206 }
207
SetUndefinedResult(const napi_env & env,napi_value & result)208 void SetUndefinedResult(const napi_env& env, napi_value& result)
209 {
210 napi_get_undefined(env, &result);
211 }
212
CreateJsMap(napi_env env,const std::map<std::string,std::string> & additionsMap)213 napi_value CreateJsMap(napi_env env, const std::map<std::string, std::string>& additionsMap)
214 {
215 napi_value global = nullptr;
216 napi_value mapFunc = nullptr;
217 napi_value map = nullptr;
218 NAPI_CALL(env, napi_get_global(env, &global));
219 NAPI_CALL(env, napi_get_named_property(env, global, "Map", &mapFunc));
220 NAPI_CALL(env, napi_new_instance(env, mapFunc, 0, nullptr, &map));
221 napi_value setFunc = nullptr;
222 NAPI_CALL(env, napi_get_named_property(env, map, "set", &setFunc));
223 for (auto iter : additionsMap) {
224 napi_value key = nullptr;
225 napi_value value = nullptr;
226 NAPI_CALL(env, napi_create_string_utf8(env, iter.first.c_str(), NAPI_AUTO_LENGTH, &key));
227 NAPI_CALL(env, napi_create_string_utf8(env, iter.second.c_str(), NAPI_AUTO_LENGTH, &value));
228 napi_value setArgs[] = { key, value };
229 NAPI_CALL(env, napi_call_function(env, map, setFunc, sizeof(setArgs) / sizeof(setArgs[0]), setArgs, nullptr));
230 }
231 return map;
232 }
233
CountryCodeToJs(const napi_env & env,const std::shared_ptr<CountryCode> & country,napi_value & result)234 void CountryCodeToJs(const napi_env& env, const std::shared_ptr<CountryCode>& country, napi_value& result)
235 {
236 SetValueUtf8String(env, "country", country->GetCountryCodeStr().c_str(), result);
237 SetValueInt64(env, "type", country->GetCountryCodeType(), result);
238 }
239
SystemLocationToJs(const napi_env & env,const std::unique_ptr<Location> & locationInfo,napi_value & result)240 void SystemLocationToJs(const napi_env& env, const std::unique_ptr<Location>& locationInfo, napi_value& result)
241 {
242 SetValueDouble(env, "longitude", locationInfo->GetLongitude(), result);
243 SetValueDouble(env, "latitude", locationInfo->GetLatitude(), result);
244 SetValueDouble(env, "altitude", locationInfo->GetAltitude(), result);
245 SetValueDouble(env, "accuracy", locationInfo->GetAccuracy(), result);
246 SetValueInt64(env, "time", locationInfo->GetTimeStamp(), result);
247 }
248
GeoAddressesToJsObj(const napi_env & env,std::list<std::shared_ptr<GeoAddress>> & replyList,napi_value & arrayResult)249 bool GeoAddressesToJsObj(const napi_env& env,
250 std::list<std::shared_ptr<GeoAddress>>& replyList, napi_value& arrayResult)
251 {
252 uint32_t idx = 0;
253 for (auto iter = replyList.begin(); iter != replyList.end(); ++iter) {
254 auto geoAddress = *iter;
255 napi_value eachObj;
256 NAPI_CALL_BASE(env, napi_create_object(env, &eachObj), false);
257 SetValueDouble(env, "latitude", geoAddress->GetLatitude(), eachObj);
258 SetValueDouble(env, "longitude", geoAddress->GetLongitude(), eachObj);
259 SetValueUtf8String(env, "locale", geoAddress->locale_.c_str(), eachObj);
260 SetValueUtf8String(env, "placeName", geoAddress->placeName_.c_str(), eachObj);
261 SetValueUtf8String(env, "countryCode", geoAddress->countryCode_.c_str(), eachObj);
262 SetValueUtf8String(env, "countryName", geoAddress->countryName_.c_str(), eachObj);
263 SetValueUtf8String(env, "administrativeArea", geoAddress->administrativeArea_.c_str(), eachObj);
264 SetValueUtf8String(env, "subAdministrativeArea", geoAddress->subAdministrativeArea_.c_str(), eachObj);
265 SetValueUtf8String(env, "locality", geoAddress->locality_.c_str(), eachObj);
266 SetValueUtf8String(env, "subLocality", geoAddress->subLocality_.c_str(), eachObj);
267 SetValueUtf8String(env, "roadName", geoAddress->roadName_.c_str(), eachObj);
268 SetValueUtf8String(env, "subRoadName", geoAddress->subRoadName_.c_str(), eachObj);
269 SetValueUtf8String(env, "premises", geoAddress->premises_.c_str(), eachObj);
270 SetValueUtf8String(env, "postalCode", geoAddress->postalCode_.c_str(), eachObj);
271 SetValueUtf8String(env, "phoneNumber", geoAddress->phoneNumber_.c_str(), eachObj);
272 SetValueUtf8String(env, "addressUrl", geoAddress->addressUrl_.c_str(), eachObj);
273 napi_value descriptionArray;
274 if (geoAddress->descriptionsSize_ > 0) {
275 NAPI_CALL_BASE(env,
276 napi_create_array_with_length(env, geoAddress->descriptionsSize_, &descriptionArray), false);
277 uint32_t idx1 = 0;
278 for (int index = 0; index < geoAddress->descriptionsSize_; index++) {
279 napi_value value;
280 NAPI_CALL_BASE(env, napi_create_string_utf8(env, geoAddress->GetDescriptions(index).c_str(),
281 NAPI_AUTO_LENGTH, &value), false);
282 NAPI_CALL_BASE(env, napi_set_element(env, descriptionArray, idx1++, value), false);
283 }
284 SetValueStringArray(env, "descriptions", descriptionArray, eachObj);
285 }
286 SetValueInt32(env, "descriptionsSize", geoAddress->descriptionsSize_, eachObj);
287 if (geoAddress->GetIsSystemApp()) {
288 SetValueBool(env, "isFromMock", geoAddress->isFromMock_, eachObj);
289 }
290 NAPI_CALL_BASE(env, napi_set_element(env, arrayResult, idx++, eachObj), false);
291 }
292 return true;
293 }
294
LocatingRequiredDataToJsObj(const napi_env & env,std::vector<std::shared_ptr<LocatingRequiredData>> & replyList,napi_value & arrayResult)295 bool LocatingRequiredDataToJsObj(const napi_env& env,
296 std::vector<std::shared_ptr<LocatingRequiredData>>& replyList, napi_value& arrayResult)
297 {
298 uint32_t idx = 0;
299 for (size_t i = 0; i < replyList.size(); i++) {
300 napi_value eachObj;
301 NAPI_CALL_BASE(env, napi_create_object(env, &eachObj), false);
302 napi_value wifiObj;
303 NAPI_CALL_BASE(env, napi_create_object(env, &wifiObj), false);
304 SetValueUtf8String(env, "ssid", replyList[i]->GetWifiScanInfo()->GetSsid().c_str(), wifiObj);
305 SetValueUtf8String(env, "bssid", replyList[i]->GetWifiScanInfo()->GetBssid().c_str(), wifiObj);
306 SetValueInt32(env, "rssi", replyList[i]->GetWifiScanInfo()->GetRssi(), wifiObj);
307 SetValueInt32(env, "frequency", replyList[i]->GetWifiScanInfo()->GetFrequency(), wifiObj);
308 SetValueInt64(env, "timestamp", replyList[i]->GetWifiScanInfo()->GetTimestamp(), wifiObj);
309
310 napi_value blueToothObj;
311 NAPI_CALL_BASE(env, napi_create_object(env, &blueToothObj), false);
312 SetValueUtf8String(env, "deviceName",
313 replyList[i]->GetBluetoothScanInfo()->GetDeviceName().c_str(), blueToothObj);
314 SetValueUtf8String(env, "macAddress", replyList[i]->GetBluetoothScanInfo()->GetMac().c_str(), blueToothObj);
315 SetValueInt64(env, "rssi", replyList[i]->GetBluetoothScanInfo()->GetRssi(), blueToothObj);
316 SetValueInt64(env, "timestamp", replyList[i]->GetBluetoothScanInfo()->GetTimeStamp(), blueToothObj);
317
318 NAPI_CALL_BASE(env, napi_set_named_property(env, eachObj, "wifiData", wifiObj), false);
319 NAPI_CALL_BASE(env, napi_set_named_property(env, eachObj, "bluetoothData", blueToothObj), false);
320 napi_status status = napi_set_element(env, arrayResult, idx++, eachObj);
321 if (status != napi_ok) {
322 LBSLOGE(LOCATING_DATA_CALLBACK, "set element error: %{public}d, idx: %{public}d", status, idx - 1);
323 return false;
324 }
325 }
326 return true;
327 }
328
JsObjToCachedLocationRequest(const napi_env & env,const napi_value & object,std::unique_ptr<CachedGnssLocationsRequest> & request)329 void JsObjToCachedLocationRequest(const napi_env& env, const napi_value& object,
330 std::unique_ptr<CachedGnssLocationsRequest>& request)
331 {
332 JsObjectToInt(env, object, "reportingPeriodSec", request->reportingPeriodSec);
333 JsObjectToBool(env, object, "wakeUpCacheQueueFull", request->wakeUpCacheQueueFull);
334 }
335
JsObjToLocationRequest(const napi_env & env,const napi_value & object,std::unique_ptr<RequestConfig> & requestConfig)336 void JsObjToLocationRequest(const napi_env& env, const napi_value& object,
337 std::unique_ptr<RequestConfig>& requestConfig)
338 {
339 int value = 0;
340 double valueDouble = 0.0;
341 bool valueBool = false;
342 if (JsObjectToInt(env, object, "priority", value) == SUCCESS) {
343 requestConfig->SetPriority(value);
344 }
345 if (JsObjectToInt(env, object, "scenario", value) == SUCCESS ||
346 JsObjectToInt(env, object, "locationScenario", value) == SUCCESS) {
347 requestConfig->SetScenario(value);
348 }
349 if (JsObjectToInt(env, object, "timeInterval", value) == SUCCESS ||
350 JsObjectToInt(env, object, "interval", value) == SUCCESS) {
351 requestConfig->SetTimeInterval(value);
352 }
353 if (JsObjectToDouble(env, object, "maxAccuracy", valueDouble) == SUCCESS) {
354 requestConfig->SetMaxAccuracy(valueDouble);
355 }
356 if (JsObjectToDouble(env, object, "distanceInterval", valueDouble) == SUCCESS) {
357 requestConfig->SetDistanceInterval(valueDouble);
358 }
359 if (JsObjectToBool(env, object, "needPoi", valueBool) == SUCCESS) {
360 requestConfig->SetIsNeedPoi(valueBool);
361 }
362 }
363
JsObjToLocation(const napi_env & env,const napi_value & object,Location & location)364 bool JsObjToLocation(const napi_env& env, const napi_value& object,
365 Location& location)
366 {
367 double valueDouble = 0.0;
368 if (JsObjectToDouble(env, object, "latitude", valueDouble) == SUCCESS) {
369 location.SetLatitude(valueDouble);
370 } else {
371 LBSLOGE(NAPI_UTILS, "analysis latitude fail.");
372 return false;
373 }
374 if (JsObjectToDouble(env, object, "longitude", valueDouble) == SUCCESS) {
375 location.SetLongitude(valueDouble);
376 } else {
377 LBSLOGE(NAPI_UTILS, "analysis longitude fail.");
378 return false;
379 }
380 return true;
381 }
382
JsObjToLocatingRequiredDataConfig(const napi_env & env,const napi_value & object,std::unique_ptr<LocatingRequiredDataConfig> & config)383 void JsObjToLocatingRequiredDataConfig(const napi_env& env, const napi_value& object,
384 std::unique_ptr<LocatingRequiredDataConfig>& config)
385 {
386 int valueInt = 0;
387 bool valueBool = false;
388 if (JsObjectToInt(env, object, "type", valueInt) == SUCCESS) {
389 config->SetType(valueInt);
390 }
391 if (JsObjectToBool(env, object, "needStartScan", valueBool) == SUCCESS) {
392 config->SetNeedStartScan(valueBool);
393 }
394 if (JsObjectToInt(env, object, "scanInterval", valueInt) == SUCCESS) {
395 config->SetScanIntervalMs(valueInt < MIN_WIFI_SCAN_TIME ? MIN_WIFI_SCAN_TIME : valueInt);
396 }
397 if (JsObjectToInt(env, object, "scanTimeout", valueInt) == SUCCESS) {
398 config->SetScanTimeoutMs(valueInt < MIN_WIFI_SCAN_TIME ? MIN_WIFI_SCAN_TIME : valueInt);
399 }
400 }
401
JsObjToCurrentLocationRequest(const napi_env & env,const napi_value & object,std::unique_ptr<RequestConfig> & requestConfig)402 void JsObjToCurrentLocationRequest(const napi_env& env, const napi_value& object,
403 std::unique_ptr<RequestConfig>& requestConfig)
404 {
405 int value = 0;
406 double valueDouble = 0.0;
407 bool valueBool = false;
408 if (JsObjectToInt(env, object, "priority", value) == SUCCESS ||
409 JsObjectToInt(env, object, "locatingPriority", value) == SUCCESS) {
410 requestConfig->SetPriority(value);
411 }
412 if (JsObjectToInt(env, object, "scenario", value) == SUCCESS) {
413 requestConfig->SetScenario(value);
414 }
415 if (JsObjectToDouble(env, object, "maxAccuracy", valueDouble) == SUCCESS) {
416 requestConfig->SetMaxAccuracy(valueDouble);
417 }
418 if (JsObjectToInt(env, object, "timeoutMs", value) == SUCCESS ||
419 JsObjectToInt(env, object, "locatingTimeoutMs", value) == SUCCESS) {
420 requestConfig->SetTimeOut(value);
421 }
422 if (JsObjectToBool(env, object, "needPoi", valueBool) == SUCCESS) {
423 requestConfig->SetIsNeedPoi(valueBool);
424 }
425 }
426
JsObjToCommand(const napi_env & env,const napi_value & object,std::unique_ptr<LocationCommand> & commandConfig)427 int JsObjToCommand(const napi_env& env, const napi_value& object,
428 std::unique_ptr<LocationCommand>& commandConfig)
429 {
430 if (commandConfig == nullptr) {
431 return COMMON_ERROR;
432 }
433 CHK_ERROR_CODE("scenario", JsObjectToInt(env, object, "scenario", commandConfig->scenario), true);
434 CHK_ERROR_CODE("command", JsObjectToString(env, object, "command", MAX_BUF_LEN, commandConfig->command), true);
435 return SUCCESS;
436 }
437
JsObjToGeoCodeRequest(const napi_env & env,const napi_value & object,MessageParcel & dataParcel)438 int JsObjToGeoCodeRequest(const napi_env& env, const napi_value& object, MessageParcel& dataParcel)
439 {
440 std::string description = "";
441 int maxItems = 1;
442 double minLatitude = 0.0;
443 double minLongitude = 0.0;
444 double maxLatitude = 0.0;
445 double maxLongitude = 0.0;
446 std::string locale = "";
447 int bufLen = MAX_BUF_LEN;
448 std::string country = "";
449 CHK_ERROR_CODE("locale", JsObjectToString(env, object, "locale", bufLen, locale), false);
450 CHK_ERROR_CODE("description", JsObjectToString(env, object, "description", bufLen, description), true);
451 if (description == "") {
452 LBSLOGE(LOCATOR_STANDARD, "The required description field should not be empty.");
453 return INPUT_PARAMS_ERROR;
454 }
455 CHK_ERROR_CODE("maxItems", JsObjectToInt(env, object, "maxItems", maxItems), false);
456 CHK_ERROR_CODE("minLatitude", JsObjectToDouble(env, object, "minLatitude", minLatitude), false);
457 CHK_ERROR_CODE("minLongitude", JsObjectToDouble(env, object, "minLongitude", minLongitude), false);
458 CHK_ERROR_CODE("maxLatitude", JsObjectToDouble(env, object, "maxLatitude", maxLatitude), false);
459 CHK_ERROR_CODE("maxLongitude", JsObjectToDouble(env, object, "maxLongitude", maxLongitude), false);
460 CHK_ERROR_CODE("country", JsObjectToString(env, object, "country", MAX_BUF_LEN, country), false);
461 if (minLatitude < MIN_LATITUDE || minLatitude > MAX_LATITUDE) {
462 return INPUT_PARAMS_ERROR;
463 }
464 if (minLongitude < MIN_LONGITUDE || minLongitude > MAX_LONGITUDE) {
465 return INPUT_PARAMS_ERROR;
466 }
467 if (maxLatitude < MIN_LATITUDE || maxLatitude > MAX_LATITUDE) {
468 return INPUT_PARAMS_ERROR;
469 }
470 if (maxLongitude < MIN_LONGITUDE || maxLongitude > MAX_LONGITUDE) {
471 return INPUT_PARAMS_ERROR;
472 }
473 if (!dataParcel.WriteInterfaceToken(LocatorProxy::GetDescriptor())) {
474 LBSLOGE(LOCATOR_STANDARD, "write interfaceToken fail!");
475 return COMMON_ERROR;
476 }
477 dataParcel.WriteString16(Str8ToStr16(locale)); // locale
478 dataParcel.WriteString16(Str8ToStr16(description)); // description
479 dataParcel.WriteInt32(maxItems); // maxItems
480 dataParcel.WriteDouble(minLatitude); // latitude
481 dataParcel.WriteDouble(minLongitude); // longitude
482 dataParcel.WriteDouble(maxLatitude); // latitude
483 dataParcel.WriteDouble(maxLongitude); // longitude
484 dataParcel.WriteString16(Str8ToStr16(CommonUtils::GenerateUuid())); // transId
485 dataParcel.WriteString16(Str8ToStr16(country)); // country
486 return SUCCESS;
487 }
488
JsObjToReverseGeoCodeRequest(const napi_env & env,const napi_value & object,MessageParcel & dataParcel)489 int JsObjToReverseGeoCodeRequest(const napi_env& env, const napi_value& object, MessageParcel& dataParcel)
490 {
491 double latitude = 0;
492 double longitude = 0;
493 int maxItems = 1;
494 std::string locale = "";
495 std::string country = "";
496
497 CHK_ERROR_CODE("latitude", JsObjectToDouble(env, object, "latitude", latitude), true);
498 CHK_ERROR_CODE("longitude", JsObjectToDouble(env, object, "longitude", longitude), true);
499 CHK_ERROR_CODE("maxItems", JsObjectToInt(env, object, "maxItems", maxItems), false);
500 CHK_ERROR_CODE("locale", JsObjectToString(env, object, "locale", MAX_BUF_LEN, locale), false); // max bufLen
501 CHK_ERROR_CODE("country", JsObjectToString(env, object, "country", MAX_BUF_LEN, country), false);
502
503 if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {
504 return INPUT_PARAMS_ERROR;
505 }
506 if (longitude < MIN_LONGITUDE || longitude > MAX_LONGITUDE) {
507 return INPUT_PARAMS_ERROR;
508 }
509 if (!dataParcel.WriteInterfaceToken(LocatorProxy::GetDescriptor())) {
510 return COMMON_ERROR;
511 }
512 dataParcel.WriteString16(Str8ToStr16(locale)); // locale
513 dataParcel.WriteDouble(latitude); // latitude
514 dataParcel.WriteDouble(longitude); // longitude
515 dataParcel.WriteInt32(maxItems); // maxItems
516 dataParcel.WriteString16(Str8ToStr16(CommonUtils::GenerateUuid())); // transId
517 dataParcel.WriteString16(Str8ToStr16(country)); // country
518 return SUCCESS;
519 }
520
GetArrayProperty(const napi_env & env,const napi_value & object,const std::string propertyName)521 napi_value GetArrayProperty(const napi_env& env, const napi_value& object, const std::string propertyName)
522 {
523 if (object == nullptr) {
524 LBSLOGE(NAPI_UTILS, "object is nullptr.");
525 return UndefinedNapiValue(env);
526 }
527 bool hasProperty = false;
528 NAPI_CALL_BASE(env,
529 napi_has_named_property(env, object, propertyName.c_str(), &hasProperty), UndefinedNapiValue(env));
530 if (!hasProperty) {
531 LBSLOGE(NAPI_UTILS, "propertyName is not exist");
532 return UndefinedNapiValue(env);
533 }
534 napi_value property = nullptr;
535 NAPI_CALL_BASE(env,
536 napi_get_named_property(env, object, propertyName.c_str(), &property), UndefinedNapiValue(env));
537 bool isArray = false;
538 NAPI_CALL_BASE(env, napi_is_array(env, property, &isArray), UndefinedNapiValue(env));
539 if (!isArray) {
540 LBSLOGE(NAPI_UTILS, "propertyName is not an array!");
541 return UndefinedNapiValue(env);
542 }
543 return property;
544 }
545
GetLocationInfo(const napi_env & env,const napi_value & object,const char * fieldStr,std::shared_ptr<ReverseGeocodeRequest> & request)546 bool GetLocationInfo(const napi_env& env, const napi_value& object,
547 const char* fieldStr, std::shared_ptr<ReverseGeocodeRequest>& request)
548 {
549 bool result = false;
550 napi_value value = nullptr;
551
552 if (object == nullptr) {
553 LBSLOGE(LOCATOR_STANDARD, "object is nullptr.");
554 return false;
555 }
556
557 NAPI_CALL_BASE(env, napi_has_named_property(env, object, fieldStr, &result), false);
558 if (result) {
559 NAPI_CALL_BASE(env, napi_get_named_property(env, object, fieldStr, &value), false);
560 JsObjectToString(env, value, "locale", MAX_BUF_LEN, request->locale);
561 JsObjectToInt(env, value, "maxItems", request->maxItems);
562 JsObjectToDouble(env, value, "latitude", request->latitude);
563 JsObjectToDouble(env, value, "longitude", request->longitude);
564 return true;
565 }
566 return false;
567 }
568
GetNapiValueByKey(napi_env env,const std::string & keyChar,napi_value object)569 napi_value GetNapiValueByKey(napi_env env, const std::string& keyChar, napi_value object)
570 {
571 if (object == nullptr) {
572 LBSLOGE(LOCATOR_STANDARD, "GetNapiValueByKey object is nullptr.");
573 return nullptr;
574 }
575 bool result = false;
576 NAPI_CALL(env, napi_has_named_property(env, object, keyChar.c_str(), &result));
577 if (result) {
578 napi_value value = nullptr;
579 NAPI_CALL(env, napi_get_named_property(env, object, keyChar.c_str(), &value));
580 return value;
581 }
582 return nullptr;
583 }
584
GetStringArrayFromJsObj(napi_env env,napi_value value,std::vector<std::string> & outArray)585 bool GetStringArrayFromJsObj(napi_env env, napi_value value, std::vector<std::string>& outArray)
586 {
587 uint32_t arrayLength = 0;
588 NAPI_CALL_BASE(env, napi_get_array_length(env, value, &arrayLength), false);
589 if (arrayLength == 0) {
590 LBSLOGE(LOCATOR_STANDARD, "The array is empty.");
591 return false;
592 }
593 for (size_t i = 0; i < arrayLength; i++) {
594 napi_value napiElement = nullptr;
595 NAPI_CALL_BASE(env, napi_get_element(env, value, i, &napiElement), false);
596 napi_valuetype napiValueType = napi_undefined;
597 NAPI_CALL_BASE(env, napi_typeof(env, napiElement, &napiValueType), false);
598 if (napiValueType != napi_string) {
599 LBSLOGE(LOCATOR_STANDARD, "wrong argument type.");
600 return false;
601 }
602 char type[64] = {0}; // max length
603 size_t typeLen = 0;
604 NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, napiElement, type, sizeof(type), &typeLen), false);
605 std::string event = type;
606 outArray.push_back(event);
607 }
608 return true;
609 }
610
GetStringArrayValueByKey(napi_env env,napi_value jsObject,const std::string & key,std::vector<std::string> & outArray)611 bool GetStringArrayValueByKey(
612 napi_env env, napi_value jsObject, const std::string& key, std::vector<std::string>& outArray)
613 {
614 napi_value array = GetNapiValueByKey(env, key, jsObject);
615 if (array == nullptr) {
616 return false;
617 }
618 bool isArray = false;
619 NAPI_CALL_BASE(env, napi_is_array(env, array, &isArray), false);
620 if (!isArray) {
621 LBSLOGE(LOCATOR_STANDARD, "not an array!");
622 return false;
623 }
624 return GetStringArrayFromJsObj(env, array, outArray);
625 }
626
GetGeoAddressInfo(const napi_env & env,const napi_value & object,const std::string & fieldStr,std::shared_ptr<GeoAddress> address)627 bool GetGeoAddressInfo(const napi_env& env, const napi_value& object,
628 const std::string& fieldStr, std::shared_ptr<GeoAddress> address)
629 {
630 napi_value value = GetNapiValueByKey(env, fieldStr, object);
631 if (value == nullptr) {
632 LBSLOGE(LOCATOR_STANDARD, "GetNapiValueByKey is nullptr.");
633 return false;
634 }
635 int bufLen = MAX_BUF_LEN;
636 JsObjectToDouble(env, value, "latitude", address->latitude_);
637 JsObjectToDouble(env, value, "longitude", address->longitude_);
638 JsObjectToString(env, value, "locale", bufLen, address->locale_);
639 JsObjectToString(env, value, "placeName", bufLen, address->placeName_);
640 JsObjectToString(env, value, "countryCode", bufLen, address->countryCode_);
641 JsObjectToString(env, value, "countryName", bufLen, address->countryName_);
642 JsObjectToString(env, value, "administrativeArea", bufLen, address->administrativeArea_);
643 JsObjectToString(env, value, "subAdministrativeArea", bufLen, address->subAdministrativeArea_);
644 JsObjectToString(env, value, "locality", bufLen, address->locality_);
645 JsObjectToString(env, value, "subLocality", bufLen, address->subLocality_);
646 JsObjectToString(env, value, "roadName", bufLen, address->roadName_);
647 JsObjectToString(env, value, "subRoadName", bufLen, address->subRoadName_);
648 JsObjectToString(env, value, "premises", bufLen, address->premises_);
649 JsObjectToString(env, value, "postalCode", bufLen, address->postalCode_);
650 JsObjectToString(env, value, "phoneNumber", bufLen, address->phoneNumber_);
651 JsObjectToString(env, value, "addressUrl", bufLen, address->addressUrl_);
652 JsObjectToInt(env, value, "descriptionsSize", address->descriptionsSize_);
653 JsObjectToBool(env, value, "isFromMock", address->isFromMock_);
654 std::vector<std::string> descriptions;
655 GetStringArrayValueByKey(env, value, "descriptions", descriptions);
656 size_t size = static_cast<size_t>(address->descriptionsSize_) > descriptions.size() ?
657 descriptions.size() : static_cast<size_t>(address->descriptionsSize_);
658 for (size_t i = 0; i < size; i++) {
659 address->descriptions_.insert(std::make_pair(i, descriptions[i]));
660 }
661 return true;
662 }
663
JsObjToRevGeocodeMock(const napi_env & env,const napi_value & object,std::vector<std::shared_ptr<GeocodingMockInfo>> & mockInfo)664 bool JsObjToRevGeocodeMock(const napi_env& env, const napi_value& object,
665 std::vector<std::shared_ptr<GeocodingMockInfo>>& mockInfo)
666 {
667 bool isArray = false;
668 NAPI_CALL_BASE(env, napi_is_array(env, object, &isArray), false);
669 if (!isArray) {
670 LBSLOGE(LOCATOR_STANDARD, "JsObjToRevGeocodeMock:not an array!");
671 return false;
672 }
673 uint32_t arrayLength = 0;
674 NAPI_CALL_BASE(env, napi_get_array_length(env, object, &arrayLength), false);
675 if (arrayLength == 0) {
676 LBSLOGE(LOCATOR_STANDARD, "JsObjToRevGeocodeMock:The array is empty.");
677 return false;
678 }
679 for (size_t i = 0; i < arrayLength; i++) {
680 napi_value napiElement = nullptr;
681 NAPI_CALL_BASE(env, napi_get_element(env, object, i, &napiElement), false);
682 std::shared_ptr<GeocodingMockInfo> info = std::make_shared<GeocodingMockInfo>();
683 std::shared_ptr<ReverseGeocodeRequest> request = std::make_shared<ReverseGeocodeRequest>();
684 std::shared_ptr<GeoAddress> geoAddress = std::make_shared<GeoAddress>();
685 GetLocationInfo(env, napiElement, "location", request);
686 GetGeoAddressInfo(env, napiElement, "geoAddress", geoAddress);
687 info->SetLocation(request);
688 info->SetGeoAddressInfo(geoAddress);
689 mockInfo.push_back(info);
690 }
691 return true;
692 }
693
GetLocationArray(const napi_env & env,LocationMockAsyncContext * asyncContext,const napi_value & object)694 void GetLocationArray(const napi_env& env, LocationMockAsyncContext *asyncContext, const napi_value& object)
695 {
696 uint32_t arrayLength = 0;
697 NAPI_CALL_RETURN_VOID(env, napi_get_array_length(env, object, &arrayLength));
698 if (arrayLength == 0) {
699 LBSLOGE(LOCATOR_STANDARD, "The array is empty.");
700 return;
701 }
702 for (uint32_t i = 0; i < arrayLength; i++) {
703 napi_value elementValue = nullptr;
704 std::shared_ptr<Location> locationAdapter = std::make_shared<Location>();
705 NAPI_CALL_RETURN_VOID(env, napi_get_element(env, object, i, &elementValue));
706 double latitude = 0.0;
707 JsObjectToDouble(env, elementValue, "latitude", latitude);
708 locationAdapter->SetLatitude(latitude);
709 double longitude = 0.0;
710 JsObjectToDouble(env, elementValue, "longitude", longitude);
711 locationAdapter->SetLongitude(longitude);
712 double altitude = 0.0;
713 JsObjectToDouble(env, elementValue, "altitude", altitude);
714 locationAdapter->SetAltitude(altitude);
715 double accuracy = 0.0;
716 JsObjectToDouble(env, elementValue, "accuracy", accuracy);
717 locationAdapter->SetAccuracy(accuracy);
718 double speed = 0.0;
719 JsObjectToDouble(env, elementValue, "speed", speed);
720 locationAdapter->SetSpeed(speed);
721 double direction = 0.0;
722 JsObjectToDouble(env, elementValue, "direction", direction);
723 locationAdapter->SetDirection(direction);
724 int64_t timeStamp = 0;
725 JsObjectToInt64(env, elementValue, "timeStamp", timeStamp);
726 locationAdapter->SetTimeStamp(timeStamp);
727 int64_t timeSinceBoot = 0;
728 JsObjectToInt64(env, elementValue, "timeSinceBoot", timeSinceBoot);
729 locationAdapter->SetTimeSinceBoot(timeSinceBoot);
730 int32_t additionSize = 0;
731 JsObjectToInt(env, elementValue, "additionSize", additionSize);
732 locationAdapter->SetAdditionSize(static_cast<int64_t>(additionSize));
733 bool isFromMock = false;
734 JsObjectToBool(env, elementValue, "isFromMock", isFromMock);
735 locationAdapter->SetIsFromMock(isFromMock ? 1 : 0);
736 std::vector<std::string> additions;
737 GetStringArrayValueByKey(env, elementValue, "additions", additions);
738 locationAdapter->SetAdditions(additions, false);
739 asyncContext->LocationNapi.push_back(locationAdapter);
740 }
741 }
742
JsObjectToString(const napi_env & env,const napi_value & object,const char * fieldStr,const int bufLen,std::string & fieldRef)743 int JsObjectToString(const napi_env& env, const napi_value& object,
744 const char* fieldStr, const int bufLen, std::string& fieldRef)
745 {
746 bool hasProperty = false;
747 NAPI_CALL_BASE(env, napi_has_named_property(env, object, fieldStr, &hasProperty), COMMON_ERROR);
748 if (hasProperty) {
749 napi_value field;
750 napi_valuetype valueType;
751
752 NAPI_CALL_BASE(env, napi_get_named_property(env, object, fieldStr, &field), COMMON_ERROR);
753 NAPI_CALL_BASE(env, napi_typeof(env, field, &valueType), COMMON_ERROR);
754 if (valueType != napi_string) {
755 LBSLOGE(LOCATOR_STANDARD, "JsObjectToString, valueType != napi_string.");
756 return INPUT_PARAMS_ERROR;
757 }
758 if (bufLen <= 0) {
759 LBSLOGE(LOCATOR_STANDARD, "The length of buf should be greater than 0.");
760 return COMMON_ERROR;
761 }
762 int32_t actBuflen = bufLen + 1;
763 std::unique_ptr<char[]> buf = std::make_unique<char[]>(actBuflen);
764 (void)memset_s(buf.get(), actBuflen, 0, actBuflen);
765 size_t result = 0;
766 NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, field, buf.get(), actBuflen, &result), COMMON_ERROR);
767 fieldRef = buf.get();
768 return SUCCESS;
769 }
770 LBSLOGD(LOCATOR_STANDARD, "Js obj to str no property: %{public}s", fieldStr);
771 return PARAM_IS_EMPTY;
772 }
773
JsObjectToDouble(const napi_env & env,const napi_value & object,const char * fieldStr,double & fieldRef)774 int JsObjectToDouble(const napi_env& env, const napi_value& object, const char* fieldStr, double& fieldRef)
775 {
776 bool hasProperty = false;
777 NAPI_CALL_BASE(env, napi_has_named_property(env, object, fieldStr, &hasProperty), COMMON_ERROR);
778 if (hasProperty) {
779 napi_value field;
780 napi_valuetype valueType;
781
782 NAPI_CALL_BASE(env, napi_get_named_property(env, object, fieldStr, &field), COMMON_ERROR);
783 NAPI_CALL_BASE(env, napi_typeof(env, field, &valueType), COMMON_ERROR);
784 NAPI_ASSERT_BASE(env, valueType == napi_number, "Wrong argument type.", INPUT_PARAMS_ERROR);
785 NAPI_CALL_BASE(env, napi_get_value_double(env, field, &fieldRef), COMMON_ERROR);
786 return SUCCESS;
787 }
788 LBSLOGD(LOCATOR_STANDARD, "Js to int no property: %{public}s", fieldStr);
789 return PARAM_IS_EMPTY;
790 }
791
JsObjectToInt(const napi_env & env,const napi_value & object,const char * fieldStr,int & fieldRef)792 int JsObjectToInt(const napi_env& env, const napi_value& object, const char* fieldStr, int& fieldRef)
793 {
794 bool hasProperty = false;
795 NAPI_CALL_BASE(env, napi_has_named_property(env, object, fieldStr, &hasProperty), COMMON_ERROR);
796 if (hasProperty) {
797 napi_value field;
798 napi_valuetype valueType;
799
800 NAPI_CALL_BASE(env, napi_get_named_property(env, object, fieldStr, &field), COMMON_ERROR);
801 NAPI_CALL_BASE(env, napi_typeof(env, field, &valueType), COMMON_ERROR);
802 NAPI_ASSERT_BASE(env, valueType == napi_number, "Wrong argument type.", INPUT_PARAMS_ERROR);
803 NAPI_CALL_BASE(env, napi_get_value_int32(env, field, &fieldRef), COMMON_ERROR);
804 return SUCCESS;
805 }
806 LBSLOGD(LOCATOR_STANDARD, "Js to int no property: %{public}s", fieldStr);
807 return PARAM_IS_EMPTY;
808 }
809
JsObjectToInt64(const napi_env & env,const napi_value & object,const char * fieldStr,int64_t & fieldRef)810 int JsObjectToInt64(const napi_env& env, const napi_value& object, const char* fieldStr, int64_t& fieldRef)
811 {
812 bool hasProperty = false;
813 NAPI_CALL_BASE(env, napi_has_named_property(env, object, fieldStr, &hasProperty), COMMON_ERROR);
814 if (hasProperty) {
815 napi_value field;
816 napi_valuetype valueType;
817
818 NAPI_CALL_BASE(env, napi_get_named_property(env, object, fieldStr, &field), COMMON_ERROR);
819 NAPI_CALL_BASE(env, napi_typeof(env, field, &valueType), COMMON_ERROR);
820 NAPI_ASSERT_BASE(env, valueType == napi_number, "Wrong argument type.", INPUT_PARAMS_ERROR);
821 NAPI_CALL_BASE(env, napi_get_value_int64(env, field, &fieldRef), COMMON_ERROR);
822 return SUCCESS;
823 }
824 LBSLOGD(LOCATOR_STANDARD, "Js to int no property: %{public}s", fieldStr);
825 return PARAM_IS_EMPTY;
826 }
827
JsObjectToBool(const napi_env & env,const napi_value & object,const char * fieldStr,bool & fieldRef)828 int JsObjectToBool(const napi_env& env, const napi_value& object, const char* fieldStr, bool& fieldRef)
829 {
830 bool hasProperty = false;
831 NAPI_CALL_BASE(env, napi_has_named_property(env, object, fieldStr, &hasProperty), COMMON_ERROR);
832 if (hasProperty) {
833 napi_value field;
834 napi_valuetype valueType;
835
836 NAPI_CALL_BASE(env, napi_get_named_property(env, object, fieldStr, &field), COMMON_ERROR);
837 NAPI_CALL_BASE(env, napi_typeof(env, field, &valueType), COMMON_ERROR);
838 NAPI_ASSERT_BASE(env, valueType == napi_boolean, "Wrong argument type.", INPUT_PARAMS_ERROR);
839 NAPI_CALL_BASE(env, napi_get_value_bool(env, field, &fieldRef), COMMON_ERROR);
840 return SUCCESS;
841 }
842 LBSLOGD(LOCATOR_STANDARD, "Js to bool no property: %{public}s", fieldStr);
843 return PARAM_IS_EMPTY;
844 }
845
SetValueUtf8String(const napi_env & env,const char * fieldStr,const char * str,napi_value & result)846 napi_status SetValueUtf8String(const napi_env& env, const char* fieldStr, const char* str, napi_value& result)
847 {
848 napi_value value = nullptr;
849 NAPI_CALL_BASE(env, napi_create_string_utf8(env, str, NAPI_AUTO_LENGTH, &value), napi_generic_failure);
850 NAPI_CALL_BASE(env, napi_set_named_property(env, result, fieldStr, value), napi_generic_failure);
851 return napi_ok;
852 }
853
SetValueStringArray(const napi_env & env,const char * fieldStr,napi_value & value,napi_value & result)854 napi_status SetValueStringArray(const napi_env& env, const char* fieldStr, napi_value& value, napi_value& result)
855 {
856 NAPI_CALL_BASE(env, napi_set_named_property(env, result, fieldStr, value), napi_generic_failure);
857 return napi_ok;
858 }
859
SetValueStringMap(const napi_env & env,const char * fieldStr,napi_value & value,napi_value & result)860 napi_status SetValueStringMap(const napi_env& env, const char* fieldStr, napi_value& value, napi_value& result)
861 {
862 NAPI_CALL_BASE(env, napi_set_named_property(env, result, fieldStr, value), napi_generic_failure);
863 return napi_ok;
864 }
865
SetValuePoi(const napi_env & env,const char * fieldStr,napi_value & value,napi_value & result)866 napi_status SetValuePoi(const napi_env& env, const char* fieldStr, napi_value& value, napi_value& result)
867 {
868 NAPI_CALL_BASE(env, napi_set_named_property(env, result, fieldStr, value), napi_generic_failure);
869 return napi_ok;
870 }
871
SetValueInt32(const napi_env & env,const char * fieldStr,const int intValue,napi_value & result)872 napi_status SetValueInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result)
873 {
874 napi_value value = nullptr;
875 NAPI_CALL_BASE(env, napi_create_int32(env, intValue, &value), napi_generic_failure);
876 NAPI_CALL_BASE(env, napi_set_named_property(env, result, fieldStr, value), napi_generic_failure);
877 return napi_ok;
878 }
879
SetValueInt64(const napi_env & env,const char * fieldStr,const int64_t intValue,napi_value & result)880 napi_status SetValueInt64(const napi_env& env, const char* fieldStr, const int64_t intValue, napi_value& result)
881 {
882 napi_value value = nullptr;
883 NAPI_CALL_BASE(env, napi_create_int64(env, intValue, &value), napi_generic_failure);
884 NAPI_CALL_BASE(env, napi_set_named_property(env, result, fieldStr, value), napi_generic_failure);
885 return napi_ok;
886 }
887
SetValueDouble(const napi_env & env,const char * fieldStr,const double doubleValue,napi_value & result)888 napi_status SetValueDouble(const napi_env& env, const char* fieldStr, const double doubleValue, napi_value& result)
889 {
890 napi_value value = nullptr;
891 NAPI_CALL_BASE(env, napi_create_double(env, doubleValue, &value), napi_generic_failure);
892 NAPI_CALL_BASE(env, napi_set_named_property(env, result, fieldStr, value), napi_generic_failure);
893 return napi_ok;
894 }
895
SetValueBool(const napi_env & env,const char * fieldStr,const bool boolvalue,napi_value & result)896 napi_status SetValueBool(const napi_env& env, const char* fieldStr, const bool boolvalue, napi_value& result)
897 {
898 napi_value value = nullptr;
899 NAPI_CALL_BASE(env, napi_get_boolean(env, boolvalue, &value), napi_generic_failure);
900 NAPI_CALL_BASE(env, napi_set_named_property(env, result, fieldStr, value), napi_generic_failure);
901 return napi_ok;
902 }
903
SetValueArrayBuffer(const napi_env & env,const char * fieldStr,const std::vector<uint8_t> vectorValue,napi_value & result)904 napi_status SetValueArrayBuffer(const napi_env& env, const char* fieldStr, const std::vector<uint8_t> vectorValue,
905 napi_value& result)
906 {
907 size_t bufferSize = vectorValue.size();
908 uint8_t *nativeArraybuffer = nullptr;
909 napi_value nativeValue = nullptr;
910 napi_create_arraybuffer(env, bufferSize, reinterpret_cast<void **>(&nativeArraybuffer), &nativeValue);
911 memcpy_s(nativeArraybuffer, bufferSize, vectorValue.data(), bufferSize);
912 NAPI_CALL_BASE(env, napi_set_named_property(env, result, fieldStr, nativeValue), napi_generic_failure);
913 return napi_ok;
914 }
915
InitAsyncCallBackEnv(const napi_env & env,AsyncContext * asyncContext,const size_t argc,const napi_value * argv,const size_t objectArgsNum)916 static bool InitAsyncCallBackEnv(const napi_env& env, AsyncContext* asyncContext,
917 const size_t argc, const napi_value* argv, const size_t objectArgsNum)
918 {
919 if (asyncContext == nullptr || argv == nullptr ||
920 argc > MAXIMUM_JS_PARAMS || objectArgsNum > MAXIMUM_JS_PARAMS) {
921 return false;
922 }
923 size_t startLoop = objectArgsNum;
924 size_t endLoop = argc;
925 for (size_t i = startLoop; i < endLoop; ++i) {
926 napi_valuetype valuetype;
927 NAPI_CALL_BASE(env, napi_typeof(env, argv[i], &valuetype), false);
928 NAPI_ASSERT_BASE(env, valuetype == napi_function, "Wrong argument type.", false);
929 size_t index = i - startLoop;
930 if (index >= MAX_CALLBACK_NUM) {
931 break;
932 }
933 NAPI_CALL_BASE(env, napi_create_reference(env, argv[i], 1, &asyncContext->callback[index]), false);
934 }
935 return true;
936 }
937
InitAsyncPromiseEnv(const napi_env & env,AsyncContext * asyncContext,napi_value & promise)938 static bool InitAsyncPromiseEnv(const napi_env& env, AsyncContext *asyncContext, napi_value& promise)
939 {
940 napi_deferred deferred;
941 if (asyncContext == nullptr) {
942 return false;
943 }
944 NAPI_CALL_BASE(env, napi_create_promise(env, &deferred, &promise), false);
945 asyncContext->deferred = deferred;
946 return true;
947 }
948
CreateFailCallBackParams(AsyncContext & context,const std::string & msg,int32_t errorCode)949 void CreateFailCallBackParams(AsyncContext& context, const std::string& msg, int32_t errorCode)
950 {
951 SetValueUtf8String(context.env, "data", msg.c_str(), context.result[PARAM0]);
952 SetValueInt32(context.env, "code", errorCode, context.result[PARAM1]);
953 }
954
GetErrorMsgByCode(int code)955 std::string GetErrorMsgByCode(int code)
956 {
957 static std::map<int, std::string> errorCodeMap = GetErrorCodeMap();
958 auto iter = errorCodeMap.find(code);
959 if (iter != errorCodeMap.end()) {
960 std::string errMessage = "BussinessError ";
961 code = ConvertErrorCode(code);
962 errMessage.append(std::to_string(code)).append(": ").append(iter->second);
963 return errMessage;
964 }
965 return "undefined error.";
966 }
967
GetErrorCodeMap()968 std::map<int, std::string> GetErrorCodeMap()
969 {
970 std::map<int, std::string> errorCodeMap = {
971 {SUCCESS, "SUCCESS"},
972 {NOT_SUPPORTED, "NOT_SUPPORTED"},
973 {INPUT_PARAMS_ERROR, "INPUT_PARAMS_ERROR"},
974 {REVERSE_GEOCODE_ERROR, "REVERSE_GEOCODE_ERROR"},
975 {GEOCODE_ERROR, "GEOCODE_ERROR"},
976 {LOCATOR_ERROR, "LOCATOR_ERROR"},
977 {LOCATION_SWITCH_ERROR, "LOCATION_SWITCH_ERROR"},
978 {LAST_KNOWN_LOCATION_ERROR, "LAST_KNOWN_LOCATION_ERROR"},
979 {LOCATION_REQUEST_TIMEOUT_ERROR, "LOCATION_REQUEST_TIMEOUT_ERROR"},
980 {QUERY_COUNTRY_CODE_ERROR, "QUERY_COUNTRY_CODE_ERROR"},
981 {LocationErrCode::ERRCODE_SUCCESS, "SUCCESS."},
982 {LocationErrCode::ERRCODE_PERMISSION_DENIED,
983 "Permission verification failed. The application does not have the permission required to call the API."},
984 {LocationErrCode::ERRCODE_SYSTEM_PERMISSION_DENIED,
985 "Permission verification failed. A non-system application calls a system API."},
986 {LocationErrCode::ERRCODE_INVALID_PARAM,
987 "Parameter error. Possible causes:1.Mandatory parameters are left unspecified;" \
988 "2.Incorrect parameter types;3. Parameter verification failed."},
989 {LocationErrCode::ERRCODE_NOT_SUPPORTED,
990 "Capability not supported." \
991 "Failed to call function due to limited device capabilities."},
992 {LocationErrCode::ERRCODE_SERVICE_UNAVAILABLE, "The location service is unavailable."},
993 {LocationErrCode::ERRCODE_LOCATING_NETWORK_FAIL,
994 "The network locating is failed because the network cannot be accessed."},
995 {LocationErrCode::ERRCODE_LOCATING_ACC_FAIL,
996 "The positioning result does not meet the precision requirement (maxAccuracy)" \
997 " in the positioning request parameters. "},
998 {LocationErrCode::ERRCODE_LOCATING_CACHE_FAIL, "The system does not have a cache locaiton."},
999 {LocationErrCode::ERRCODE_SWITCH_OFF, "The location switch is off."},
1000 {LocationErrCode::ERRCODE_LOCATING_FAIL, "Failed to obtain the geographical location."},
1001 {LocationErrCode::ERRCODE_REVERSE_GEOCODING_FAIL, "Reverse geocoding query failed."},
1002 {LocationErrCode::ERRCODE_GEOCODING_FAIL, "Geocoding query failed."},
1003 {LocationErrCode::ERRCODE_COUNTRYCODE_FAIL, "Failed to query the area information."},
1004 {LocationErrCode::ERRCODE_GEOFENCE_FAIL, "Failed to operate the geofence."},
1005 {LocationErrCode::ERRCODE_NO_RESPONSE, "No response to the request."},
1006 {LocationErrCode::ERRCODE_GEOFENCE_EXCEED_MAXIMUM, "The number of geofences exceeds the maximum."},
1007 {LocationErrCode::ERRCODE_GEOFENCE_INCORRECT_ID, "Failed to delete a geofence due to an incorrect ID."},
1008 {LocationErrCode::ERRCODE_WIFI_IS_NOT_CONNECTED,
1009 "Failed to obtain the hotpot MAC address because the Wi-Fi is not connected."}
1010 };
1011 GetErrorCodeMapExt(errorCodeMap);
1012 return errorCodeMap;
1013 }
1014
GetErrorCodeMapExt(std::map<int,std::string> & errorCodeMap)1015 void GetErrorCodeMapExt(std::map<int, std::string>& errorCodeMap)
1016 {
1017 errorCodeMap.insert(std::make_pair(LocationErrCode::ERRCODE_BEACONFENCE_LOCATION_SWITCH_OFF,
1018 "Failed to add a beacon fence because the location switch is off."));
1019 errorCodeMap.insert(std::make_pair(LocationErrCode::ERRCODE_BEACONFENCE_BLUETOOTH_SWITCH_OFF,
1020 "Failed to add a beacon fence because the bluetooth switch is off."));
1021 errorCodeMap.insert(std::make_pair(LocationErrCode::ERRCODE_BEACONFENCE_EXCEED_MAXIMUM,
1022 "The number of beacon fence exceeds the maximum."));
1023 errorCodeMap.insert(std::make_pair(LocationErrCode::ERRCODE_BEACONFENCE_INCORRECT_ID,
1024 "Failed to delete the fence due to incorrect beacon fence information."));
1025 errorCodeMap.insert(std::make_pair(LocationErrCode::ERRCODE_BEACONFENCE_DUPLICATE_INFORMATION,
1026 "Duplicate beacon fence information."));
1027 }
1028
ConvertErrorCode(int errorCode)1029 int ConvertErrorCode(int errorCode)
1030 {
1031 if (errorCode == LocationErrCode::ERRCODE_LOCATING_NETWORK_FAIL ||
1032 errorCode == LocationErrCode::ERRCODE_LOCATING_CACHE_FAIL ||
1033 errorCode == LocationErrCode::ERRCODE_LOCATING_ACC_FAIL) {
1034 LBSLOGI(LOCATOR_STANDARD, "Convert ErrorCode: %{public}d to %{public}d",
1035 errorCode, LocationErrCode::ERRCODE_LOCATING_FAIL);
1036 return LocationErrCode::ERRCODE_LOCATING_FAIL;
1037 }
1038 return errorCode;
1039 }
1040
GetErrorObject(napi_env env,const int32_t errCode,const std::string & errMsg)1041 napi_value GetErrorObject(napi_env env, const int32_t errCode, const std::string& errMsg)
1042 {
1043 napi_value businessError = nullptr;
1044 napi_value eCode = nullptr;
1045 napi_value eMsg = nullptr;
1046 NAPI_CALL(env, napi_create_int32(env, errCode, &eCode));
1047 NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(), errMsg.length(), &eMsg));
1048 NAPI_CALL(env, napi_create_object(env, &businessError));
1049 NAPI_CALL(env, napi_set_named_property(env, businessError, "code", eCode));
1050 NAPI_CALL(env, napi_set_named_property(env, businessError, "message", eMsg));
1051 return businessError;
1052 }
1053
CreateResultObject(const napi_env & env,AsyncContext * context)1054 void CreateResultObject(const napi_env& env, AsyncContext* context)
1055 {
1056 if (context == nullptr || env == nullptr) {
1057 LBSLOGE(LOCATOR_STANDARD, "CreateResultObject input para error");
1058 return;
1059 }
1060 if (context->errCode != SUCCESS) {
1061 std::string errMsg = GetErrorMsgByCode(context->errCode);
1062 context->errCode = ConvertErrorCode(context->errCode);
1063 context->result[PARAM0] = GetErrorObject(env, context->errCode, errMsg);
1064 NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &context->result[PARAM1]));
1065 } else {
1066 NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &context->result[PARAM0]));
1067 }
1068 }
1069
SendResultToJs(const napi_env & env,AsyncContext * context)1070 void SendResultToJs(const napi_env& env, AsyncContext* context)
1071 {
1072 if (context == nullptr || env == nullptr) {
1073 LBSLOGE(LOCATOR_STANDARD, "SendResultToJs input para error");
1074 return;
1075 }
1076
1077 bool isPromise = context->deferred != nullptr;
1078 if (isPromise) {
1079 if (context->errCode != SUCCESS) {
1080 NAPI_CALL_RETURN_VOID(env,
1081 napi_reject_deferred(env, context->deferred, context->result[PARAM0]));
1082 } else {
1083 NAPI_CALL_RETURN_VOID(env,
1084 napi_resolve_deferred(env, context->deferred, context->result[PARAM1]));
1085 }
1086 } else {
1087 napi_value undefine;
1088 NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefine));
1089 napi_value callback;
1090 NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, context->callback[0], &callback));
1091 NAPI_CALL_RETURN_VOID(env,
1092 napi_call_function(env, nullptr, callback, RESULT_SIZE, context->result, &undefine));
1093 }
1094 }
1095
MemoryReclamation(const napi_env & env,AsyncContext * context)1096 void MemoryReclamation(const napi_env& env, AsyncContext* context)
1097 {
1098 if (context == nullptr || env == nullptr) {
1099 LBSLOGE(LOCATOR_STANDARD, "MemoryReclamation input para error");
1100 return;
1101 }
1102
1103 if (context->callback[SUCCESS_CALLBACK] != nullptr) {
1104 NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, context->callback[SUCCESS_CALLBACK]));
1105 }
1106 if (context->callback[FAIL_CALLBACK] != nullptr) {
1107 NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, context->callback[FAIL_CALLBACK]));
1108 }
1109 if (context->callback[COMPLETE_CALLBACK] != nullptr) {
1110 NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, context->callback[COMPLETE_CALLBACK]));
1111 }
1112 NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, context->work));
1113 delete context;
1114 }
1115
CreateAsyncWork(const napi_env & env,AsyncContext * asyncContext)1116 static napi_value CreateAsyncWork(const napi_env& env, AsyncContext* asyncContext)
1117 {
1118 if (asyncContext == nullptr) {
1119 return UndefinedNapiValue(env);
1120 }
1121 NAPI_CALL(env, napi_create_async_work(
1122 env, nullptr, asyncContext->resourceName,
1123 [](napi_env env, void* data) {
1124 if (data == nullptr) {
1125 LBSLOGE(LOCATOR_STANDARD, "Async data parameter is null");
1126 return;
1127 }
1128 AsyncContext* context = static_cast<AsyncContext *>(data);
1129 context->executeFunc(context);
1130 },
1131 [](napi_env env, napi_status status, void* data) {
1132 if (data == nullptr) {
1133 LBSLOGE(LOCATOR_STANDARD, "Async data parameter is null");
1134 return;
1135 }
1136 AsyncContext* context = static_cast<AsyncContext *>(data);
1137 context->completeFunc(data);
1138 CreateResultObject(env, context);
1139 SendResultToJs(env, context);
1140 MemoryReclamation(env, context);
1141 }, static_cast<void*>(asyncContext), &asyncContext->work));
1142 NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
1143 return UndefinedNapiValue(env);
1144 }
1145
DoAsyncWork(const napi_env & env,AsyncContext * asyncContext,const size_t argc,const napi_value * argv,const size_t objectArgsNum)1146 napi_value DoAsyncWork(const napi_env& env, AsyncContext* asyncContext,
1147 const size_t argc, const napi_value* argv, const size_t objectArgsNum)
1148 {
1149 if (asyncContext == nullptr || argv == nullptr) {
1150 return UndefinedNapiValue(env);
1151 }
1152 if (argc > objectArgsNum) {
1153 InitAsyncCallBackEnv(env, asyncContext, argc, argv, objectArgsNum);
1154 return CreateAsyncWork(env, asyncContext);
1155 } else {
1156 napi_value promise;
1157 InitAsyncPromiseEnv(env, asyncContext, promise);
1158 CreateAsyncWork(env, asyncContext);
1159 return promise;
1160 }
1161 }
1162
DeleteQueueWork(AsyncContext * context)1163 void DeleteQueueWork(AsyncContext* context)
1164 {
1165 uv_loop_s *loop = nullptr;
1166 if (context->env == nullptr) {
1167 LBSLOGE(LOCATOR_STANDARD, "env is nullptr.");
1168 delete context;
1169 return;
1170 }
1171 NAPI_CALL_RETURN_VOID(context->env, napi_get_uv_event_loop(context->env, &loop));
1172 if (loop == nullptr) {
1173 LBSLOGE(LOCATOR_STANDARD, "loop == nullptr.");
1174 delete context;
1175 return;
1176 }
1177 uv_work_t *work = new (std::nothrow) uv_work_t;
1178 if (work == nullptr) {
1179 LBSLOGE(LOCATOR_STANDARD, "work == nullptr.");
1180 delete context;
1181 return;
1182 }
1183 work->data = context;
1184 DeleteCallbackHandler(loop, work);
1185 }
1186
DeleteCallbackHandler(uv_loop_s * & loop,uv_work_t * & work)1187 void DeleteCallbackHandler(uv_loop_s *&loop, uv_work_t *&work)
1188 {
1189 uv_queue_work(loop, work, [](uv_work_t *work) {},
1190 [](uv_work_t *work, int status) {
1191 AsyncContext *context = nullptr;
1192 napi_handle_scope scope = nullptr;
1193 if (work == nullptr) {
1194 LBSLOGE(LOCATOR_CALLBACK, "work is nullptr");
1195 return;
1196 }
1197 context = static_cast<AsyncContext *>(work->data);
1198 if (context == nullptr || context->env == nullptr) {
1199 LBSLOGE(LOCATOR_CALLBACK, "context is nullptr");
1200 delete work;
1201 return;
1202 }
1203 NAPI_CALL_RETURN_VOID(context->env, napi_open_handle_scope(context->env, &scope));
1204 if (scope == nullptr) {
1205 LBSLOGE(LOCATOR_CALLBACK, "scope is nullptr");
1206 delete context;
1207 delete work;
1208 return;
1209 }
1210 if (context->callback[SUCCESS_CALLBACK] != nullptr) {
1211 CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
1212 napi_delete_reference(context->env, context->callback[SUCCESS_CALLBACK]),
1213 scope, context, work);
1214 }
1215 if (context->callback[FAIL_CALLBACK] != nullptr) {
1216 CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
1217 napi_delete_reference(context->env, context->callback[FAIL_CALLBACK]),
1218 scope, context, work);
1219 }
1220 if (context->callback[COMPLETE_CALLBACK] != nullptr) {
1221 CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
1222 napi_delete_reference(context->env, context->callback[COMPLETE_CALLBACK]),
1223 scope, context, work);
1224 }
1225 NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
1226 delete context;
1227 delete work;
1228 });
1229 }
1230
CheckIfParamIsFunctionType(napi_env env,napi_value param)1231 bool CheckIfParamIsFunctionType(napi_env env, napi_value param)
1232 {
1233 napi_valuetype valueType;
1234 NAPI_CALL_BASE(env, napi_typeof(env, param, &valueType), false);
1235 if (valueType != napi_function) {
1236 return false;
1237 }
1238 return true;
1239 }
1240
SetEnumPropertyByInteger(napi_env env,napi_value dstObj,int32_t enumValue,const char * enumName)1241 napi_value SetEnumPropertyByInteger(napi_env env, napi_value dstObj, int32_t enumValue, const char *enumName)
1242 {
1243 napi_value enumProp = nullptr;
1244 NAPI_CALL(env, napi_create_int32(env, enumValue, &enumProp));
1245 NAPI_CALL(env, napi_set_named_property(env, dstObj, enumName, enumProp));
1246 return enumProp;
1247 }
1248
CheckIfParamIsObjectType(napi_env env,napi_value param)1249 bool CheckIfParamIsObjectType(napi_env env, napi_value param)
1250 {
1251 napi_valuetype valueType;
1252 NAPI_CALL_BASE(env, napi_typeof(env, param, &valueType), false);
1253 if (valueType != napi_object) {
1254 return false;
1255 }
1256 return true;
1257 }
1258
CreateError(napi_env env,int32_t err,const std::string & msg)1259 napi_value CreateError(napi_env env, int32_t err, const std::string &msg)
1260 {
1261 napi_value businessError = nullptr;
1262 napi_value errorCode = nullptr;
1263 NAPI_CALL(env, napi_create_int32(env, err, &errorCode));
1264 napi_value errorMessage = nullptr;
1265 NAPI_CALL(env, napi_create_string_utf8(env, msg.c_str(), NAPI_AUTO_LENGTH, &errorMessage));
1266 napi_create_error(env, nullptr, errorMessage, &businessError);
1267 napi_set_named_property(env, businessError, "code", errorCode);
1268 return businessError;
1269 }
1270 } // namespace Location
1271 } // namespace OHOS
1272