-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathhttp-router.ts
61 lines (57 loc) · 1.75 KB
/
http-router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import {
HttpMiddleware,
HttpRouter,
HttpServer,
HttpServerRequest,
HttpServerRespondable,
HttpServerResponse,
Multipart
} from "@effect/platform"
import { BunHttpServer, BunRuntime } from "@effect/platform-bun"
import { Schema } from "@effect/schema"
import { Effect, Layer, Schedule, Stream } from "effect"
const ServerLive = BunHttpServer.layer({ port: 3000 })
class MyError extends Schema.TaggedError<MyError>()("MyError", {
message: Schema.String
}) {
[HttpServerRespondable.symbol]() {
return HttpServerResponse.schemaJson(MyError)(this, { status: 403 })
}
}
const HttpLive = HttpRouter.empty.pipe(
HttpRouter.get(
"/",
Effect.map(
HttpServerRequest.HttpServerRequest,
(req) => HttpServerResponse.text(req.url)
)
),
HttpRouter.get("/package", HttpServerResponse.file("./package.json")),
HttpRouter.get("/fail", new MyError({ message: "failed" })),
HttpRouter.get("/sleep", Effect.as(Effect.sleep("10 seconds"), HttpServerResponse.empty())),
HttpRouter.post(
"/upload",
Effect.gen(function*() {
const data = yield* HttpServerRequest.schemaBodyForm(Schema.Struct({
files: Multipart.FilesSchema
}))
console.log("got files", data.files)
return HttpServerResponse.empty()
})
),
HttpRouter.get(
"/ws",
Stream.fromSchedule(Schedule.spaced(1000)).pipe(
Stream.map(JSON.stringify),
Stream.pipeThroughChannel(HttpServerRequest.upgradeChannel()),
Stream.decodeText(),
Stream.runForEach((_) => Effect.log(_)),
Effect.annotateLogs("ws", "recv"),
Effect.as(HttpServerResponse.empty())
)
),
HttpServer.serve(HttpMiddleware.logger),
HttpServer.withLogAddress,
Layer.provide(ServerLive)
)
BunRuntime.runMain(Layer.launch(HttpLive))