This code compiles. I think it works, but it feels disgusting. Refactoring advice ?
let http_post = (hostname: string, port: string, path: string, body: string) => {
let options = {
"hostname": hostname,
"port": port,
"path": path,
"method": "POST",
"headers": {
"Content-Length": Js.String.length(body) } };
let p1 = Js.Promise2.make((~resolve, ~reject) => {
let ans = [];
let req = Http_Api.Http.request(options, (response) => {
response->Http_Server_Response.on("data", (x) => {
Js.Array2.push(ans, x); });
response->Http_Server_Response.on("end", (_) => {
resolve(. Js.String.concatMany(ans))
})
});
req->Http_Api.Http_Client_Request.write(body);
req->Http_Api.Http_Client_Request.end();
});
p1
};
let http_get = (hostname: string, port: string, path: string) => {
let options = {
"hostname": hostname,
"port": port,
"path": path,
"method": "GET",
// "headers": { }
};
let p1 = Js.Promise2.make((~resolve, ~reject) => {
let ans = [];
let req = Http_Api.Http.request(options, (response) => {
response->Http_Server_Response.on("data", (x) => {
Js.Array2.push(ans, x); });
response->Http_Server_Response.on("end", (_) => {
let ans: string = Js.String.concatMany(ans, "");
resolve(. ans)
})
});
req->Http_Api.Http_Client_Request.end();
});
p1
};
module Http_Client_Request = {
type t;
@send external write: (t, string) => unit = "write"
@send external end: (t, ()) => unit = "end"
@get external url: (t) => string = "url"
}
module Http_Server_Response = {
type t;
@send external write: (t, string) => unit = "write"
@send external writeHead: (t, int, 'http_headers) => unit = "writeHead"
@send external end: (t, ()) => unit = "end"
@send external on: (t, string, 'a) => unit = "on"
}
module Http_Server = {
type t;
@send external listen: (t, 'a) => unit = "listen"
}
module Http = {
@module("http") external createServer: ((Http_Client_Request.t, Http_Server_Response.t) => unit) => Http_Server.t = "createServer"
@module("http") external request: ({..}, 'callback) => Http_Client_Request.t = "request"
}
module Fs = {
@module("fs") external readFile: (~name: string, ('a, 'b) => unit ) => unit = "readFile"
}