Mercurial > sci
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/page-api-projects.c Mon Jun 14 22:08:24 2021 +0200 @@ -0,0 +1,118 @@ +#include <assert.h> + +#include "config.h" +#include "page-api-projects.h" +#include "page.h" +#include "req.h" +#include "types.h" +#include "util.h" + +static void +list(struct kreq *r, const struct project *projects, size_t projectsz) +{ + struct json_t *doc; + char *dump; + + doc = project_to(projects, projectsz); + dump = json_dumps(doc, JSON_COMPACT); + + khttp_puts(r, dump); + free(dump); + json_decref(doc); +} + +static void +push(struct kreq *r, const struct project *p) +{ + struct json_t *json; + char *dump; + + json = project_to(p, 1); + dump = json_dumps(json, JSON_COMPACT); + + khttp_head(r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME_APP_JSON]); + khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]); + khttp_body(r); + khttp_puts(r, dump); + khttp_free(r); + + free(dump); + json_decref(json); +} + +static void +get_one(struct kreq *r, const char *name) +{ + struct project project; + struct req req; + + if ((req = req_project_find(&project, name)).status) + page(r, NULL, KHTTP_500, KMIME_APP_JSON, NULL); + else + push(r, &project); +} + +static void +get_one_id(struct kreq *r, int id) +{ + struct project project; + struct req req; + + if ((req = req_project_find_id(&project, id)).status) + page(r, NULL, KHTTP_500, KMIME_APP_JSON, NULL); + else + push(r, &project); +} + +static void +get_all(struct kreq *r) +{ + struct project projects[SCI_PROJECT_MAX]; + struct req req; + size_t projectsz = UTIL_SIZE(projects); + + if ((req = req_project_list(projects, &projectsz)).status) + page(r, NULL, KHTTP_500, KMIME_APP_JSON, NULL); + else { + khttp_head(r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME_APP_JSON]); + khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]); + khttp_body(r); + list(r, projects, projectsz); + req_finish(&req); + khttp_free(r); + } +} + +static void +get(struct kreq *r) +{ + char name[128]; + int id; + + if (sscanf(r->path, "v1/projects/%d", &id) == 1) + get_one_id(r, id); + else if (sscanf(r->path, "v1/projects/%127s", name) == 1) + get_one(r, name); + else + get_all(r); +} + +void +page_api_v1_projects(struct kreq *r) +{ + assert(r); + + switch (r->method) { + case KMETHOD_GET: + get(r); + break; +#if 0 + case KMETHOD_POST: + post(r); + break; +#endif + default: + page(r, NULL, KHTTP_400, KMIME_APP_JSON, NULL); + break; + } +}