Skip to content

Commit

Permalink
net: Expose protocolHandler so custom protocols can be handled
Browse files Browse the repository at this point in the history
  • Loading branch information
lauriro committed Jul 10, 2024
1 parent b5dcf8e commit 27630eb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
6 changes: 6 additions & 0 deletions net.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ exports.XMLHttpRequest = XMLHttpRequest
exports.defaultHeaders = {
accept: ["Accept", "*/*"]
}
exports.protocolHandler = {}

function XMLHttpRequest() {
this._reqHeaders = Object.assign({}, exports.defaultHeaders)
Expand Down Expand Up @@ -121,6 +122,11 @@ XMLHttpRequest.prototype = {
return
}

if (exports.protocolHandler[proto]) {
exports.protocolHandler[proto](url, head, fillBody, done)
return
}

throw Error("Unsuported protocol in: " + url)

function head(code, text, headers) {
Expand Down
25 changes: 24 additions & 1 deletion test/net.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

describe("XMLHttpRequest", function() {
var XMLHttpRequest = require("../net.js").XMLHttpRequest
var { XMLHttpRequest, protocolHandler } = require("../net.js")

it("throws on invalid protocol", function(assert) {
assert.throws(function() {
Expand Down Expand Up @@ -147,5 +147,28 @@ describe("XMLHttpRequest", function() {
xhr.send()
})
})

// Blob was added in Node18
it("has a protocolHandler", parseInt(process.versions.node) >= 18 && function(assert) {
protocolHandler.blob = function(url, head, fillBody, done) {
var blob = require("buffer").resolveObjectURL("" + url)
if (blob) blob.text().then(function(text) {
head(200, "OK", { "content-type": blob.type, "content-length": blob.length })
fillBody(text)
done()
})
else done(Error("Blob not found"))
}
var url = URL.createObjectURL(new Blob(['<q id="a"><span id="b">hey!</span></q>'], { type: "text/html" }))
var xhr = new XMLHttpRequest()
xhr.open("GET", url)
xhr.onload = function() {
assert.equal(xhr.getResponseHeader("content-type"), "text/html")
assert.equal(xhr.responseText, '<q id="a"><span id="b">hey!</span></q>')
assert.equal(xhr.readyState, 4)
assert.end()
}
xhr.send()
})
})

0 comments on commit 27630eb

Please sign in to comment.