mirror of
https://github.com/zigzap/zap.git
synced 2025-10-20 15:14:08 +00:00
Endpoint better json handling
This commit is contained in:
parent
886f1ea299
commit
172ddd3e0f
2 changed files with 24 additions and 11 deletions
|
@ -64,18 +64,31 @@ fn getUser(e: *zap.SimpleEndpoint, r: zap.SimpleRequest) void {
|
|||
|
||||
fn listUsers(e: *zap.SimpleEndpoint, r: zap.SimpleRequest) void {
|
||||
_ = e;
|
||||
|
||||
// 1MB json buffer
|
||||
var jsonbuf: [1024 * 1024]u8 = undefined;
|
||||
|
||||
var l: std.ArrayList(User) = std.ArrayList(User).init(alloc);
|
||||
if (users.list(&l)) {} else |_| {
|
||||
return;
|
||||
}
|
||||
// attention: if you add too many users, this will not be enough
|
||||
var jsonbuf: [1024 * 1024]u8 = undefined;
|
||||
if (zap.stringifyArrayListBuf(&jsonbuf, User, &l, .{})) |maybe_json| {
|
||||
var maybe_json: ?[]const u8 = null;
|
||||
var maybe_free: ?std.ArrayList(u8) = null;
|
||||
// if (users.count > 0) {
|
||||
if (users.count > 20000) {
|
||||
// if > 20000 users, 1MB might not be enough for json
|
||||
if (zap.stringifyArrayListAlloc(alloc, User, &l, .{}) catch null) |string| {
|
||||
maybe_free = string;
|
||||
maybe_json = string.items;
|
||||
}
|
||||
} else {
|
||||
maybe_json = zap.stringifyArrayListBuf(&jsonbuf, User, &l, .{}) catch null;
|
||||
}
|
||||
if (maybe_json) |json| {
|
||||
_ = r.sendJson(json);
|
||||
}
|
||||
} else |_| {
|
||||
return;
|
||||
if (maybe_free) |free| {
|
||||
free.deinit();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -87,10 +87,10 @@ pub fn stringifyAlloc(
|
|||
a: std.mem.Allocator,
|
||||
value: anytype,
|
||||
options: std.json.StringifyOptions,
|
||||
) ?[]const u8 {
|
||||
) ?std.ArrayList(u8) {
|
||||
var string = std.ArrayList(u8).init(a);
|
||||
if (std.json.stringify(value, options, string.writer())) {
|
||||
return string.items;
|
||||
return string;
|
||||
} else |_| { // error
|
||||
return null;
|
||||
}
|
||||
|
@ -102,7 +102,7 @@ pub fn stringifyArrayListAlloc(
|
|||
comptime T: anytype,
|
||||
list: *std.ArrayList(T),
|
||||
options: std.json.StringifyOptions,
|
||||
) !?[]const u8 {
|
||||
) !?std.ArrayList(u8) {
|
||||
var string = std.ArrayList(u8).init(a);
|
||||
var writer = string.writer();
|
||||
try writer.writeByte('[');
|
||||
|
@ -113,5 +113,5 @@ pub fn stringifyArrayListAlloc(
|
|||
try std.json.stringify(user, options, string.writer());
|
||||
}
|
||||
try writer.writeByte(']');
|
||||
return string.items;
|
||||
return string;
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue