forked from effect-app/boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlog.Controllers.ts
More file actions
77 lines (67 loc) · 2.16 KB
/
Blog.Controllers.ts
File metadata and controls
77 lines (67 loc) · 2.16 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { matchFor } from "api/lib/matchFor"
import { BlogPostRepo, Events, forkOperationWithEffect, Operations, UserRepo } from "api/services"
import { Duration, Effect, Schedule } from "effect"
import { NonNegativeInt } from "effect-app/schema"
import { BlogPost } from "models/Blog"
import { BlogRsc } from "resources"
import { BogusEvent } from "resources/Events"
const blog = matchFor(BlogRsc)
export default blog.controllers({
FindPost: blog.FindPost((req) =>
BlogPostRepo
.find(req.id)
.andThen((_) => _.value ?? null)
),
GetPosts: blog.GetPosts(
BlogPostRepo
.all
.andThen((items) => ({ items }))
),
CreatePost: blog.CreatePost((req) =>
UserRepo
.getCurrentUser
.andThen((author) => (new BlogPost({ ...req, author }, true)))
.tap(BlogPostRepo.save)
),
PublishPost: blog.PublishPost((req) =>
Effect.gen(function*($) {
const post = yield* $(BlogPostRepo.get(req.id))
console.log("publishing post", post)
const targets = [
"google",
"twitter",
"facebook"
]
const done: string[] = []
const operationId = yield* $(
forkOperationWithEffect(
(opId) =>
Operations
.update(opId, {
total: NonNegativeInt(targets.length),
completed: NonNegativeInt(done.length)
})
.andThen(targets
.forEachEffect((_) =>
Effect
.sync(() => done.push(_))
.tap(() =>
Operations.update(opId, {
total: NonNegativeInt(targets.length),
completed: NonNegativeInt(done.length)
})
)
.pipe(Effect.delay(Duration.seconds(4)))
))
.andThen(() => "the answer to the universe is 41"),
// while operation is running...
(_opId) =>
Effect
.suspend(() => Events.publish(new BogusEvent()))
.pipe(Effect.schedule(Schedule.spaced(Duration.seconds(1))))
)
)
return operationId
})
)
})