Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor HTTP module a bit. #588

Merged
merged 3 commits into from
May 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 85 additions & 20 deletions core/source/Http.mint
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* Represents a HTTP header */
record Http.Header {
key : String,
value : String
value : String,
key : String
}

/* Represents an HTTP request. */
Expand All @@ -15,12 +15,24 @@ record Http.Request {

/* Represents an HTTP response. */
record Http.Response {
status : Number,
body : String
headers : Map(String, String),
body : Http.ResponseBody,
bodyString : String,
status : Number
}

/* Represents the body of a HTTP response. */
enum Http.ResponseBody {
JSON(Object)
HTML(Object)
Text(String)
XML(Object)
File(File)
}

/* Represents an HTTP request which failed to load. */
record Http.ErrorResponse {
headers : Map(String, String),
type : Http.Error,
status : Number,
url : String
Expand Down Expand Up @@ -239,24 +251,16 @@ module Http {
}

/*
Sends the request with a generated unique ID.

"https://httpbin.org/get"
|> Http.get()
|> Http.send()
*/
fun send (request : Http.Request) : Promise(Result(Http.ErrorResponse, Http.Response)) {
sendWithId(request, Uid.generate())
}

/*
Sends the request with the given ID so it could be aborted later.
Sends the request with a unique ID (generated by default) so it could be aborted later.

"https://httpbin.org/get"
|> Http.get()
|> Http.sendWithId("my-request")
*/
fun sendWithId (request : Http.Request, uid : String) : Promise(Result(Http.ErrorResponse, Http.Response)) {
fun send (
request : Http.Request,
uid : String = Uid.generate()
) : Promise(Result(Http.ErrorResponse, Http.Response)) {
`
new Promise((resolve, reject) => {
if (!this._requests) { this._requests = {} }
Expand All @@ -266,13 +270,26 @@ module Http {
this._requests[#{uid}] = xhr

xhr.withCredentials = #{request.withCredentials}
xhr.responseType = "blob"

const getResponseHeaders = () => {
return xhr
.getAllResponseHeaders()
.trim()
.split(/[\r\n]+/)
.map((line) => {
const parts = line.split(': ');
return [parts.shift(), parts.join(': ')];
})
}

try {
xhr.open(#{request.method}.toUpperCase(), #{request.url}, true)
} catch (error) {
delete this._requests[#{uid}]

resolve(#{Result::Err({
headers: `getResponseHeaders()`,
type: Http.Error::BadUrl,
status: `xhr.status`,
url: request.url
Expand All @@ -287,6 +304,7 @@ module Http {
delete this._requests[#{uid}]

resolve(#{Result::Err({
headers: `getResponseHeaders()`,
type: Http.Error::NetworkError,
status: `xhr.status`,
url: request.url
Expand All @@ -297,25 +315,72 @@ module Http {
delete this._requests[#{uid}]

resolve(#{Result::Err({
headers: `getResponseHeaders()`,
type: Http.Error::Timeout,
status: `xhr.status`,
url: request.url
})})
})

xhr.addEventListener('load', (event) => {
xhr.addEventListener('load', async (event) => {
delete this._requests[#{uid}]

let contentType = xhr.getResponseHeader("Content-Type");
let responseText = await xhr.response.text();
let body;

if (contentType.startsWith("text/html")) {
const object =
(new DOMParser()).parseFromString(responseText, "text/html");

const errorNode =
doc.querySelector("parsererror");

if (errorNode) {
body = #{Http.ResponseBody::Text(`responseText`)};
} else {
body = #{Http.ResponseBody::HTML(`object`)};
}
} else if (contentType.startsWith("application/xml")) {
const object =
(new DOMParser()).parseFromString(responseText, "application/xml");

const errorNode =
doc.querySelector("parsererror");

if (errorNode) {
body = #{Http.ResponseBody::Text(`responseText`)};
} else {
body = #{Http.ResponseBody::XML(`object`)};
}
} else if (contentType.startsWith("application/json")) {
try {
body = #{Http.ResponseBody::JSON(`JSON.parse(responseText)`)};
} catch (e) {
body = #{Http.ResponseBody::Text(`responseText`)};
}
} else if (contentType.startsWith("text/")) {
body = #{Http.ResponseBody::Text(`responseText`)};
}

if (!body) {
Sija marked this conversation as resolved.
Show resolved Hide resolved
const parts = #{Url.parse(request.url).path}.split('/');
body = #{Http.ResponseBody::File(`new File([xhr.response], parts[parts.length - 1], { type: contentType })`)};
}

resolve(#{Result::Ok({
body: `xhr.responseText`,
status: `xhr.status`
headers: `getResponseHeaders()`,
bodyString: `responseText`,
status: `xhr.status`,
body: `body`,
})})
})

xhr.addEventListener('abort', (event) => {
delete this._requests[#{uid}]

resolve(#{Result::Err({
headers: `getResponseHeaders()`,
type: Http.Error::Aborted,
status: `xhr.status`,
url: request.url
Expand Down
6 changes: 3 additions & 3 deletions core/tests/tests/Http.mint
Original file line number Diff line number Diff line change
Expand Up @@ -232,11 +232,11 @@ suite "Http.hasHeader" {
}
}

suite "Http.sendWithId" {
suite "Http.send" {
test "sends the request with the given ID" {
let response =
Http.get("/blah")
|> Http.sendWithId("A")
|> Http.send("A")

`#{Http.requests()}["A"] != undefined`
}
Expand Down Expand Up @@ -265,7 +265,7 @@ component Test.Http {
await Http.empty()
|> Http.url(url)
|> Http.method(method)
|> Http.sendWithId("test")
|> Http.send("test")
|> wrap(
`
(async (promise) => {
Expand Down