-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.mo
78 lines (67 loc) · 1.68 KB
/
main.mo
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
78
import Trie "mo:base/Trie";
import Text "mo:base/Text";
import Nat32 "mo:base/Nat32";
import Bool "mo:base/Bool";
import Option "mo:base/Option";
actor {
type BookId = Nat32;
type Book = {
title : Text;
author : Text;
genre : Text;
isRead : Bool;
};
type ResponseBook = {
title : Text;
author : Text;
genre : Text;
isRead : Bool;
id : Nat32;
};
private stable var nextBookId : BookId = 0;
private stable var books : Trie.Trie<BookId, Book> = Trie.empty();
public func addBook(book : Book) : async Text {
let bookId = nextBookId;
nextBookId += 1;
books := Trie.replace(
books,
key(bookId),
Nat32.equal,
?book,
).0;
return ("Book Added Successfully");
};
public func updateBook(bookId : BookId, book : Book) : async Bool {
let result = Trie.find(books, key(bookId), Nat32.equal);
let exists = Option.isSome(result);
if (exists) {
books := Trie.replace(
books,
key(bookId),
Nat32.equal,
?book,
).0;
};
return exists;
};
public func deleteBook(bookId : BookId) : async Bool {
let result = Trie.find(books, key(bookId), Nat32.equal);
let exists = Option.isSome(result);
if (exists) {
books := Trie.replace(
books,
key(bookId),
Nat32.equal,
null,
).0;
};
return exists;
};
public func getBooks(id : BookId) : async ? Book {
let result = Trie.find(books, key(id), Nat32.equal);
return result;
};
private func key(x : BookId) : Trie.Key<BookId> {
return { hash = x; key = x };
};
};