Files
Calendink/Provider/main/api/users/update.cpp

69 lines
1.9 KiB
C++

// POST /api/users/update — Update an existing user's name
// Body: {"id": 1, "name": "Bob"}
#include "cJSON.h"
#include "esp_http_server.h"
#include "api/users/store.hpp"
#include "types.hpp"
#include "user.hpp"
internal esp_err_t api_users_update_handler(httpd_req_t *req)
{
httpd_resp_set_type(req, "application/json");
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
char buf[128];
int received = httpd_req_recv(req, buf, sizeof(buf) - 1);
if (received <= 0)
{
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Empty body");
return ESP_FAIL;
}
buf[received] = '\0';
cJSON *body = cJSON_Parse(buf);
if (!body)
{
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
return ESP_FAIL;
}
cJSON *id_item = cJSON_GetObjectItem(body, "id");
cJSON *name_item = cJSON_GetObjectItem(body, "name");
if (!cJSON_IsNumber(id_item) || !cJSON_IsString(name_item) ||
strlen(name_item->valuestring) == 0)
{
cJSON_Delete(body);
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing 'id' or 'name'");
return ESP_FAIL;
}
user_t *user = update_user((uint8)id_item->valueint, name_item->valuestring);
cJSON_Delete(body);
if (!user)
{
httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "User not found");
return ESP_FAIL;
}
cJSON *resp = cJSON_CreateObject();
cJSON_AddStringToObject(resp, "status", "ok");
const char *json = cJSON_PrintUnformatted(resp);
httpd_resp_sendstr(req, json);
free((void *)json);
cJSON_Delete(resp);
return ESP_OK;
}
internal const httpd_uri_t api_users_update_uri = {.uri = "/api/users/update",
.method = HTTP_POST,
.handler =
api_users_update_handler,
.user_ctx = NULL};