From 0189c82ccf11828e89b03408e72700c60bc87171 Mon Sep 17 00:00:00 2001 From: Dendy Date: Fri, 21 Oct 2022 20:38:16 +0200 Subject: [PATCH] Move into Item the json serialization --- src/Db.zig | 1 + src/Item.zig | 28 ++++++++++++++++++++++++++++ src/main.zig | 20 ++------------------ 3 files changed, 31 insertions(+), 18 deletions(-) diff --git a/src/Db.zig b/src/Db.zig index aa96b4c..8b3a6e3 100644 --- a/src/Db.zig +++ b/src/Db.zig @@ -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 diff --git a/src/Item.zig b/src/Item.zig index 60187d2..4873e13 100644 --- a/src/Item.zig +++ b/src/Item.zig @@ -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; +} diff --git a/src/main.zig b/src/main.zig index 3211745..df72db0 100644 --- a/src/main.zig +++ b/src/main.zig @@ -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()});