comparison scid/crud.c @ 27:dae2de19ca5d

misc: switch to JSON everywhere
author David Demelier <markand@malikania.fr>
date Wed, 03 Aug 2022 15:18:09 +0200
parents
children 695637f1d8a7
comparison
equal deleted inserted replaced
26:7e10cace67a3 27:dae2de19ca5d
1 /*
2 * crud.c -- convenient helpers for page-api-*
3 *
4 * Copyright (c) 2021 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include "log.h"
20 #include "page.h"
21
22 static int
23 save(struct kreq *r, int (*saver)(json_t *), const char *topic)
24 {
25 json_t *doc;
26 json_error_t err;
27 int ret = -1;
28
29 if (!(doc = json_loads(r->fields[0].val, 0, &err)))
30 log_warn("%s: invalid JSON input: %s", topic, err.text);
31 else {
32 if (saver(doc) < 0)
33 log_warn("%s: database insertion failed", topic);
34 else
35 ret = 0;
36
37 json_decref(doc);
38 }
39
40 return ret;
41 }
42
43 void
44 crud_insert(struct kreq *r, int (*saver)(json_t *), const char *topic)
45 {
46 if (r->fieldsz < 1)
47 page(r, KHTTP_400, KMIME_APP_JSON, NULL, NULL);
48 else if (save(r, saver, topic) < 0)
49 page(r, KHTTP_500, KMIME_APP_JSON, NULL, NULL);
50 else {
51 khttp_head(r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME_APP_JSON]);
52 khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
53 khttp_body(r);
54 khttp_free(r);
55 }
56 }
57
58 void
59 crud_list(struct kreq *r, json_t *doc)
60 {
61 char *str;
62
63 if (!doc)
64 page(r, KHTTP_500, KMIME_APP_JSON, NULL, NULL);
65 else {
66 if (!(str = json_dumps(doc, JSON_COMPACT)))
67 page(r, KHTTP_500, KMIME_APP_JSON, NULL, NULL);
68 else {
69 khttp_head(r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME_APP_JSON]);
70 khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
71 khttp_body(r);
72 khttp_printf(r, "%s", str);
73 khttp_free(r);
74 json_decref(doc);
75 }
76
77 free(str);
78 }
79 }