fediglam/src/main/api/notes.zig

56 lines
1.1 KiB
Zig
Raw Normal View History

2022-09-08 07:52:23 +00:00
const std = @import("std");
const util = @import("util");
2022-10-02 05:18:24 +00:00
const sql = @import("sql");
2022-09-08 07:52:23 +00:00
const Uuid = util.Uuid;
const DateTime = util.DateTime;
const getRandom = @import("../api.zig").getRandom;
pub const Note = struct {
id: Uuid,
author_id: Uuid,
content: []const u8,
created_at: DateTime,
};
2022-10-02 05:18:24 +00:00
pub const CreateError = error{
DatabaseFailure,
2022-09-08 07:52:23 +00:00
};
pub fn create(
db: anytype,
author: Uuid,
content: []const u8,
2022-10-02 05:18:24 +00:00
alloc: std.mem.Allocator,
) CreateError!Uuid {
2022-09-08 07:52:23 +00:00
const id = Uuid.randV4(getRandom());
2022-10-02 05:18:24 +00:00
db.insert("note", .{
2022-09-08 07:52:23 +00:00
.id = id,
.author_id = author,
.content = content,
.created_at = DateTime.now(),
2022-10-02 05:18:24 +00:00
}, alloc) catch return error.DatabaseFailure;
2022-09-08 07:52:23 +00:00
return id;
}
2022-10-02 05:18:24 +00:00
pub const GetError = error{
DatabaseFailure,
NotFound,
};
pub fn get(db: anytype, id: Uuid, alloc: std.mem.Allocator) GetError!Note {
return db.queryRow(
Note,
sql.selectStar(Note, "note") ++
\\WHERE id = $1
\\LIMIT 1
,
2022-09-08 07:52:23 +00:00
.{id},
alloc,
2022-10-02 05:18:24 +00:00
) catch |err| switch (err) {
error.NoRows => error.NotFound,
else => error.DatabaseFailure,
2022-09-08 07:52:23 +00:00
};
}