-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.ts
More file actions
67 lines (57 loc) · 1.4 KB
/
Copy pathbasic.ts
File metadata and controls
67 lines (57 loc) · 1.4 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
import {Effect} from "effect"
import {Ability} from "../src/index"
interface Post {
readonly id: string
readonly authorId: string
readonly published: boolean
readonly title: string
readonly body: string
}
type Subjects = {
readonly Post: Post
}
const ability = Ability.define<Subjects>()(function* (ability) {
yield* ability.allow("read", "Post")
yield* ability.allow("update", "Post", {
fields: ["title", "body"],
conditions: {authorId: "u1"},
reason: "Authors can edit their own draft content"
})
yield* ability.deny("delete", "Post", {
conditions: {published: true},
reason: "Published posts cannot be deleted"
})
})
const program = Effect.gen(function* () {
const post: Post = {
id: "p1",
authorId: "u1",
published: true,
title: "Hello",
body: "World"
}
const canUpdateTitle = yield* Ability.check(ability, {
action: "update",
subject: "Post",
value: post,
field: "title"
}).pipe(
Effect.match({
onFailure: () => false,
onSuccess: () => true
})
)
const deleteResult = yield* Ability.check(ability, {
action: "delete",
subject: "Post",
value: post
}).pipe(
Effect.catchTag("AuthorizationError", (error) => Effect.succeed(error.reason)),
Effect.catch(() => Effect.succeed("unexpected failure"))
)
return {
canUpdateTitle,
deleteResult
}
})
console.log(Effect.runSync(program))