browser: create a fetchResult func

This commit is contained in:
Pierre Tachoire
2024-01-15 18:15:26 +01:00
parent 2efda8f452
commit 55f69b3ae7

View File

@@ -332,34 +332,18 @@ pub const Page = struct {
if (opt_src) |src| { if (opt_src) |src| {
log.debug("starting GET {s}", .{src}); log.debug("starting GET {s}", .{src});
const u = std.Uri.parse(src) catch try std.Uri.parseWithoutScheme(src); self.fetchScript(src) catch |err| {
const ru = try std.Uri.resolve(self.uri, u, false, self.alloc); switch (err) {
FetchError.BadStatusCode => return err,
var fetchres = try self.loader.fetch(self.alloc, ru);
defer fetchres.deinit();
log.info("GET {any}: {d}", .{ ru, fetchres.status });
if (fetchres.status != .ok) {
return error.BadStatusCode;
}
// TODO check content-type
// check no body
// TODO If el's result is null, then fire an event named error at // TODO If el's result is null, then fire an event named error at
// el, and return. // el, and return.
if (fetchres.body == null) return; FetchError.NoBody => return,
var res = jsruntime.JSResult{}; FetchError.JsErr => {}, // nothing to do here.
try self.env.run(self.alloc, fetchres.body.?, src, &res, null); else => return err,
defer res.deinit(self.alloc);
if (res.success) {
log.debug("eval remote {s}: {s}", .{ src, res.result });
} else {
log.info("eval remote {s}: {s}", .{ src, res.result });
} }
};
// TODO If el's from an external file is true, then fire an event // TODO If el's from an external file is true, then fire an event
// named load at el. // named load at el.
@@ -388,6 +372,44 @@ pub const Page = struct {
// el, and return. // el, and return.
} }
const FetchError = error{
BadStatusCode,
NoBody,
JsErr,
};
// fetchScript senf a GET request to the src and execute the script
// received.
fn fetchScript(self: *Page, src: []const u8) !void {
log.debug("starting fetch script {s}", .{src});
const u = std.Uri.parse(src) catch try std.Uri.parseWithoutScheme(src);
const ru = try std.Uri.resolve(self.uri, u, false, self.alloc);
var fetchres = try self.loader.fetch(self.alloc, ru);
defer fetchres.deinit();
log.info("fech script {any}: {d}", .{ ru, fetchres.status });
if (fetchres.status != .ok) return FetchError.BadStatusCode;
// TODO check content-type
// check no body
if (fetchres.body == null) return FetchError.NoBody;
var res = jsruntime.JSResult{};
try self.env.run(self.alloc, fetchres.body.?, src, &res, null);
defer res.deinit(self.alloc);
if (res.success) {
log.debug("eval remote {s}: {s}", .{ src, res.result });
} else {
log.info("eval remote {s}: {s}", .{ src, res.result });
return FetchError.JsErr;
}
}
// > type // > type
// > Attribute is not set (default), an empty string, or a JavaScript MIME // > Attribute is not set (default), an empty string, or a JavaScript MIME
// > type indicates that the script is a "classic script", containing // > type indicates that the script is a "classic script", containing