Move into Item the json serialization

This commit is contained in:
Dendy 2022-10-21 20:38:16 +02:00
parent 91df4c50d4
commit 0189c82ccf
3 changed files with 31 additions and 18 deletions

View File

@ -2,6 +2,7 @@ const std = @import("std");
const sqlite = @import("sqlite");
// TODO: Make DB an object so we can just do Self.
// TODO: Wrap into transactions with a .flush() method
const ObjectError = error{
IncompatibleObjectType, // No ?u32 "id" field

View File

@ -1,6 +1,9 @@
const std = @import("std");
const json = @import("json.zig");
const Db = @import("Db.zig");
const sqlite = @import("sqlite");
const Self = @This();
pub const Tag = struct{
@ -52,3 +55,28 @@ pub fn persist(self: *Self, db: *sqlite.Db) !void {
}
}
/// Convert into a JSON object. A call to deinit() is necessary from the caller's side
pub fn toJson(self: Self) json.Obj {
var jobj = json.Obj.newObject();
jobj.objectAdd("id", &json.Obj.newInt64(self.id.?));
var jtags = json.Obj.newObject();
jobj.objectAdd("tags", &jtags);
// If there are tags there's no point on continuing
if (self.tags) |tags| {
for (tags) |tag_i| {
const jtag = if (tag_i.value) |value|
&json.Obj.newString(value)
else
null;
jtags.objectAdd(tag_i.name, jtag);
}
}
return jobj;
}

View File

@ -1,7 +1,6 @@
const std = @import("std");
const sqlite = @import("sqlite");
const json = @import("json.zig");
const Db = @import("Db.zig");
const Item = @import("Item.zig");
const Tag = @import("Tag.zig");
@ -22,24 +21,9 @@ pub fn main() !void {
try item.persist(&db);
var jobj = json.Obj.newObject();
jobj.objectAdd("id", &json.Obj.newInt64(item.id.?));
var jtags = json.Obj.newObject();
jobj.objectAdd("tags", &jtags);
for (tags) |tag_i| {
const jtag = if (tag_i.value) |value|
&json.Obj.newString(value)
else
null;
jtags.objectAdd(tag_i.name, jtag);
}
var jobj = item.toJson();
defer jobj.deinit();
_ = alloc;
std.debug.print("{s}\n", .{jobj.toString()});