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 #include "common.h"
16 #include "common_want.h"
17
18 #include "errors.h"
19 #include "work_sched_hilog.h"
20 #include "work_sched_errors.h"
21
22 namespace OHOS {
23 namespace WorkScheduler {
24 const int32_t NAME_MAXIMUM_LIMIT = 128;
25 const int32_t RESULT_PARAMS_NUM = 2;
26 const int32_t UNSET_INT_PARAM = -1;
27 const std::string UNSET_STRING_PARAM = "";
28 const int32_t TRUE_PARAM = 1;
29 const int32_t FALSE_PARAM = 0;
30 const int32_t BATTERY_LEVEL_MIN = 0;
31 const int32_t BATTERY_LEVEL_MAX = 100;
32 bool g_hasParamError = false;
33
AsyncWorkData(napi_env napiEnv)34 AsyncWorkData::AsyncWorkData(napi_env napiEnv)
35 {
36 env = napiEnv;
37 }
38
~AsyncWorkData()39 AsyncWorkData::~AsyncWorkData()
40 {
41 if (callback) {
42 WS_HILOGD("callback delete");
43 napi_delete_reference(env, callback);
44 callback = nullptr;
45 }
46 if (asyncWork) {
47 WS_HILOGD("asyncWork delete");
48 napi_delete_async_work(env, asyncWork);
49 asyncWork = nullptr;
50 }
51 }
52
NapiGetNull(napi_env env)53 napi_value Common::NapiGetNull(napi_env env)
54 {
55 napi_value result = nullptr;
56 napi_get_null(env, &result);
57 return result;
58 }
59
GetBaseWorkInfo(napi_env env,napi_value objValue,WorkInfo & workInfo)60 bool Common::GetBaseWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo)
61 {
62 // Get workid.
63 int32_t workId = GetIntProperty(env, objValue, "workId", E_WORKID_ERR);
64 if (workId == UNSET_INT_PARAM || workId < 0) {
65 WS_HILOGE("Work id is invalid, failed.");
66 HandleParamErr(env, E_WORKID_ERR);
67 return false;
68 }
69
70 // Get bundleName and abilityName.
71 std::string bundleName = GetStringProperty(env, objValue, "bundleName", E_BUNDLE_OR_ABILITY_NAME_ERR);
72 std::string abilityName = GetStringProperty(env, objValue, "abilityName", E_BUNDLE_OR_ABILITY_NAME_ERR);
73 if (bundleName == UNSET_STRING_PARAM || abilityName == UNSET_STRING_PARAM) {
74 WS_HILOGE("BundleName or abilityName is invalid, failed.");
75 HandleParamErr(env, E_BUNDLE_OR_ABILITY_NAME_ERR);
76 return false;
77 }
78
79 workInfo.SetWorkId(workId);
80 workInfo.SetElement(bundleName, abilityName);
81
82 // Get persist param. if not set, it will be used false.
83 workInfo.RequestPersisted(GetBoolProperty(env, objValue, "isPersisted", E_IS_PERSISTED_ERR));
84 return true;
85 }
86
GetNetWorkInfo(napi_env env,napi_value objValue,WorkInfo & workInfo)87 bool Common::GetNetWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo)
88 {
89 bool hasCondition = false;
90 int32_t networkType = GetIntProperty(env, objValue, "networkType", E_NETWORK_TYPE_ERR);
91 if (networkType == UNSET_INT_PARAM) {
92 WS_HILOGI("Unset networkType.");
93 } else if (networkType >= WorkCondition::Network::NETWORK_TYPE_ANY &&
94 networkType <= WorkCondition::Network::NETWORK_TYPE_ETHERNET) {
95 workInfo.RequestNetworkType(WorkCondition::Network(networkType));
96 hasCondition = true;
97 } else {
98 WS_HILOGE("NetworkType set is invalid, just ignore set.");
99 HandleParamErr(env, E_NETWORK_TYPE_ERR);
100 }
101 return hasCondition;
102 }
103
GetChargeInfo(napi_env env,napi_value objValue,WorkInfo & workInfo)104 bool Common::GetChargeInfo(napi_env env, napi_value objValue, WorkInfo &workInfo)
105 {
106 bool hasCondition = false;
107 int32_t isCharging = GetBoolToIntProperty(env, objValue, "isCharging", E_IS_CHARGING_ERR);
108 int32_t chargerType = GetIntProperty(env, objValue, "chargerType", E_CHARGER_TYPE_ERR);
109 if (isCharging == UNSET_INT_PARAM) {
110 WS_HILOGI("Unset isCharging, ignore ChargerType set also.");
111 } else if (isCharging == FALSE_PARAM) {
112 workInfo.RequestChargerType(false, WorkCondition::Charger::CHARGING_UNPLUGGED);
113 hasCondition = true;
114 } else {
115 if (chargerType == UNSET_INT_PARAM) {
116 workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGING_PLUGGED_ANY);
117 } else if (chargerType >= WorkCondition::Charger::CHARGING_PLUGGED_ANY &&
118 chargerType <= WorkCondition::Charger::CHARGING_PLUGGED_WIRELESS) {
119 workInfo.RequestChargerType(true, WorkCondition::Charger(chargerType));
120 } else {
121 workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGING_PLUGGED_ANY);
122 WS_HILOGE("ChargeType info is invalid, just ignore set.");
123 HandleParamErr(env, E_CHARGER_TYPE_ERR);
124 }
125 hasCondition = true;
126 }
127 return hasCondition;
128 }
129
GetBatteryInfo(napi_env env,napi_value objValue,WorkInfo & workInfo)130 bool Common::GetBatteryInfo(napi_env env, napi_value objValue, WorkInfo &workInfo)
131 {
132 bool hasCondition = false;
133 // Get battery level info.
134 int32_t batteryLevel = GetIntProperty(env, objValue, "batteryLevel", E_BATTERY_LEVEL_ERR);
135 if (batteryLevel == UNSET_INT_PARAM) {
136 WS_HILOGI("Unset batteryLevel.");
137 } else if (batteryLevel >= BATTERY_LEVEL_MIN && batteryLevel <= BATTERY_LEVEL_MAX) {
138 workInfo.RequestBatteryLevel(batteryLevel);
139 hasCondition = true;
140 } else {
141 WS_HILOGE("BatteryLevel set is invalid, just ignore set.");
142 HandleParamErr(env, E_BATTERY_LEVEL_ERR);
143 }
144
145 // Get battery status info.
146 int32_t batteryStatus = GetIntProperty(env, objValue, "batteryStatus", E_BATTERY_STATUS_ERR);
147 if (batteryStatus == UNSET_INT_PARAM) {
148 WS_HILOGI("Unset batteryStatus.");
149 } else if (batteryStatus >= WorkCondition::BatteryStatus::BATTERY_STATUS_LOW &&
150 batteryStatus <= WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY) {
151 workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus(batteryStatus));
152 hasCondition = true;
153 } else {
154 WS_HILOGE("BatteryStatus set is invalid, just ignore set.");
155 HandleParamErr(env, E_BATTERY_STATUS_ERR);
156 }
157 return hasCondition;
158 }
159
GetStorageInfo(napi_env env,napi_value objValue,WorkInfo & workInfo)160 bool Common::GetStorageInfo(napi_env env, napi_value objValue, WorkInfo &workInfo)
161 {
162 bool hasCondition = false;
163 int32_t storageRequest = GetIntProperty(env, objValue, "storageRequest", E_STORAGE_REQUEST_ERR);
164 if (storageRequest == UNSET_INT_PARAM) {
165 WS_HILOGI("Unset StorageRequest.");
166 } else if (storageRequest >= WorkCondition::Storage::STORAGE_LEVEL_LOW
167 && storageRequest <= WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY) {
168 workInfo.RequestStorageLevel(WorkCondition::Storage(storageRequest));
169 hasCondition = true;
170 } else {
171 WS_HILOGE("StorageRequest set is invalid, just ignore set.");
172 HandleParamErr(env, E_STORAGE_REQUEST_ERR);
173 }
174 return hasCondition;
175 }
176
GetRepeatInfo(napi_env env,napi_value objValue,WorkInfo & workInfo)177 bool Common::GetRepeatInfo(napi_env env, napi_value objValue, WorkInfo &workInfo)
178 {
179 int32_t repeatCycleTime = GetIntProperty(env, objValue, "repeatCycleTime", E_REPEAT_CYCLE_TIME_TYPE_ERR);
180 if (repeatCycleTime == UNSET_INT_PARAM) {
181 WS_HILOGI("RepeatCycleTime not set, just ignore other repeat set.");
182 return false;
183 }
184
185 bool isRepeat = GetBoolProperty(env, objValue, "isRepeat", E_IS_REPEAT_ERR);
186 int32_t repeatCount = GetIntProperty(env, objValue, "repeatCount", E_REPEAT_COUNT_ERR);
187 if (!isRepeat && repeatCount == UNSET_INT_PARAM) {
188 WS_HILOGI("Not set isRepeat or repeatCount, ignore.");
189 return false;
190 }
191 if (isRepeat) {
192 if (repeatCount > 0) {
193 WS_HILOGI("RepeatCount has been set , ignore isRepeat.");
194 workInfo.RequestRepeatCycle(repeatCycleTime, repeatCount);
195 } else {
196 workInfo.RequestRepeatCycle(repeatCycleTime);
197 }
198 return true;
199 } else {
200 if (repeatCount < 0) {
201 WS_HILOGE("RepeatCount is invalid, ignore.");
202 HandleParamErr(env, E_REPEAT_COUNT_ERR);
203 return false;
204 }
205 workInfo.RequestRepeatCycle(repeatCycleTime, repeatCount);
206 return true;
207 }
208 }
209
GetExtrasInfo(napi_env env,napi_value objValue,WorkInfo & workInfo)210 bool Common::GetExtrasInfo(napi_env env, napi_value objValue, WorkInfo &workInfo)
211 {
212 napi_value extras = nullptr;
213 napi_status getExtrasStatus = napi_get_named_property(env, objValue, "parameters", &extras);
214 if (getExtrasStatus != napi_ok) {
215 return true;
216 }
217 AAFwk::WantParams extraParams;
218 if (!UnwrapWantParams(env, extras, extraParams)) {
219 HandleParamErr(env, E_PARAMETERS_TYPE_ERR);
220 return false;
221 }
222 workInfo.RequestExtras(extraParams);
223 WS_HILOGD("Get parameters finished.");
224 return true;
225 }
226
227
GetWorkInfo(napi_env env,napi_value objValue,WorkInfo & workInfo)228 bool Common::GetWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo)
229 {
230 g_hasParamError = false;
231 // Get base info.
232 if (!GetBaseWorkInfo(env, objValue, workInfo)) {
233 return false;
234 }
235 // Get extra parameters.
236 if (!GetExtrasInfo(env, objValue, workInfo)) {
237 return false;
238 }
239
240 // Get condition info.
241 bool hasConditions = false;
242 if (GetNetWorkInfo(env, objValue, workInfo)) {
243 hasConditions = true;
244 }
245 if (GetChargeInfo(env, objValue, workInfo)) {
246 hasConditions = true;
247 }
248 if (GetBatteryInfo(env, objValue, workInfo)) {
249 hasConditions = true;
250 }
251 if (GetStorageInfo(env, objValue, workInfo)) {
252 hasConditions = true;
253 }
254 if (GetRepeatInfo(env, objValue, workInfo)) {
255 hasConditions = true;
256 }
257 // if param error occurs when get workInfo
258 if (g_hasParamError) {
259 return false;
260 }
261 if (!hasConditions) {
262 WS_HILOGE("Set none conditions, so fail to init WorkInfo.");
263 HandleParamErr(env, E_CONDITION_EMPTY);
264 return false;
265 }
266 return true;
267 }
268
GetIntProperty(napi_env env,napi_value object,const std::string & propertyName,ErrCode errCode)269 int32_t Common::GetIntProperty(napi_env env, napi_value object,
270 const std::string &propertyName, ErrCode errCode)
271 {
272 int32_t intValue = UNSET_INT_PARAM;
273 napi_value value = nullptr;
274 napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value);
275 if (getNameStatus != napi_ok) {
276 return intValue;
277 }
278 napi_valuetype valueType = napi_undefined;
279 napi_typeof(env, value, &valueType);
280 if (valueType == napi_undefined) {
281 WS_HILOGD("Unset %{public}s.", propertyName.c_str());
282 return intValue;
283 } else if (valueType != napi_number) {
284 WS_HILOGE("%{public}s type error, number expect.", propertyName.c_str());
285 HandleParamErr(env, errCode);
286 return intValue;
287 }
288 napi_get_value_int32(env, value, &intValue);
289 return intValue;
290 }
291
GetBoolProperty(napi_env env,napi_value object,const std::string & propertyName,ErrCode errCode)292 bool Common::GetBoolProperty(napi_env env, napi_value object,
293 const std::string &propertyName, ErrCode errCode)
294 {
295 bool boolValue = false;
296 napi_value value = nullptr;
297 napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value);
298 if (getNameStatus != napi_ok) {
299 return boolValue;
300 }
301 napi_valuetype valueType = napi_undefined;
302 napi_typeof(env, value, &valueType);
303 if (valueType == napi_undefined) {
304 WS_HILOGD("Unset %{public}s.", propertyName.c_str());
305 return boolValue;
306 } else if (valueType != napi_boolean) {
307 WS_HILOGE("%{public}s type error, boolean expect.", propertyName.c_str());
308 HandleParamErr(env, errCode);
309 return boolValue;
310 }
311 napi_get_value_bool(env, value, &boolValue);
312 return boolValue;
313 }
314
GetBoolToIntProperty(napi_env env,napi_value object,const std::string & propertyName,ErrCode errCode)315 int32_t Common::GetBoolToIntProperty(napi_env env, napi_value object,
316 const std::string &propertyName, ErrCode errCode)
317 {
318 bool boolValue = false;
319 napi_value value = nullptr;
320 napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value);
321 if (getNameStatus != napi_ok) {
322 return UNSET_INT_PARAM;
323 }
324 napi_valuetype valueType = napi_undefined;
325 napi_typeof(env, value, &valueType);
326 if (valueType == napi_undefined) {
327 WS_HILOGD("Unset %{public}s.", propertyName.c_str());
328 return UNSET_INT_PARAM;
329 } else if (valueType != napi_boolean) {
330 WS_HILOGE("%{public}s type error, boolean expect.", propertyName.c_str());
331 HandleParamErr(env, errCode);
332 return UNSET_INT_PARAM;
333 }
334 napi_status getIntStatus = napi_get_value_bool(env, value, &boolValue);
335 if (getIntStatus == napi_ok) {
336 return boolValue ? TRUE_PARAM : FALSE_PARAM;
337 }
338 return UNSET_INT_PARAM;
339 }
340
GetStringProperty(napi_env env,napi_value object,const std::string & propertyName,ErrCode errCode)341 std::string Common::GetStringProperty(napi_env env, napi_value object,
342 const std::string &propertyName, ErrCode errCode)
343 {
344 napi_value value = nullptr;
345 napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value);
346 if (getNameStatus != napi_ok) {
347 return UNSET_STRING_PARAM;
348 }
349 napi_valuetype valueType = napi_undefined;
350 napi_typeof(env, value, &valueType);
351 if (valueType == napi_undefined) {
352 WS_HILOGD("Unset %{public}s.", propertyName.c_str());
353 return UNSET_STRING_PARAM;
354 } else if (valueType != napi_string) {
355 WS_HILOGE("%{public}s type error, string expect.", propertyName.c_str());
356 HandleParamErr(env, errCode);
357 return UNSET_STRING_PARAM;
358 }
359 char chars[NAME_MAXIMUM_LIMIT] = {0};
360 size_t charLength = 0;
361 napi_status getStringStatus = napi_get_value_string_utf8(env, value, chars, NAME_MAXIMUM_LIMIT, &charLength);
362 if (getStringStatus == napi_ok && charLength > 0) {
363 return std::string(chars, charLength);
364 }
365 return UNSET_STRING_PARAM;
366 }
367
MatchValueType(napi_env env,napi_value value,napi_valuetype targetType)368 bool Common::MatchValueType(napi_env env, napi_value value, napi_valuetype targetType)
369 {
370 napi_valuetype valueType = napi_undefined;
371 napi_typeof(env, value, &valueType);
372 return valueType == targetType;
373 }
374
JSParaError(const napi_env & env,const napi_ref & callback)375 napi_value Common::JSParaError(const napi_env &env, const napi_ref &callback)
376 {
377 if (callback) {
378 return Common::NapiGetNull(env);
379 } else {
380 napi_value promise = nullptr;
381 napi_deferred deferred = nullptr;
382 napi_create_promise(env, &deferred, &promise);
383 napi_resolve_deferred(env, deferred, Common::NapiGetNull(env));
384 return promise;
385 }
386 }
387
PaddingAsyncWorkData(const napi_env & env,const napi_ref & callback,AsyncWorkData & info,napi_value & promise)388 void Common::PaddingAsyncWorkData(
389 const napi_env &env, const napi_ref &callback, AsyncWorkData &info, napi_value &promise)
390 {
391 if (callback) {
392 info.callback = callback;
393 info.isCallback = true;
394 } else {
395 napi_deferred deferred = nullptr;
396 NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise));
397 info.deferred = deferred;
398 info.isCallback = false;
399 }
400 }
401
GetNapiWorkInfo(napi_env env,std::shared_ptr<WorkInfo> & workInfo)402 napi_value Common::GetNapiWorkInfo(napi_env env, std::shared_ptr<WorkInfo> &workInfo)
403 {
404 if (workInfo == nullptr) {
405 return NapiGetNull(env);
406 }
407 napi_value napiWork = nullptr;
408 napi_create_object(env, &napiWork);
409
410 // Set base info.
411 napi_value napiWorkId = nullptr;
412 napi_value napiBundleName = nullptr;
413 napi_value napiAbilityName = nullptr;
414 napi_create_int32(env, workInfo->GetWorkId(), &napiWorkId);
415 napi_create_string_utf8(env, workInfo->GetBundleName().c_str(), workInfo->GetBundleName().length(),
416 &napiBundleName);
417 napi_create_string_utf8(env, workInfo->GetAbilityName().c_str(), workInfo->GetAbilityName().length(),
418 &napiAbilityName);
419 napi_set_named_property(env, napiWork, "workId", napiWorkId);
420 napi_set_named_property(env, napiWork, "bundleName", napiBundleName);
421 napi_set_named_property(env, napiWork, "abilityName", napiAbilityName);
422
423 // Set isPersisted.
424 napi_value napiIsPersisted = nullptr;
425 napi_get_boolean(env, workInfo->IsPersisted(), &napiIsPersisted);
426 napi_set_named_property(env, napiWork, "isPersisted", napiIsPersisted);
427
428 // Set net info.
429 if (workInfo->GetNetworkType() != WorkCondition::Network::NETWORK_UNKNOWN) {
430 napi_value napiNetworkType = nullptr;
431 napi_create_int32(env, static_cast<int32_t>(workInfo->GetNetworkType()), &napiNetworkType);
432 napi_set_named_property(env, napiWork, "networkType", napiNetworkType);
433 }
434
435 // Set charge info.
436 WorkCondition::Charger charger = workInfo-> GetChargerType();
437 if (charger != WorkCondition::Charger::CHARGING_UNKNOWN) {
438 napi_value napiIsCharging = nullptr;
439 if (charger == WorkCondition::Charger::CHARGING_UNPLUGGED) {
440 napi_get_boolean(env, false, &napiIsCharging);
441 napi_set_named_property(env, napiWork, "isCharging", napiIsCharging);
442 } else {
443 napi_get_boolean(env, true, &napiIsCharging);
444 napi_set_named_property(env, napiWork, "isCharging", napiIsCharging);
445 napi_value napiChargerType = nullptr;
446 napi_create_int32(env, static_cast<int32_t>(charger), &napiChargerType);
447 napi_set_named_property(env, napiWork, "chargerType", napiChargerType);
448 }
449 }
450
451 // Set batteryLevel info.
452 if (workInfo->GetBatteryLevel() >= 0) {
453 napi_value napiBatteryLevel = nullptr;
454 napi_create_int32(env, workInfo->GetBatteryLevel(), &napiBatteryLevel);
455 napi_set_named_property(env, napiWork, "batteryLevel", napiBatteryLevel);
456 }
457
458 // Set batteryStatus info.
459 if (workInfo->GetBatteryStatus() != WorkCondition::BatteryStatus::BATTERY_UNKNOWN) {
460 napi_value napiBatteryStatus = nullptr;
461 napi_create_int32(env, static_cast<int32_t>(workInfo->GetBatteryStatus()), &napiBatteryStatus);
462 napi_set_named_property(env, napiWork, "batteryStatus", napiBatteryStatus);
463 }
464
465 // Set storage info.
466 if (workInfo->GetStorageLevel() != WorkCondition::Storage::STORAGE_UNKNOWN) {
467 napi_value napiStorageRequest = nullptr;
468 napi_create_int32(env, static_cast<int32_t>(workInfo->GetStorageLevel()), &napiStorageRequest);
469 napi_set_named_property(env, napiWork, "storageRequest", napiStorageRequest);
470 }
471
472 // Set timer info.
473 uint32_t timeInterval = workInfo->GetTimeInterval();
474 if (timeInterval > 0) {
475 napi_value napiTimer = nullptr;
476 napi_create_int32(env, static_cast<int32_t>(timeInterval), &napiTimer);
477 napi_set_named_property(env, napiWork, "repeatCycleTime", napiTimer);
478 if (workInfo->IsRepeat()) {
479 napi_value napiIsRepeat = nullptr;
480 napi_get_boolean(env, true, &napiIsRepeat);
481 napi_set_named_property(env, napiWork, "isRepeat", napiIsRepeat);
482 } else {
483 napi_value napiCount = nullptr;
484 napi_create_int32(env, workInfo->GetCycleCount(), &napiCount);
485 napi_set_named_property(env, napiWork, "repeatCount", napiCount);
486 }
487 }
488
489 if (workInfo->GetExtras()) {
490 napi_value parameters = WrapWantParams(env, *workInfo->GetExtras());
491 napi_set_named_property(env, napiWork, "parameters", parameters);
492 }
493 return napiWork;
494 }
495
GetCallbackErrorValue(napi_env env,int32_t errCode,const std::string errMsg)496 napi_value Common::GetCallbackErrorValue(napi_env env, int32_t errCode, const std::string errMsg)
497 {
498 if (errCode == ERR_OK) {
499 return NapiGetNull(env);
500 }
501 napi_value error = nullptr;
502 napi_value eCode = nullptr;
503 napi_value eMsg = nullptr;
504 NAPI_CALL(env, napi_create_int32(env, errCode, &eCode));
505 NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(),
506 errMsg.length(), &eMsg));
507 NAPI_CALL(env, napi_create_object(env, &error));
508 NAPI_CALL(env, napi_set_named_property(env, error, "code", eCode));
509 NAPI_CALL(env, napi_set_named_property(env, error, "message", eMsg));
510 return error;
511 }
512
SetCallback(const napi_env & env,const napi_ref & callbackIn,int32_t errCode,const napi_value & result)513 void Common::SetCallback(
514 const napi_env &env, const napi_ref &callbackIn, int32_t errCode, const napi_value &result)
515 {
516 napi_value undefined = nullptr;
517 napi_get_undefined(env, &undefined);
518
519 napi_value callback = nullptr;
520 napi_value resultout = nullptr;
521 napi_get_reference_value(env, callbackIn, &callback);
522 napi_value results[RESULT_PARAMS_NUM] = {nullptr};
523 if (errCode == ERR_OK) {
524 results[0] = NapiGetNull(env);
525 } else {
526 std::string errMsg = FindErrMsg(env, errCode);
527 int32_t errCodeInfo = FindErrCode(env, errCode);
528 results[0] = GetCallbackErrorValue(env, errCodeInfo, errMsg);
529 }
530 results[1] = result;
531 NAPI_CALL_RETURN_VOID(env,
532 napi_call_function(env, undefined, callback, RESULT_PARAMS_NUM, &results[0], &resultout));
533 }
534
SetPromise(const napi_env & env,const AsyncWorkData & info,const napi_value & result)535 napi_value Common::SetPromise(
536 const napi_env &env, const AsyncWorkData &info, const napi_value &result)
537 {
538 if (info.errorCode == ERR_OK) {
539 napi_resolve_deferred(env, info.deferred, result);
540 } else {
541 int32_t errCodeInfo = FindErrCode(env, info.errorCode);
542 std::string errMsg = FindErrMsg(env, info.errorCode);
543 napi_value error = nullptr;
544 napi_value eCode = nullptr;
545 napi_value eMsg = nullptr;
546 NAPI_CALL(env, napi_create_int32(env, errCodeInfo, &eCode));
547 NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(),
548 errMsg.length(), &eMsg));
549 NAPI_CALL(env, napi_create_object(env, &error));
550 NAPI_CALL(env, napi_set_named_property(env, error, "data", eCode));
551 NAPI_CALL(env, napi_set_named_property(env, error, "code", eCode));
552 NAPI_CALL(env, napi_set_named_property(env, error, "message", eMsg));
553 napi_reject_deferred(env, info.deferred, error);
554 }
555 return result;
556 }
557
ReturnCallbackPromise(const napi_env & env,const AsyncWorkData & info,const napi_value & result)558 void Common::ReturnCallbackPromise(const napi_env &env, const AsyncWorkData &info, const napi_value &result)
559 {
560 if (info.isCallback) {
561 SetCallback(env, info.callback, info.errorCode, result);
562 } else {
563 SetPromise(env, info, result);
564 }
565 }
566
HandleErrCode(const napi_env & env,int32_t errCode)567 void Common::HandleErrCode(const napi_env &env, int32_t errCode)
568 {
569 WS_HILOGI("HandleErrCode errCode = %{public}d", errCode);
570 if (errCode == ERR_OK) {
571 return;
572 }
573 std::string errMsg = FindErrMsg(env, errCode);
574 int32_t errCodeInfo = FindErrCode(env, errCode);
575 if (errMsg != "") {
576 napi_throw_error(env, std::to_string(errCodeInfo).c_str(), errMsg.c_str());
577 }
578 }
579
HandleParamErr(const napi_env & env,int32_t errCode)580 void Common::HandleParamErr(const napi_env &env, int32_t errCode)
581 {
582 WS_HILOGI("HandleParamErr errCode = %{public}d", errCode);
583 if (errCode == ERR_OK) {
584 return;
585 }
586 auto iter = paramErrCodeMsgMap.find(errCode);
587 if (iter != paramErrCodeMsgMap.end()) {
588 std::string errMessage = "BussinessError 401: Parameter error. ";
589 errMessage.append(iter->second);
590 napi_throw_error(env, std::to_string(E_PARAM_ERROR).c_str(), errMessage.c_str());
591 g_hasParamError = true;
592 }
593 }
594
FindErrMsg(const napi_env & env,int32_t errCode)595 std::string Common::FindErrMsg(const napi_env &env, int32_t errCode)
596 {
597 if (errCode == ERR_OK) {
598 return "";
599 }
600 auto iter = saErrCodeMsgMap.find(errCode);
601 if (iter != saErrCodeMsgMap.end()) {
602 std::string errMessage = "BussinessError ";
603 int32_t errCodeInfo = FindErrCode(env, errCode);
604 errMessage.append(std::to_string(errCodeInfo)).append(": ").append(iter->second);
605 return errMessage;
606 }
607 iter = paramErrCodeMsgMap.find(errCode);
608 if (iter != paramErrCodeMsgMap.end()) {
609 std::string errMessage = "BussinessError 401: Parameter error. ";
610 errMessage.append(iter->second);
611 return errMessage;
612 }
613 return "Inner error.";
614 }
615
FindErrCode(const napi_env & env,int32_t errCodeIn)616 int32_t Common::FindErrCode(const napi_env &env, int32_t errCodeIn)
617 {
618 auto iter = paramErrCodeMsgMap.find(errCodeIn);
619 if (iter != paramErrCodeMsgMap.end()) {
620 return E_PARAM_ERROR;
621 }
622 return errCodeIn > THRESHOLD ? errCodeIn / OFFSET : errCodeIn;
623 }
624 } // namespace WorkScheduler
625 } // namespace OHOS