int valid_response(struct lh_table *body_top_level) { struct lh_entry *success, *error_message; success = lh_table_lookup_entry(body_top_level, "success"); if(((int)json_object_get_boolean((struct json_object *) success->v)) != 1) { error_message = lh_table_lookup_entry(body_top_level, "message"); fprintf(stderr, "ERROR: Response from server: %s\n", json_object_get_string((struct json_object *) error_message->v)); return 1; } return 0; }
json_bool lh_table_lookup_ex(struct lh_table* t, const void* k, void **v) { struct lh_entry *e = lh_table_lookup_entry(t, k); if (e != NULL) { if (v != NULL) *v = (void *)e->v; return TRUE; /* key found */ } if (v != NULL) *v = NULL; return FALSE; /* key not found */ }
int lh_table_delete(struct lh_table *t, const void *k) { struct lh_entry *e = lh_table_lookup_entry(t, k); if(!e) return -1; return lh_table_delete_entry(t, e); }
const void* lh_table_lookup(struct lh_table *t, const void *k) { struct lh_entry *e = lh_table_lookup_entry(t, k); if(e) return e->v; return NULL; }
int request_search(char *query, char **suggestion, struct egg **found) { int i = 0; json_object *body; // json post body struct lh_table *response_body_lookup; struct lh_table *results; struct array_list *eggs; struct lh_table *tmp; struct egg *egg_tmp = NULL; /* url to test site */ char *url = "http://192.168.1.7:3000/api/search"; *found = NULL; /* create json object for post */ body = json_object_new_object(); /* build post data */ json_object_object_add(body, "query", json_object_new_string(query)); if(json_request("POST", url, &body) != 0) return 1; response_body_lookup = json_object_get_object(body); if(valid_response(response_body_lookup) != 0) return 1; results = json_object_get_object( (struct json_object *) lh_table_lookup_entry(response_body_lookup, "result")->v ); *suggestion = (char *) json_object_get_string( (struct json_object *) lh_table_lookup_entry(results, "suggestion")->v ); eggs = json_object_get_array( (struct json_object *) lh_table_lookup_entry(results, "eggs")->v ); for(i=eggs->length-1; i >= 0; i--) { if(*found == NULL) { *found = (struct egg *)malloc(sizeof(struct egg)); (*found)->next = NULL; } else { egg_tmp = (struct egg *)malloc(sizeof(struct egg)); egg_tmp->next = *found; *found = egg_tmp; } tmp = json_object_get_object( (struct json_object *) array_list_get_idx(eggs, i) ); (*found)->name = (char *) json_object_get_string( (struct json_object *) lh_table_lookup_entry( tmp, "name" )->v ); (*found)->description = (char *) json_object_get_string( (struct json_object *) lh_table_lookup_entry( tmp, "description" )->v ); } return 0; }