Skip to content

Commit

Permalink
xhr: fix json response
Browse files Browse the repository at this point in the history
  • Loading branch information
krichprollsch committed Feb 12, 2024
1 parent f8789fa commit 5642313
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/xhr/xhr.zig
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ pub const XMLHttpRequest = struct {
};

// TODO use std.json.Value instead, but it causes comptime error.
// blocked by https://github.com/lightpanda-io/jsruntime-lib/issues/204
// const JSONValue = std.json.Value;
const JSONValue = u8;

const Response = union(ResponseType) {
Expand Down Expand Up @@ -511,6 +513,7 @@ pub const XMLHttpRequest = struct {
// TODO Let jsonObject be the result of running parse JSON from bytes
// on this’s received bytes. If that threw an exception, then return
// null.
self.setResponseObjJSON();
}

if (self.response_obj) |obj| {
Expand Down Expand Up @@ -558,7 +561,13 @@ pub const XMLHttpRequest = struct {

// setResponseObjJSON parses the received bytes as a std.json.Value.
fn setResponseObjJSON(self: *XMLHttpRequest) void {
const p = std.json.parseFromSlice(JSONValue, self.alloc, self.response_bytes, .{}) catch {
const p = std.json.parseFromSliceLeaky(
JSONValue,
self.alloc,
self.response_bytes.?,
.{},
) catch |e| {
log.err("parse JSON: {}\n{s}", .{ e, self.response_bytes.? });
self.response_obj = .{ .Failure = true };
return;
};
Expand Down Expand Up @@ -652,4 +661,19 @@ pub fn testExecFn(
.{ .src = "req.response", .ex = "" },
};
try checkCases(js_env, &send);

var json = [_]Case{
.{ .src = "const req2 = new XMLHttpRequest()", .ex = "undefined" },
.{ .src = "req2.open('GET', 'http://httpbin.io/json')", .ex = "undefined" },
.{ .src = "req2.responseType = 'json'", .ex = "json" },

.{ .src = "req2.send()", .ex = "undefined" },

// Each case executed waits for all loop callaback calls.
// So the url has been retrieved.
.{ .src = "req2.status", .ex = "200" },
.{ .src = "req2.statusText", .ex = "OK" },
.{ .src = "req2.response", .ex = "" },
};
try checkCases(js_env, &json);
}

0 comments on commit 5642313

Please sign in to comment.