1 | // Copyright (C) 2024 The Qt Company Ltd. |
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only |
3 | |
4 | #include <QtGrpcQuick/qqmlgrpcfunctionalhandlers.h> |
5 | |
6 | QT_BEGIN_NAMESPACE |
7 | |
8 | namespace QtGrpcQuickFunctional { |
9 | |
10 | void handleDeserializationError(QJSEngine *jsEngine, const QJSValue &errorCallback) |
11 | { |
12 | if (!errorCallback.isCallable()) |
13 | return; |
14 | using StatusCode = QtGrpc::StatusCode; |
15 | const auto status = QGrpcStatus{ StatusCode::InvalidArgument, |
16 | "Unable to deserialize return value" }; |
17 | errorCallback.call(args: QJSValueList{ jsEngine->toScriptValue(value: status) }); |
18 | } |
19 | |
20 | bool checkReceivedStatus(QJSEngine *jsEngine, const QGrpcStatus &status, |
21 | const QJSValue &errorCallback) |
22 | { |
23 | Q_ASSERT(jsEngine != nullptr); |
24 | |
25 | if (status.isOk()) |
26 | return true; |
27 | |
28 | if (errorCallback.isCallable()) |
29 | errorCallback.call(args: QJSValueList{ jsEngine->toScriptValue(value: status) }); |
30 | return false; |
31 | } |
32 | |
33 | void connectMultipleReceiveOperationFinished(QJSEngine *jsEngine, |
34 | std::unique_ptr<QGrpcOperation> &&operation, |
35 | const QJSValue &successCallback, |
36 | const QJSValue &errorCallback) |
37 | { |
38 | auto *operationPtr = operation.get(); |
39 | QtGrpcQuickFunctional::validateEngineAndOperation(jsEngine, operation: operationPtr); |
40 | |
41 | auto finishConnection = std::make_shared<QMetaObject::Connection>(); |
42 | *finishConnection = QObject::connect(sender: operationPtr, signal: &QGrpcOperation::finished, context: jsEngine, |
43 | slot: [successCallback, errorCallback, jsEngine, |
44 | finishConnection, |
45 | operation = std::move(operation)](const QGrpcStatus |
46 | &status) { |
47 | // We take 'operation' by copy so that its lifetime |
48 | // is extended until this lambda is destroyed. |
49 | if (QtGrpcQuickFunctional:: |
50 | checkReceivedStatus(jsEngine, status, |
51 | errorCallback) |
52 | && successCallback.isCallable()) { |
53 | successCallback.call(); |
54 | } |
55 | QObject::disconnect(*finishConnection); |
56 | }); |
57 | } |
58 | |
59 | void handleReceivedMessageImpl(QJSEngine *jsEngine, std::optional<QJSValue> message, |
60 | const QJSValue &successCallback, const QJSValue &errorCallback) |
61 | { |
62 | if (!successCallback.isCallable()) |
63 | return; |
64 | |
65 | if (message) |
66 | successCallback.call(args: QJSValueList{ *message }); |
67 | else |
68 | QtGrpcQuickFunctional::handleDeserializationError(jsEngine, errorCallback); |
69 | } |
70 | |
71 | } // namespace QtGrpcQuickFunctional |
72 | |
73 | QT_END_NAMESPACE |
74 | |