artificer/api/schemas/item.zig

76 lines
2.3 KiB
Zig

const std = @import("std");
const Store = @import("../store.zig");
const EnumStringUtils = @import("../enum_string_utils.zig").EnumStringUtils;
const json = std.json;
const Allocator = std.mem.Allocator;
const json_utils = @import("../json_utils.zig");
const Craft = @import("./craft.zig");
const Item = @This();
pub const Type = enum {
consumable,
body_armor,
weapon,
resource,
leg_armor,
helmet,
boots,
shield,
amulet,
ring,
artifact,
currency,
};
pub const TypeUtils = EnumStringUtils(Type, .{
.{ "consumable", .consumable },
.{ "body_armor", .body_armor },
.{ "weapon" , .weapon },
.{ "resource" , .resource },
.{ "leg_armor" , .leg_armor },
.{ "helmet" , .helmet },
.{ "boots" , .boots },
.{ "shield" , .shield },
.{ "amulet" , .amulet },
.{ "ring" , .ring },
.{ "artifact" , .artifact },
.{ "currency" , .currency },
});
allocator: Allocator,
name: []u8,
code: []u8,
level: u64,
type: Type,
subtype: []u8,
description: []u8,
craft: ?Craft,
// TODO: effects
pub fn parse(store: *Store, obj: json.ObjectMap, allocator: Allocator) !Item {
const level = json_utils.getInteger(obj, "level") orelse return error.MissingProperty;
if (level < 1) return error.InvalidLevel;
const craft = json_utils.getObject(obj, "craft");
const item_type_str = try json_utils.getStringRequired(obj, "type");
return Item{
.allocator = allocator,
.name = (try json_utils.dupeString(allocator, obj, "name")) orelse return error.MissingProperty,
.code = (try json_utils.dupeString(allocator, obj, "code")) orelse return error.MissingProperty,
.level = @intCast(level),
.type = TypeUtils.fromString(item_type_str) orelse return error.InvalidType,
.subtype = (try json_utils.dupeString(allocator, obj, "subtype")) orelse return error.MissingProperty,
.description = (try json_utils.dupeString(allocator, obj, "description")) orelse return error.MissingProperty,
.craft = if (craft != null) try Craft.parse(store, craft.?) else null
};
}
pub fn deinit(self: Item) void {
self.allocator.free(self.name);
self.allocator.free(self.code);
self.allocator.free(self.subtype);
self.allocator.free(self.description);
}