Skip to content

Commit ba9fc7f

Browse files
committed
xhr: implement responseText
1 parent a27db0d commit ba9fc7f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/xhr/xhr.zig

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ pub const XMLHttpRequest = struct {
9797
JSON,
9898
};
9999

100+
alloc: std.mem.Allocator,
100101
proto: XMLHttpRequestEventTarget,
101102
cli: Client,
102103
impl: YieldImpl,
@@ -120,6 +121,7 @@ pub const XMLHttpRequest = struct {
120121

121122
pub fn constructor(alloc: std.mem.Allocator, loop: *Loop) !XMLHttpRequest {
122123
return .{
124+
.alloc = alloc,
123125
.proto = try XMLHttpRequestEventTarget.constructor(),
124126
.headers = .{ .allocator = alloc, .owned = true },
125127
.response_headers = .{ .allocator = alloc, .owned = true },
@@ -270,6 +272,23 @@ pub const XMLHttpRequest = struct {
270272

271273
self.state = LOADING;
272274

275+
var buf: std.ArrayListUnmanaged(u8) = .{};
276+
277+
const reader = req.reader();
278+
var buffer: [1024]u8 = undefined;
279+
var ln = buffer.len;
280+
while (ln > 0) {
281+
ln = reader.read(&buffer) catch |e| {
282+
buf.deinit(self.alloc);
283+
return self.onerr(e);
284+
};
285+
buf.appendSlice(self.alloc, buffer[0..ln]) catch |e| {
286+
buf.deinit(self.alloc);
287+
return self.onerr(e);
288+
};
289+
}
290+
self.response_bytes = buf.items;
291+
273292
self.state = DONE;
274293

275294
// TODO use events instead
@@ -289,6 +308,7 @@ pub const XMLHttpRequest = struct {
289308
pub fn get_responseText(self: *XMLHttpRequest) ![]const u8 {
290309
if (self.state != LOADING and self.state != DONE) return DOMError.InvalidState;
291310
if (self.response_type != .Empty and self.response_type != .Text) return DOMError.InvalidState;
311+
292312
return if (self.response_bytes) |v| v else "";
293313
}
294314

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

299319
var buf: std.ArrayListUnmanaged(u8) = .{};
320+
errdefer buf.deinit(alloc);
321+
300322
const w = buf.writer(alloc);
301323

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

0 commit comments

Comments
 (0)