Skip to content

Commit

Permalink
xhr: implement responseText
Browse files Browse the repository at this point in the history
  • Loading branch information
krichprollsch committed Jan 31, 2024
1 parent a27db0d commit ba9fc7f
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/xhr/xhr.zig
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ pub const XMLHttpRequest = struct {
JSON,
};

alloc: std.mem.Allocator,
proto: XMLHttpRequestEventTarget,
cli: Client,
impl: YieldImpl,
Expand All @@ -120,6 +121,7 @@ pub const XMLHttpRequest = struct {

pub fn constructor(alloc: std.mem.Allocator, loop: *Loop) !XMLHttpRequest {
return .{
.alloc = alloc,
.proto = try XMLHttpRequestEventTarget.constructor(),
.headers = .{ .allocator = alloc, .owned = true },
.response_headers = .{ .allocator = alloc, .owned = true },
Expand Down Expand Up @@ -270,6 +272,23 @@ pub const XMLHttpRequest = struct {

self.state = LOADING;

var buf: std.ArrayListUnmanaged(u8) = .{};

const reader = req.reader();
var buffer: [1024]u8 = undefined;
var ln = buffer.len;
while (ln > 0) {
ln = reader.read(&buffer) catch |e| {
buf.deinit(self.alloc);
return self.onerr(e);
};
buf.appendSlice(self.alloc, buffer[0..ln]) catch |e| {
buf.deinit(self.alloc);
return self.onerr(e);
};
}
self.response_bytes = buf.items;

self.state = DONE;

// TODO use events instead
Expand All @@ -289,6 +308,7 @@ pub const XMLHttpRequest = struct {
pub fn get_responseText(self: *XMLHttpRequest) ![]const u8 {
if (self.state != LOADING and self.state != DONE) return DOMError.InvalidState;
if (self.response_type != .Empty and self.response_type != .Text) return DOMError.InvalidState;

return if (self.response_bytes) |v| v else "";
}

Expand All @@ -297,6 +317,8 @@ pub const XMLHttpRequest = struct {
self.response_headers.sort();

var buf: std.ArrayListUnmanaged(u8) = .{};
errdefer buf.deinit(alloc);

const w = buf.writer(alloc);

for (self.response_headers.list.items) |entry| {
Expand Down Expand Up @@ -332,6 +354,7 @@ pub fn testExecFn(
// So the url has been retrieved.
.{ .src = "nb", .ex = "1" },
.{ .src = "req.getAllResponseHeaders()", .ex = "undefined" },
.{ .src = "req.responseText", .ex = "undefined" },
};
try checkCases(js_env, &send);
}

0 comments on commit ba9fc7f

Please sign in to comment.