Created
April 23, 2020 22:44
-
-
Save sfpgmr/7da1f0d6081ccd3156662a02a76662c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <class T> | |
constexpr bool is_string(){ | |
return std::is_same<char *, typename std::decay< T >::type >::value | |
|| std::is_same< const char *, typename std::decay< T >::type >::value | |
|| std::is_same<std::string, typename std::decay<T>::type>::value; | |
}; | |
template<typename FuncType = std::function<int()>,bool IsReturnValue = false> | |
class FuncWorker : public Napi::AsyncWorker | |
{ | |
public: | |
FuncWorker(Statement &stmt, Napi::Env env, Napi::Promise::Deferred *deferred, FuncType &executeFunc) | |
: AsyncWorker(env), stmt_(stmt), deferred_(deferred), executeFunc_(executeFunc) | |
{ | |
} | |
virtual ~FuncWorker() | |
{ | |
} | |
void Execute() override | |
{ | |
result_ = executeFunc_(); | |
//int status =SQLITE_OK; | |
if constexpr (!IsReturnValue){ | |
if (result_ != SQLITE_OK && result_ != SQLITE_DONE) | |
{ | |
std::string errorMessage(sqlite3_errmsg(const_cast<sqlite3 *>(stmt_.db().handle()))); | |
SetError("Error:" + errorMessage); | |
return; | |
} | |
} | |
} | |
void OnOK() override | |
{ | |
if constexpr (is_string<typename FuncType::result_type>()){ | |
deferred_->Resolve(Napi::String::New(Env(),result_)); | |
} else if constexpr (std::is_arithmetic<typename FuncType::result_type>::value){ | |
deferred_->Resolve(Napi::Number::New(Env(),result_)); | |
} | |
} | |
void OnError(Napi::Error const &error) override | |
{ | |
deferred_->Reject(error.Value()); | |
} | |
private: | |
Statement &stmt_; | |
std::unique_ptr<Napi::Promise::Deferred> deferred_; | |
FuncType executeFunc_; | |
typename FuncType::result_type result_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment