1
0
Fork 0
mirror of https://github.com/zigzap/zap.git synced 2025-10-20 15:14:08 +00:00

update endpoint example to the new json api

This commit is contained in:
Ed Yu 2023-05-18 20:54:16 -07:00
parent dc7720e298
commit 3fb6a65e48

View file

@ -82,10 +82,9 @@ fn listUsers(self: *Self, r: zap.SimpleRequest) void {
fn postUser(e: *zap.SimpleEndpoint, r: zap.SimpleRequest) void { fn postUser(e: *zap.SimpleEndpoint, r: zap.SimpleRequest) void {
const self = @fieldParentPtr(Self, "endpoint", e); const self = @fieldParentPtr(Self, "endpoint", e);
if (r.body) |body| { if (r.body) |body| {
var stream = std.json.TokenStream.init(body); var maybe_user: ?User = std.json.parseFromSlice(User, self.alloc, body, .{}) catch null;
var maybe_user: ?User = std.json.parse(User, &stream, .{ .allocator = self.alloc }) catch null;
if (maybe_user) |u| { if (maybe_user) |u| {
defer std.json.parseFree(User, u, .{ .allocator = self.alloc }); defer std.json.parseFree(User, self.alloc, u);
if (self.users.addByName(u.first_name, u.last_name)) |id| { if (self.users.addByName(u.first_name, u.last_name)) |id| {
var jsonbuf: [128]u8 = undefined; var jsonbuf: [128]u8 = undefined;
if (zap.stringifyBuf(&jsonbuf, .{ .status = "OK", .id = id }, .{})) |json| { if (zap.stringifyBuf(&jsonbuf, .{ .status = "OK", .id = id }, .{})) |json| {
@ -105,10 +104,9 @@ fn putUser(e: *zap.SimpleEndpoint, r: zap.SimpleRequest) void {
if (self.userIdFromPath(path)) |id| { if (self.userIdFromPath(path)) |id| {
if (self.users.get(id)) |_| { if (self.users.get(id)) |_| {
if (r.body) |body| { if (r.body) |body| {
var stream = std.json.TokenStream.init(body); var maybe_user: ?User = std.json.parseFromSlice(User, self.alloc, body, .{}) catch null;
var maybe_user: ?User = std.json.parse(User, &stream, .{ .allocator = self.alloc }) catch null;
if (maybe_user) |u| { if (maybe_user) |u| {
defer std.json.parseFree(User, u, .{ .allocator = self.alloc }); defer std.json.parseFree(User, self.alloc, u);
var jsonbuf: [128]u8 = undefined; var jsonbuf: [128]u8 = undefined;
if (self.users.update(id, u.first_name, u.last_name)) { if (self.users.update(id, u.first_name, u.last_name)) {
if (zap.stringifyBuf(&jsonbuf, .{ .status = "OK", .id = id }, .{})) |json| { if (zap.stringifyBuf(&jsonbuf, .{ .status = "OK", .id = id }, .{})) |json| {