Skip to content

Commit

Permalink
🎉 First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
MystPi committed Jan 11, 2024
0 parents commit a4319c0
Show file tree
Hide file tree
Showing 10 changed files with 246 additions and 0 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: test

on:
push:
branches:
- master
- main
pull_request:

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: erlef/setup-beam@v1
with:
otp-version: "26.0.2"
gleam-version: "0.33.0"
rebar3-version: "3"
# elixir-version: "1.15.4"
- run: gleam deps download
- run: gleam test
- run: gleam format --check src test
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*.beam
*.ez
build
erl_crash.dump
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 MystPi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# conversation

[![Package Version](https://img.shields.io/hexpm/v/conversation)](https://hex.pm/packages/conversation)
[![Hex Docs](https://img.shields.io/badge/hex-docs-ffaff3)](https://hexdocs.pm/conversation/)

Gleam bindings for the standard JavaScript [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) APIs.

## Installation

This package can be added to your Gleam project:

```sh
gleam add conversation
```

and its documentation can be found at <https://hexdocs.pm/conversation>.

## Example Usage

An example wrapper for `Deno.serve` that uses `conversation` can be found in [./test](./test/). The example can be run with the command `gleam test`.
21 changes: 21 additions & 0 deletions gleam.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name = "conversation"
version = "1.0.0"
target = "javascript"

description = "Gleam bindings for the standard JavaScript Request and Response APIs"
licences = ["MIT"]
repository = { type = "github", user = "MystPi", repo = "conversation" }
# links = [{ title = "Website", href = "https://gleam.run" }]

[javascript]
runtime = "deno"

[javascript.deno]
allow_all = true

[dependencies]
gleam_stdlib = "~> 0.32"
gleam_http = "~> 3.5"
gleam_javascript = "~> 0.7"

[dev-dependencies]
13 changes: 13 additions & 0 deletions manifest.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# This file was generated by Gleam
# You typically do not need to edit this file

packages = [
{ name = "gleam_http", version = "3.5.3", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_http", source = "hex", outer_checksum = "C2FC3322203B16F897C1818D9810F5DEFCE347F0751F3B44421E1261277A7373" },
{ name = "gleam_javascript", version = "0.7.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_javascript", source = "hex", outer_checksum = "B5E05F479C52217C02BA2E8FC650A716BFB62D4F8D20A90909C908598E12FBE0" },
{ name = "gleam_stdlib", version = "0.34.0", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "1FB8454D2991E9B4C0C804544D8A9AD0F6184725E20D63C3155F0AEB4230B016" },
]

[requirements]
gleam_http = { version = "~> 3.5" }
gleam_javascript = { version = "~> 0.7" }
gleam_stdlib = { version = "~> 0.32" }
52 changes: 52 additions & 0 deletions src/conversation.gleam
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import gleam/http/request.{type Request}
import gleam/http/response.{type Response}
import gleam/javascript/promise.{type Promise}
import gleam/dynamic.{type Dynamic}

/// A standard JavaScript [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request).
pub type JsRequest

/// A standard JavaScript [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
pub type JsResponse

/// The body of an incoming request. It must be read with functions like
/// [`read_text`](#read_text), and can only be read once.
pub type RequestBody

/// Body type for an outgoing response.
///
/// ```
/// import gleam/http/response
/// import conversation.{Text}
///
/// response.new(200)
/// |> response.set_body(Text("Hello, world!"))
/// ```
pub type ResponseBody {
Text(String)
Bits(BitArray)
}

/// Translates a [`JsRequest`](#JsRequest) into a Gleam
/// [`Request`](https://hexdocs.pm/gleam_http/gleam/http/request.html#Request).
@external(javascript, "./ffi.mjs", "translateRequest")
pub fn translate_request(req: JsRequest) -> Request(RequestBody)

/// Translates a Gleam [`Response`](https://hexdocs.pm/gleam_http/gleam/http/response.html#Response)
/// into a [`JsResponse`](#JsResponse).
@external(javascript, "./ffi.mjs", "translateResponse")
pub fn translate_response(res: Response(ResponseBody)) -> JsResponse

/// Read a request body as text.
@external(javascript, "./ffi.mjs", "readText")
pub fn read_text(body: RequestBody) -> Promise(String)

/// Read a request body as a BitArray.
@external(javascript, "./ffi.mjs", "readBits")
pub fn read_bits(body: RequestBody) -> Promise(BitArray)

/// Read a request body as JSON, returning a
/// [`Dynamic`](https://hexdocs.pm/gleam_stdlib/gleam/dynamic.html#Dynamic) value
/// which can then be decoded with [`gleam_json`](https://hexdocs.pm/gleam_json/).
@external(javascript, "./ffi.mjs", "readJson")
pub fn read_json(body: RequestBody) -> Promise(Dynamic)
59 changes: 59 additions & 0 deletions src/ffi.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import * as $gleam from './gleam.mjs';
import * as $http from '../gleam_http/gleam/http.mjs';
import * as $request from '../gleam_http/gleam/http/request.mjs';
import * as $option from '../gleam_stdlib/gleam/option.mjs';
import * as $conversation from './conversation.mjs';

export function translateRequest(req) {
const url = new URL(req.url);

const method = $http.parse_method(req.method)[0];
const headers = $gleam.List.fromArray([...req.headers]);
const body = req;
const scheme =
url.protocol === 'https:' ? new $http.Https() : new $http.Http();
const host = url.hostname;
const port = maybe(+url.port);
const path = url.pathname;
const query = maybe(url.search.slice(1));

return new $request.Request(
method,
headers,
body,
scheme,
host,
port,
path,
query
);
}

export function translateResponse(res) {
const body =
res.body instanceof $conversation.Bits ? res.body[0].buffer : res.body[0];

return new Response(new Blob([body]), {
status: res.status,
headers: res.headers,
});
}

export function readText(body) {
return body.text();
}

export async function readBits(body) {
return new $gleam.BitArray(new Uint8Array(await body.arrayBuffer()));
}

export function readJson(body) {
return body.json();
}

function maybe(x) {
if (x) {
return new $option.Some(x);
}
return new $option.None();
}
30 changes: 30 additions & 0 deletions test/conversation_test.gleam
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import gleam/http/request.{type Request}
import gleam/http/response.{type Response}
import gleam/javascript/promise.{type Promise}
import conversation.{
type JsRequest, type JsResponse, type RequestBody, type ResponseBody, Text,
translate_request, translate_response,
}

pub fn main() {
serve(fn(req) {
let body = "Hello at " <> req.path <> "!"

response.new(200)
|> response.set_body(Text(body))
|> promise.resolve
})
}

fn serve(
handler: fn(Request(RequestBody)) -> Promise(Response(ResponseBody)),
) -> Nil {
deno_serve(fn(req) {
translate_request(req)
|> handler
|> promise.map(translate_response)
})
}

@external(javascript, "./serve.mjs", "serve")
fn deno_serve(handler: fn(JsRequest) -> Promise(JsResponse)) -> Nil
3 changes: 3 additions & 0 deletions test/serve.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function serve(handler) {
Deno.serve((req) => handler(req));
}

0 comments on commit a4319c0

Please sign in to comment.