1 /*
2 * Copyright (c) 2021 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 "close.h"
17
18 #include <cstring>
19 #include <tuple>
20 #include <unistd.h>
21
22 #include "../../common/napi/n_async/n_async_work_callback.h"
23 #include "../../common/napi/n_async/n_async_work_promise.h"
24 #include "../../common/napi/n_func_arg.h"
25 namespace OHOS {
26 namespace DistributedFS {
27 namespace ModuleFileIO {
28 using namespace std;
29
Sync(napi_env env,napi_callback_info info)30 napi_value Close::Sync(napi_env env, napi_callback_info info)
31 {
32 NFuncArg funcArg(env, info);
33 if (!funcArg.InitArgs(NARG_CNT::ONE)) {
34 UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched");
35 return nullptr;
36 }
37
38 auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32();
39 if (!resGetFirstArg || fd < 0) {
40 UniError(EINVAL).ThrowErr(env, "Invalid fd");
41 return nullptr;
42 }
43
44 if (close(fd) == -1) {
45 UniError(errno).ThrowErr(env);
46 return nullptr;
47 }
48
49 return NVal::CreateUndefined(env).val_;
50 }
51
Async(napi_env env,napi_callback_info info)52 napi_value Close::Async(napi_env env, napi_callback_info info)
53 {
54 NFuncArg funcArg(env, info);
55 if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) {
56 UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched");
57 return nullptr;
58 }
59
60 auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32();
61 if (!resGetFirstArg || fd < 0) {
62 UniError(EINVAL).ThrowErr(env, "Invalid fd");
63 return nullptr;
64 }
65
66 auto cbExec = [fd = fd](napi_env env) -> UniError {
67 int ret = close(fd);
68 if (ret == -1) {
69 return UniError(errno);
70 } else {
71 return UniError(ERRNO_NOERR);
72 }
73 };
74
75 auto cbComplete = [](napi_env env, UniError err) -> NVal {
76 if (err) {
77 return { env, err.GetNapiErr(env) };
78 } else {
79 return NVal::CreateUndefined(env);
80 }
81 };
82
83 const string procedureName = "FileIOClose";
84 size_t argc = funcArg.GetArgc();
85 NVal thisVar(env, funcArg.GetThisVar());
86 if (argc == NARG_CNT::ONE) {
87 return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_;
88 } else {
89 NVal cb(env, funcArg[NARG_POS::SECOND]);
90 return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_;
91 }
92 }
93 } // namespace ModuleFileIO
94 } // namespace DistributedFS
95 } // namespace OHOS