Set id when creating Item from JSON

This commit is contained in:
Dendy 2022-10-24 00:10:48 +02:00
parent 3032957071
commit 52a626fe12
2 changed files with 19 additions and 3 deletions

View File

@ -91,11 +91,12 @@ pub fn fromJson(jobj: json.Obj, allocator: std.mem.Allocator) !Self {
// Try to assemble a Item object from a JSON string
// An item could be just an id, just tags or both.
var opt_jtags = jobj.objectGet("tags") catch null;
var tags: ?[]Tag = null;
if (opt_jtags) |*jtags| {
if (jobj.objectGet("tags") catch null) |*jtags| {
defer jtags.deinit();
// Reserve space for slice of tags
const len = @intCast(usize, jtags.objectLen());
tags = try allocator.alloc(Tag, len);
@ -111,8 +112,19 @@ pub fn fromJson(jobj: json.Obj, allocator: std.mem.Allocator) !Self {
}
}
var id: ?i64 = null;
if (jobj.objectGet("id") catch null) |*jid| {
defer jid.deinit();
id = jid.getInt64();
}
// TODO: What should be done when both things are null?
// Return a null Obj or leave it as-is?
return Self{
.id = null,
.id = id,
.tags = tags,
.allocator = allocator,
};

View File

@ -56,6 +56,10 @@ pub const Obj = struct {
// TODO: Check type to not allow other types
return std.mem.sliceTo(c.json_object_get_string(self.obj), 0);
}
pub fn getInt64(self: Obj) i64 {
// TODO: Check ERRNO to see if there was an error
return c.json_object_get_int64(self.obj);
}
pub fn deinit(self: *Obj) void {
_ = c.json_object_put(self.obj);