1/*
2 * Copyright (c) 2024 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"
17namespace OHOS {
18namespace HiviewDFX {
19
20napi_value CreateErrorMessage(napi_env env, const std::string& msg)
21{
22    napi_value result = nullptr;
23    napi_value message = nullptr;
24    napi_create_string_utf8(env, msg.data(), msg.size(), &message);
25    napi_create_error(env, nullptr, message, &result);
26    return result;
27}
28
29napi_value CreateErrorMessage(napi_env env, const std::string& errCode, const std::string& msg)
30{
31    napi_value result = nullptr;
32    napi_value message = nullptr;
33    napi_value code = nullptr;
34    napi_create_string_utf8(env, errCode.data(), errCode.size(), &code);
35    napi_create_string_utf8(env, msg.data(), msg.size(), &message);
36    napi_create_error(env, code, message, &result);
37    return result;
38}
39
40napi_value CreateUndefined(napi_env env)
41{
42    napi_value res = nullptr;
43    napi_get_undefined(env, &res);
44    return res;
45}
46
47bool AsyncTask::CreatePromise(napi_env env, napi_value &promise)
48{
49    if (napi_create_promise(env, &deferred_, &promise) != napi_ok) {
50        return false;
51    }
52    napi_value resourceName;
53    if (napi_create_string_utf8(env, resourceName_.c_str(), resourceName_.size(), &resourceName) != napi_ok) {
54        return false;
55    };
56    if (napi_create_async_work(env, nullptr, resourceName, ExecuteCallBack, CompletedCallBack,
57                               static_cast<void *>(this), &worker_) != napi_ok) {
58        return false;
59    }
60    return napi_queue_async_work(env, worker_) == napi_ok;
61}
62
63void AsyncTask::ExecuteCallBack(napi_env env, void* data)
64{
65    auto asyncTaskPtr = reinterpret_cast<AsyncTask *>(data);
66    asyncTaskPtr->Work(env);
67}
68
69void AsyncTask::CompletedCallBack(napi_env env, napi_status status, void* data)
70{
71    auto asyncTaskPtr = reinterpret_cast<AsyncTask *>(data);
72    asyncTaskPtr->Done(env, status);
73    napi_delete_async_work(env, asyncTaskPtr->worker_);
74    delete asyncTaskPtr;
75}
76} // namespace HiviewDFX
77} // namespace OHOS