82 lines
2.4 KiB
Zig
82 lines
2.4 KiB
Zig
const std = @import("std");
|
|
|
|
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: *Db) !void {
|
|
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
|
defer arena.deinit();
|
|
const allocator = arena.allocator();
|
|
|
|
var jret = json.Obj.newObject();
|
|
defer jret.deinit();
|
|
|
|
// Test the action to carry and pass the object
|
|
if (jobj.objectGet("add") catch null) |*jaction| {
|
|
var ret = try add(jaction, db, allocator);
|
|
jret.objectAdd("added", &ret);
|
|
}
|
|
|
|
if (jobj.objectGet("query") catch null) |*jaction| {
|
|
var ret = try query(jaction, db, allocator);
|
|
jret.objectAdd("queried", &ret);
|
|
}
|
|
|
|
std.debug.print("{s}", .{jret.toString()});
|
|
}
|
|
|
|
pub fn add(jobj: *json.Obj, db: *Db, allocator: std.mem.Allocator) !json.Obj {
|
|
// TODO: Maybe return error when no items in the array?
|
|
|
|
// Freed by the caller
|
|
var jret = json.Obj.newArray();
|
|
|
|
var iter = jobj.arrayGetIterator();
|
|
while (iter.next()) |*jtags| {
|
|
var item = Item{
|
|
.id = null,
|
|
.tags = try Item.tagsFromJson(jtags, allocator),
|
|
};
|
|
item.deinit();
|
|
|
|
// Insert new items into the DB
|
|
try item.persist(db, allocator);
|
|
|
|
// Add item to new json array (Makes a deep copy, freed with jret.deinit())
|
|
jret.arrayAdd(&item.toJson());
|
|
}
|
|
|
|
return jret;
|
|
}
|
|
|
|
pub fn query(jobj: *json.Obj, db: *Db, allocator: std.mem.Allocator) !json.Obj {
|
|
const query_str = jobj.getString();
|
|
var jret = json.Obj.newArray();
|
|
|
|
// Go through each tag
|
|
var iter = std.mem.split(u8, query_str, " ");
|
|
const opt_tag = iter.next();
|
|
|
|
if (opt_tag) |tag| {
|
|
// Get the tag selector: "tag:<tag>"
|
|
const tag_sel = try std.mem.concat(allocator, u8, &[_][]const u8{"tag:", tag});
|
|
defer allocator.free(tag_sel);
|
|
|
|
// Get the items that have that tag: "<item1> <item2> <item3>"
|
|
const tag_str = db.get(tag_sel) orelse return jret;
|
|
defer Db.free(tag_str.ptr);
|
|
|
|
// Iterate through the items id
|
|
var item_iter = std.mem.split(u8, tag_str, " ");
|
|
while (item_iter.next()) |item_id| {
|
|
const item = (try Item.getById(item_id, db, allocator)) orelse continue;
|
|
|
|
jret.arrayAdd(&item.toJson());
|
|
}
|
|
}
|
|
|
|
return jret;
|
|
}
|