view scid/crud.c @ 33:1d0ddf9e6efd

misc: general documentation
author David Demelier <markand@malikania.fr>
date Thu, 04 Aug 2022 16:47:10 +0200
parents 081e1c258e64
children 71cd8447e3a4
line wrap: on
line source

/*
 * crud.c -- convenient helpers for page-api-*
 *
 * Copyright (c) 2021-2022 David Demelier <markand@malikania.fr>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <assert.h>

#include "crud.h"
#include "log.h"
#include "pageutil.h"

static int
save(struct kreq *r, int (*saver)(json_t *), const char *topic)
{
	json_t *doc;
	json_error_t err;
	int ret = -1;

	if (!(doc = json_loads(r->fields[0].val, 0, &err)))
		log_warn("crud: %s: invalid JSON input: %s", topic, err.text);
	else {
		if (saver(doc) < 0)
			log_warn("crud: %s: database insertion failed", topic);
		else
			ret = 0;

		json_decref(doc);
	}

	return ret;
}

void
crud_insert(struct kreq *r, int (*saver)(json_t *), const char *topic)
{
	assert(r);
	assert(saver);
	assert(topic);

	if (r->fieldsz < 1)
		pageutil_json(r, KHTTP_400, NULL);
	else if (save(r, saver, topic) < 0)
		pageutil_json(r, KHTTP_500, NULL);
	else
		/* TODO: Maybe we should send the updated model. */
		pageutil_json(r, KHTTP_200, NULL);
}

void
crud_list(struct kreq *r, json_t *doc)
{
	assert(r);

	if (!doc)
		pageutil_json(r, KHTTP_500, NULL);
	else
		pageutil_json(r, KHTTP_200, doc);
}