66 lines
1.7 KiB
Zig
66 lines
1.7 KiB
Zig
|
const std = @import("std");
|
||
|
|
||
|
const db = @import("./db.zig");
|
||
|
|
||
|
pub const models = @import("./models.zig");
|
||
|
pub const free = db.free;
|
||
|
pub const Id = []const u8;
|
||
|
|
||
|
pub fn CreateInfo(comptime T: type) type {
|
||
|
const t_fields = std.meta.fields(T);
|
||
|
var fields: [t_fields.len - 1]std.builtin.Type.StructField = undefined;
|
||
|
var count = 0;
|
||
|
|
||
|
inline for (t_fields) |f| {
|
||
|
if (std.mem.eql(u8, f.name, "id")) continue;
|
||
|
|
||
|
fields[count] = f;
|
||
|
count += 1;
|
||
|
}
|
||
|
|
||
|
return @Type(.{ .Struct = .{
|
||
|
.layout = .Auto,
|
||
|
.fields = &fields,
|
||
|
.decls = &[0]std.builtin.Type.Declaration{},
|
||
|
.is_tuple = false,
|
||
|
} });
|
||
|
}
|
||
|
|
||
|
fn reify(comptime T: type, id: Id, val: CreateInfo(T)) T {
|
||
|
var result: T = undefined;
|
||
|
result.id = id;
|
||
|
inline for (std.meta.fields(CreateInfo(T))) |f| {
|
||
|
@field(result, f.name) = @field(val, f.name);
|
||
|
}
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
const ApiServer = struct {
|
||
|
db: db.Database,
|
||
|
last_id: u64 = 0,
|
||
|
|
||
|
pub fn init(alloc: std.mem.Allocator) !ApiServer {
|
||
|
return ApiServer{
|
||
|
.db = try db.Database.init(alloc),
|
||
|
};
|
||
|
}
|
||
|
|
||
|
fn genId(self: *ApiServer, alloc: std.mem.Allocator) ![]const u8 {
|
||
|
self.last_id += 1;
|
||
|
return std.fmt.allocPrint(alloc, "{}", .{self.last_id});
|
||
|
}
|
||
|
|
||
|
pub fn createNote(self: *ApiServer, info: CreateInfo(models.Note), alloc: std.mem.Allocator) !models.Note {
|
||
|
const id = try self.genId(alloc);
|
||
|
|
||
|
const note = reify(models.Note, id, info);
|
||
|
try self.db.putNote(note);
|
||
|
|
||
|
return id;
|
||
|
}
|
||
|
|
||
|
pub fn getNote(self: *ApiServer, id: Id, alloc: std.mem.Allocator) !?models.Note {
|
||
|
return self.db.getNote(id, alloc);
|
||
|
}
|
||
|
};
|