Skip to content

Commit 0faff39

Browse files
committed
xhr: implement responseText
1 parent a27db0d commit 0faff39

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

src/xhr/xhr.zig

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ pub const XMLHttpRequest = struct {
9898
};
9999

100100
proto: XMLHttpRequestEventTarget,
101+
alloc: std.mem.Allocator,
101102
cli: Client,
102103
impl: YieldImpl,
103104

@@ -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,14 +308,20 @@ 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

295-
// the caller owns the string.
315+
// The caller owns the string returned.
316+
// TODO change the return type to express the string ownership and let
317+
// jsruntime free the string once copied to v8.
318+
// see https://github.com/lightpanda-io/jsruntime-lib/issues/195
296319
pub fn _getAllResponseHeaders(self: *XMLHttpRequest, alloc: std.mem.Allocator) ![]const u8 {
297320
self.response_headers.sort();
298321

299322
var buf: std.ArrayListUnmanaged(u8) = .{};
323+
errdefer buf.deinit(alloc);
324+
300325
const w = buf.writer(alloc);
301326

302327
for (self.response_headers.list.items) |entry| {
@@ -331,7 +356,8 @@ pub fn testExecFn(
331356
// Each case executed waits for all loop callaback calls.
332357
// So the url has been retrieved.
333358
.{ .src = "nb", .ex = "1" },
334-
.{ .src = "req.getAllResponseHeaders()", .ex = "undefined" },
359+
.{ .src = "req.getAllResponseHeaders().length > 1024", .ex = "true" },
360+
.{ .src = "req.responseText.length > 1024", .ex = "true" },
335361
};
336362
try checkCases(js_env, &send);
337363
}

0 commit comments

Comments
 (0)