mgtzm/src/request.zig

49 lines
1.3 KiB
Zig
Raw Normal View History

2022-10-27 00:54:00 +00:00
const std = @import("std");
const sqlite = @import("sqlite");
const Db = @import("Db.zig");
const Item = @import("Item.zig");
const Tag = @import("Tag.zig");
const json = @import("json.zig");
pub fn process(jobj: *json.Obj, db: *sqlite.Db) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
2022-10-27 01:33:47 +00:00
var jret = json.Obj.newObject();
defer jret.deinit();
2022-10-27 00:54:00 +00:00
// Test the action to carry and pass the object
if (jobj.objectGet("add") catch null) |*jadd| {
2022-10-27 01:33:47 +00:00
var ret = try add(jadd, db, allocator);
jret.objectAdd("added", &ret);
2022-10-27 00:54:00 +00:00
}
2022-10-27 01:33:47 +00:00
std.debug.print("{s}", .{ jret.toString() });
2022-10-27 00:54:00 +00:00
}
2022-10-27 01:33:47 +00:00
pub fn add(jobj: *json.Obj, db: *sqlite.Db, allocator: std.mem.Allocator) !json.Obj {
2022-10-27 00:54:00 +00:00
// TODO: Maybe return error when no items in the array?
2022-10-27 01:33:47 +00:00
// Freed by the caller
2022-10-27 01:26:14 +00:00
var jret = json.Obj.newArray();
2022-10-27 00:54:00 +00:00
var iter = jobj.arrayGetIterator();
while(iter.next()) |*jtags| {
var item = Item {
.id = null,
.tags = try Item.tagsFromJson(jtags, allocator),
};
2022-10-27 01:26:14 +00:00
item.deinit();
2022-10-27 00:54:00 +00:00
2022-10-27 01:26:14 +00:00
// Insert new items into the DB
2022-10-27 00:54:00 +00:00
try item.persist(db);
2022-10-27 01:26:14 +00:00
// Add item to new json array (Makes a deep copy, freed with jret.deinit())
jret.arrayAdd(&item.toJson());
2022-10-27 00:54:00 +00:00
}
2022-10-27 01:26:14 +00:00
2022-10-27 01:33:47 +00:00
return jret;
2022-10-27 00:54:00 +00:00
}