093d59149b6bebd17a97aaca8db6d87c5449717b
[apps/agl-service-data-persistence.git] / ll-database-binding / src / utils.h
1 /*
2 * Copyright 2017 IoT.bzh
3 *
4 * author: Loïc Collignon <loic.collignon@iot.bzh>
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #ifndef _BINDING_UTILS_H_
20 #define _BINDING_UTILS_H_
21
22 #include <string.h>
23 #include <json-c/json.h>
24
25 #ifndef AFB_BINDING_VERSION
26 #define AFB_BINDING_VERSION 2
27 #endif
28 #include <afb/afb-binding.h>
29
30 #define REGISTER_VERB(n, a, i, s) { .verb = #n, .callback = verb_##n, .auth = a, .info = i, .session = s }
31
32 /**
33  * @brief Get a string from a json object.
34  * @param[in] obj Json object from wich the string is queried.
35  * @param[in] name Name of the string to get.
36  * @return The string value.
37  */
38 static inline const char* get_json_string(struct json_object* obj, const char* name)
39 {
40         struct json_object* item = NULL;
41         if (!obj || !name || !strlen(name)) return NULL;
42         if (!json_object_object_get_ex(obj, name, &item) || !item) return NULL;
43         return json_object_get_string(item);
44 }
45
46 /**
47  * @brief Add a string key/value to a json object.
48  * @param[in] obj The json object to which the key/value is added.
49  * @param[in] key The key to add.
50  * @param[in] value The value to add.
51  */
52 static inline void json_object_add_string(struct json_object* obj, const char* key, const char* value)
53 {
54         json_object_object_add(obj, key, json_object_new_string(value));
55 }
56
57 /**
58  * @brief Send an @c event with the specified @c message then fail with the same @c message.
59  * @param[in] req The query to fail.
60  * @param[in] event The event to push.
61  * @param[in] message The message to push with the event and use as a fail message.
62  */
63 static inline void afb_fail_ex(struct afb_req req, struct afb_event event, const char* message)
64 {
65         struct json_object* result = json_object_new_object();
66         json_object_add_string(result, "message", message);
67         afb_event_push(event, result);
68         
69         afb_req_fail(req, message, NULL);
70 }
71
72 #endif // _BINDING_UTILS_H_