Add withBody.

This commit is contained in:
Dillon Kearns 2021-12-22 15:28:19 -08:00
parent 6df0ce9987
commit f43e57e265
3 changed files with 85 additions and 59 deletions

View File

@ -205,6 +205,7 @@ function reqToJson(req) {
port: 80, // TODO
protocol: "https", // TODO
rawUrl: "", // TODO
body: req.body,
};
}
`;

View File

@ -346,8 +346,19 @@ async function start(options) {
return;
}
let body = "";
req.on("data", function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6) req.connection.destroy();
});
req.on("end", async function () {
await runRenderThread(
reqToJson(req),
reqToJson(req, body),
pathname,
function (renderResult) {
const is404 = renderResult.is404;
@ -369,7 +380,10 @@ async function start(options) {
case "api-response": {
if (renderResult.body.kind === "server-response") {
const serverResponse = renderResult.body;
res.writeHead(serverResponse.statusCode, serverResponse.headers);
res.writeHead(
serverResponse.statusCode,
serverResponse.headers
);
res.end(serverResponse.body);
} else if (renderResult.body.kind === "static-file") {
let mimeType = serveStatic.mime.lookup(pathname || "text/html");
@ -405,6 +419,7 @@ async function start(options) {
}
}
);
});
}
/**
@ -579,7 +594,7 @@ async function ensureRequiredExecutables() {
}
}
function reqToJson(req) {
function reqToJson(req, body) {
const url = new URL(req.url, "http://localhost:1234");
return {
method: req.method,
@ -591,6 +606,7 @@ function reqToJson(req) {
port: url.port,
protocol: url.protocol,
rawUrl: req.url,
body: body,
};
}

View File

@ -1,7 +1,7 @@
module DataSource.ServerRequest exposing
( IsAvailable
, ServerRequest, expectHeader, init, optionalHeader, staticData, toDataSource
, Method(..), withAllHeaders, withHost, withMethod, withProtocol, withQueryParams
, Method(..), withAllHeaders, withBody, withHost, withMethod, withProtocol, withQueryParams
)
{-|
@ -143,6 +143,15 @@ optionalHeader headerName (ServerRequest decoder) =
|> ServerRequest
{-| -}
withBody : ServerRequest (Maybe String -> value) -> ServerRequest value
withBody (ServerRequest decoder) =
decoder
|> OptimizedDecoder.andMap
(OptimizedDecoder.optionalField "body" OptimizedDecoder.string)
|> ServerRequest
type Method
= Connect
| Delete