comparison scid/page-api-jobresults.c @ 24:34cbbd215ef7

misc: add basic support for jobresults
author David Demelier <markand@malikania.fr>
date Mon, 25 Jul 2022 21:11:23 +0200
parents
children 7e10cace67a3
comparison
equal deleted inserted replaced
23:2cb228f23f53 24:34cbbd215ef7
1 /*
2 * page-api-jobresults.c -- /api/v?/jobresults route
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 <sys/types.h>
20 #include <assert.h>
21 #include <stdarg.h>
22 #include <stdint.h>
23 #include <kcgi.h>
24
25 #include "db.h"
26 #include "log.h"
27 #include "page.h"
28 #include "types.h"
29
30 static int
31 save(const char *json)
32 {
33 struct jobresult res = {0};
34 int ret = -1;
35
36 json_t *doc;
37 json_error_t err;
38
39 if (!(doc = json_loads(json, 0, &err)))
40 log_warn("api/post: invalid JSON input: %s", err.text);
41 else if (jobresult_from(&res, 1, doc) < 0)
42 log_warn("api/post: failed to decode parameters");
43 else if (db_jobresult_add(&res) < 0)
44 log_warn("api/post: database save error");
45 else
46 ret = 0;
47
48 json_decref(doc);
49 jobresult_finish(&res);
50
51 return ret;
52 }
53
54 static void
55 post(struct kreq *r)
56 {
57 if (r->fieldsz < 1)
58 page(r, NULL, KHTTP_400, KMIME_APP_JSON, NULL);
59 else if (save(r->fields[0].val) < 0)
60 page(r, NULL, KHTTP_500, KMIME_APP_JSON, NULL);
61 else {
62 khttp_head(r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME_APP_JSON]);
63 khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
64 khttp_body(r);
65 khttp_free(r);
66 }
67 }
68
69 void
70 page_api_v1_jobresults(struct kreq *r)
71 {
72 assert(r);
73
74 switch (r->method) {
75 case KMETHOD_POST:
76 post(r);
77 break;
78 default:
79 page(r, NULL, KHTTP_400, KMIME_APP_JSON, NULL);
80 break;
81 }
82 }