Skip to content

Commit 5528872

Browse files
committedAug 6, 2023
fix: handle FormData on the server
1 parent 2d70555 commit 5528872

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed
 

Diff for: ‎.changeset/honest-wombats-decide.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect-http": patch
3+
---
4+
5+
Handle `FormData` on the server.

Diff for: ‎examples/form-data.ts

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import * as Schema from "@effect/schema/Schema";
2+
import { Effect, Predicate, pipe } from "effect";
3+
import * as Http from "effect-http";
4+
5+
import { debugLogger } from "./_utils";
6+
7+
const api = pipe(
8+
Http.api(),
9+
Http.post("upload", "/upload", {
10+
request: {
11+
body: Http.FormData,
12+
},
13+
response: Schema.string,
14+
}),
15+
);
16+
17+
const server = pipe(
18+
Http.server(api),
19+
Http.handle("upload", ({ body }) => {
20+
const file = body.get("file");
21+
22+
if (file === null) {
23+
return Effect.fail(Http.invalidBodyError('Expected "file"'));
24+
}
25+
26+
if (Predicate.isString(file)) {
27+
return Effect.fail(Http.invalidBodyError("Expected file"));
28+
}
29+
30+
return pipe(
31+
Effect.promise(() => file.text()),
32+
Effect.map((content) => `Received file with content: ${content}`),
33+
);
34+
}),
35+
);
36+
37+
const program = pipe(
38+
server,
39+
Http.listen({ port: 3000 }),
40+
Effect.provideSomeLayer(debugLogger),
41+
);
42+
43+
Effect.runPromise(program);

Diff for: ‎src/Server.ts

+2
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ const buildHandler =
119119
if (contentLength > 0) {
120120
if (contentTypeHeader?.startsWith("application/json")) {
121121
return request.json();
122+
} else if (contentTypeHeader?.startsWith("multipart/form-data")) {
123+
return request.formData();
122124
} else {
123125
return request.text();
124126
}

0 commit comments

Comments
 (0)
Please sign in to comment.