comparison page-api-projects.c @ 3:215c0c3b3609

misc: use JSON everywhere (scictl/sciwebd)
author David Demelier <markand@malikania.fr>
date Mon, 14 Jun 2021 22:08:24 +0200
parents
children 3051ef92173a
comparison
equal deleted inserted replaced
2:5fa3d2f479b2 3:215c0c3b3609
1 #include <assert.h>
2
3 #include "config.h"
4 #include "page-api-projects.h"
5 #include "page.h"
6 #include "req.h"
7 #include "types.h"
8 #include "util.h"
9
10 static void
11 list(struct kreq *r, const struct project *projects, size_t projectsz)
12 {
13 struct json_t *doc;
14 char *dump;
15
16 doc = project_to(projects, projectsz);
17 dump = json_dumps(doc, JSON_COMPACT);
18
19 khttp_puts(r, dump);
20 free(dump);
21 json_decref(doc);
22 }
23
24 static void
25 push(struct kreq *r, const struct project *p)
26 {
27 struct json_t *json;
28 char *dump;
29
30 json = project_to(p, 1);
31 dump = json_dumps(json, JSON_COMPACT);
32
33 khttp_head(r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME_APP_JSON]);
34 khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
35 khttp_body(r);
36 khttp_puts(r, dump);
37 khttp_free(r);
38
39 free(dump);
40 json_decref(json);
41 }
42
43 static void
44 get_one(struct kreq *r, const char *name)
45 {
46 struct project project;
47 struct req req;
48
49 if ((req = req_project_find(&project, name)).status)
50 page(r, NULL, KHTTP_500, KMIME_APP_JSON, NULL);
51 else
52 push(r, &project);
53 }
54
55 static void
56 get_one_id(struct kreq *r, int id)
57 {
58 struct project project;
59 struct req req;
60
61 if ((req = req_project_find_id(&project, id)).status)
62 page(r, NULL, KHTTP_500, KMIME_APP_JSON, NULL);
63 else
64 push(r, &project);
65 }
66
67 static void
68 get_all(struct kreq *r)
69 {
70 struct project projects[SCI_PROJECT_MAX];
71 struct req req;
72 size_t projectsz = UTIL_SIZE(projects);
73
74 if ((req = req_project_list(projects, &projectsz)).status)
75 page(r, NULL, KHTTP_500, KMIME_APP_JSON, NULL);
76 else {
77 khttp_head(r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME_APP_JSON]);
78 khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
79 khttp_body(r);
80 list(r, projects, projectsz);
81 req_finish(&req);
82 khttp_free(r);
83 }
84 }
85
86 static void
87 get(struct kreq *r)
88 {
89 char name[128];
90 int id;
91
92 if (sscanf(r->path, "v1/projects/%d", &id) == 1)
93 get_one_id(r, id);
94 else if (sscanf(r->path, "v1/projects/%127s", name) == 1)
95 get_one(r, name);
96 else
97 get_all(r);
98 }
99
100 void
101 page_api_v1_projects(struct kreq *r)
102 {
103 assert(r);
104
105 switch (r->method) {
106 case KMETHOD_GET:
107 get(r);
108 break;
109 #if 0
110 case KMETHOD_POST:
111 post(r);
112 break;
113 #endif
114 default:
115 page(r, NULL, KHTTP_400, KMIME_APP_JSON, NULL);
116 break;
117 }
118 }