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

HTTP client in jsNode and jsWeb #720

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
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
176 changes: 176 additions & 0 deletions libraries/common/io/client.effekt
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/// HTTP Clients: send a request via HTTP, get a response.
module io/client

import bytearray
import io

// TODO: mutable (native) map of headers instead?
// TODO: body a promise instead? (we get it as a promise anwyays, eh?)
record Response(status: Int, headers: List[(String, String)], body: String)

interface HttpClient {
def get(url: String, body: Option[String], headers: List[(String, String)]): Response
def post(url: String, body: Option[String], headers: List[(String, String)]): Response
}

def client[R] { program: () => R / HttpClient }: R = try {
program()
} with HttpClient {
def get(url, body, headers) = resume(js::get(url, body, headers))
def post(url, body, headers) = resume(js::post(url, body, headers))
}

def get(url: String): Response / HttpClient =
do get(url, None(), [])

def get(url: String, body: String): Response / HttpClient =
do get(url, Some(body), [])

def get(url: String, headers: List[(String, String)]): Response / HttpClient =
do get(url, None(), headers)

def get(url: String, body: String, headers: List[(String, String)]): Response / HttpClient =
do get(url, Some(body), headers)

def post(url: String): Response / HttpClient =
do post(url, None(), [])

def post(url: String, body: String): Response / HttpClient =
do post(url, Some(body), [])

def post(url: String, headers: List[(String, String)]): Response / HttpClient =
do post(url, None(), headers)

def post(url: String, body: String, headers: List[(String, String)]): Response / HttpClient =
do post(url, Some(body), headers)

namespace js {
extern jsNode """
const http = require('node:http');
const https = require('node:https');
const url = require('node:url');

function nodeRequest(method, requestUrl, headers, body) {
return new Promise((resolve, reject) => {
const parsedUrl = url.parse(requestUrl); // TODO: Deprecated?
const requestOptions = {
method: method,
hostname: parsedUrl.hostname,
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
path: parsedUrl.path,
headers: headers
};
console.log(requestOptions);

const clientModule = parsedUrl.protocol === 'https:' ? https : http;

const req = clientModule.request(requestOptions, (res) => {
let responseBody = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
resolve({
status: res.statusCode,
headers: res.headers,
body: responseBody
});
});
});

req.on('error', (error) => {
reject(error);
});

if (body) {
req.write(body);
}
req.end();
});
}
"""

// Browser fetch API implementation
// TODO: Make this work properly!
extern jsWeb """
function browserRequest(method, url, headers, body) {
const requestOptions = {
method: method,
headers: headers
};

if (body) {
requestOptions.body = body;
}

return fetch(url, requestOptions).then(async (response) => {
const headers = {}; // TODO: do we really want to do this conversion?
for (let [key, value] of response.headers.entries()) {
headers[key] = value;
}

return {
status: response.status,
headers: headers,
body: await response.text()
};
});
}
"""

extern type NativeResponse
// js "{ status: Int, headers: Map[String, String], body: String }"

extern pure def status(r: NativeResponse): Int =
js "${r}.status"

extern type NativeHeader
// js "[{key: String, value: String}]"

extern pure def unsafeHeaders(r: NativeResponse): Array[NativeHeader] =
js "Object.entries(${r}.headers)"

extern pure def headerKey(h: NativeHeader): String = js"${h}[0]"
extern pure def headerValue(h: NativeHeader): String = js"${h}[1]"

def headers(r: NativeResponse): List[(String, String)] =
r.unsafeHeaders.toList.map { h => (h.headerKey, h.headerValue) }

extern pure def makeNativeHeader(key: String, value: String): NativeHeader =
js"[${key}, ${value}]"

extern pure def body(r: NativeResponse): String =
js "${r}.body"

def toResponse(r: NativeResponse): Response =
Response(r.status, r.headers, r.body)


/// Make a HTTP request
extern async def request(
method: String,
url: String,
headers: Array[NativeHeader],
unsafeBody: String // really: 'String | undefined'
): NativeResponse =
jsNode "$effekt.capture(callback => nodeRequest(${method}, ${url}, Object.fromEntries(${headers}), ${unsafeBody}).then(callback))"
jsWeb "$effekt.capture(callback => browserRequest(${method}, ${url}, Object.fromEntries(${headers}), ${unsafeBody}).then(callback))"

def get(url: String, body: Option[String], headers: List[(String, String)]): Response =
js::request("GET", url, headers.map { case (k, v) => makeNativeHeader(k, v) }.fromList, optionToUndefined(body)).toResponse

def post(url: String, body: Option[String], headers: List[(String, String)]): Response =
js::request("POST", url, headers.map { case (k, v) => makeNativeHeader(k, v) }.fromList, optionToUndefined(body)).toResponse
}

namespace examples {
def main() = {
with client;

val response = get("https://effekt-lang.org", [("User-Agent", "Effekt/dev")])
println("Status: " ++ response.status.show)
println("Headers: " ++ response.headers.map { case (k, v) => k ++ " -> " ++ v }.show)
println("Body: " ++ response.body.substring(0, 128))
}
}
5 changes: 5 additions & 0 deletions libraries/common/option.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ def option[A, E](proxy: on[E]) { p: => A / Exception[E] }: Option[A] =
def undefinedToOption[A](value: A): Option[A] =
if (value.isUndefined) { None() } else { Some(value) }

def optionToUndefined[A](value: Option[A]): A = value match {
case Some(value) => value
case None() => undefined()
}


// Show Instances
// --------------
Expand Down