Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(examples): add simple userbook realm #1949

Merged
merged 43 commits into from
Apr 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
025e2b4
add r/demo/pagination
leohhhn Apr 18, 2024
d3ca37c
add pagination
leohhhn Apr 18, 2024
53fc6e9
use mux?
leohhhn Apr 18, 2024
a7ce776
more mux
leohhhn Apr 18, 2024
e88798e
reorg imports
leohhhn Apr 18, 2024
e02fda7
remove newline
leohhhn Apr 22, 2024
ac39676
next & previous pages
leohhhn Apr 22, 2024
bf713b6
signups, fix page index
leohhhn Apr 23, 2024
c89e4f6
add latest signu
leohhhn Apr 23, 2024
5e0f6ca
Merge branch 'master' into feat/add-paginated-signup
leohhhn Apr 23, 2024
5fa1eb0
Merge branch 'master' into feat/add-paginated-signup
leohhhn Apr 23, 2024
cf4df41
comments
leohhhn Apr 23, 2024
1c5df76
add render test
leohhhn Apr 23, 2024
b9cb27d
mod tidy
leohhhn Apr 23, 2024
5f0ad4b
sort imports
leohhhn Apr 23, 2024
152fe8b
simplify error
leohhhn Apr 23, 2024
82d52d5
simplify condition
leohhhn Apr 23, 2024
a7aac51
simplify condition 2
leohhhn Apr 23, 2024
a41d2bc
simplify render path
leohhhn Apr 23, 2024
e9697cf
simplify render path 2
leohhhn Apr 23, 2024
f1316ba
fix
leohhhn Apr 23, 2024
f320ad7
Update examples/gno.land/r/demo/pagination/pagination.gno
leohhhn Apr 23, 2024
8aed783
Update examples/gno.land/r/demo/pagination/pagination.gno
leohhhn Apr 23, 2024
5290e0d
Merge branch 'master' into feat/add-paginated-signup
leohhhn Apr 23, 2024
e75039c
fix edgecase
leohhhn Apr 23, 2024
3c629ae
fix
leohhhn Apr 24, 2024
fae1bca
userbook
leohhhn Apr 25, 2024
e2ef9f6
rename folder
leohhhn Apr 25, 2024
9e748e8
move router to init
leohhhn Apr 25, 2024
7c5e17a
add comments
leohhhn Apr 25, 2024
ba0792a
fix const
leohhhn Apr 25, 2024
5ea62f6
fix test
leohhhn Apr 25, 2024
189b5f9
Merge branch 'master' into feat/add-paginated-signup
leohhhn Apr 25, 2024
8069725
fix bad case
leohhhn Apr 25, 2024
d0a51cf
remove useless case
leohhhn Apr 25, 2024
797f3f4
fixup rednering
leohhhn Apr 25, 2024
6ee0d73
rm newline
leohhhn Apr 25, 2024
2c66ac7
defaultPageSize
leohhhn Apr 25, 2024
7683ad2
wip tests
leohhhn Apr 26, 2024
3cefc77
add testcase
leohhhn Apr 26, 2024
8ca5956
modify tests
leohhhn Apr 26, 2024
e54e145
testcases
leohhhn Apr 26, 2024
bf84da4
Merge branch 'master' into feat/add-paginated-signup
leohhhn Apr 26, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions examples/gno.land/r/demo/userbook/gno.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module gno.land/r/demo/userbook

require (
gno.land/p/demo/avl v0.0.0-latest
gno.land/p/demo/mux v0.0.0-latest
leohhhn marked this conversation as resolved.
Show resolved Hide resolved
gno.land/p/demo/testutils v0.0.0-latest
gno.land/p/demo/ufmt v0.0.0-latest
)
153 changes: 153 additions & 0 deletions examples/gno.land/r/demo/userbook/userbook.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// This realm demonstrates a small userbook system working with gnoweb
package userbook

import (
"std"
"strconv"

"gno.land/p/demo/avl"
"gno.land/p/demo/mux"
"gno.land/p/demo/ufmt"
)

type Signup struct {
account string
height int64
}

// signups - keep a slice of signed up addresses efficient pagination
var signups []Signup

// tracker - keep track of who signed up
var (
tracker *avl.Tree
router *mux.Router
)

const (
defaultPageSize = 20
pathArgument = "number"
subPath = "page/{" + pathArgument + "}"
)

func init() {
// Set up tracker tree
tracker = avl.NewTree()

// Set up route handling
router = mux.NewRouter()
router.HandleFunc("", renderHelper)
router.HandleFunc(subPath, renderHelper)

// Sign up the deployer
SignUp()
}

func SignUp() string {
// Get transaction caller
caller := std.PrevRealm().Addr().String()
height := std.GetHeight()

if _, exists := tracker.Get(caller); exists {
panic(caller + " is already signed up!")
}

tracker.Set(caller, struct{}{})
signup := Signup{
caller,
height,
}

signups = append(signups, signup)
return ufmt.Sprintf("%s added to userbook up at block #%d!", signup.account, signup.height)
}

func GetSignupsInRange(page, pageSize int) ([]Signup, int) {
if page < 1 {
panic("page number cannot be less than 1")
}
leohhhn marked this conversation as resolved.
Show resolved Hide resolved

if pageSize < 1 || pageSize > 50 {
panic("page size must be from 1 to 50")
}

// Pagination
// Calculate indexes
startIndex := (page - 1) * pageSize
endIndex := startIndex + pageSize

// If page does not contain any users
if startIndex >= len(signups) {
return nil, -1
}

// If page contains fewer users than the page size
if endIndex > len(signups) {
endIndex = len(signups)
}

return signups[startIndex:endIndex], endIndex
}

func renderHelper(res *mux.ResponseWriter, req *mux.Request) {
totalSignups := len(signups)
res.Write("# Welcome to UserBook!\n\n")

// Get URL parameter
page, err := strconv.Atoi(req.GetVar("number"))
if err != nil {
page = 1 // render first page on bad input
}

// Fetch paginated signups
fetchedSignups, endIndex := GetSignupsInRange(page, defaultPageSize)
// Handle empty page case
if len(fetchedSignups) == 0 {
res.Write("No users on this page!\n\n")
res.Write("---\n\n")
res.Write("[Back to Page #1](/r/demo/userbook:page/1)\n\n")
leohhhn marked this conversation as resolved.
Show resolved Hide resolved
return
}

// Write page title
res.Write(ufmt.Sprintf("## UserBook - Page #%d:\n\n", page))

// Write signups
pageStartIndex := defaultPageSize * (page - 1)
for i, signup := range fetchedSignups {
out := ufmt.Sprintf("#### User #%d - %s - signed up at Block #%d\n", pageStartIndex+i, signup.account, signup.height)
res.Write(out)
}

res.Write("---\n\n")

// Write UserBook info
latestSignupIndex := totalSignups - 1
res.Write(ufmt.Sprintf("#### Total users: %d\n", totalSignups))
res.Write(ufmt.Sprintf("#### Latest signup: User #%d at Block #%d\n", latestSignupIndex, signups[latestSignupIndex].height))

res.Write("---\n\n")

// Write page number
res.Write(ufmt.Sprintf("You're viewing page #%d", page))

// Write navigation buttons
var prevPage string
var nextPage string
// If we are on any page that is not the first page
if page > 1 {
prevPage = ufmt.Sprintf(" - [Previous page](/r/demo/userbook:page/%d)", page-1)
}

// If there are more pages after the current one
if endIndex < totalSignups {
nextPage = ufmt.Sprintf(" - [Next page](/r/demo/userbook:page/%d)\n\n", page+1)
}

res.Write(prevPage)
res.Write(nextPage)
}

func Render(path string) string {
return router.Render(path)
}
79 changes: 79 additions & 0 deletions examples/gno.land/r/demo/userbook/userbook_test.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package userbook

import (
"std"
"strings"
"testing"

"gno.land/p/demo/testutils"
"gno.land/p/demo/ufmt"
)

func TestRender(t *testing.T) {
// Sign up 20 users + deployer
for i := 0; i < 20; i++ {
addrName := ufmt.Sprintf("test%d", i)
caller := testutils.TestAddress(addrName)
std.TestSetOrigCaller(caller)
SignUp()
}

testCases := []struct {
name string
nextPage bool
prevPage bool
path string
expectedNumberOfUsers int
}{
{
name: "1st page render",
nextPage: true,
prevPage: false,
path: "page/1",
expectedNumberOfUsers: 20,
},
{
name: "2nd page render",
nextPage: false,
prevPage: true,
path: "page/2",
expectedNumberOfUsers: 1,
},
{
name: "Invalid path render",
nextPage: true,
prevPage: false,
path: "page/invalidtext",
expectedNumberOfUsers: 20,
},
{
name: "Empty Page",
nextPage: false,
prevPage: false,
path: "page/1000",
expectedNumberOfUsers: 0,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
got := Render(tc.path)
numUsers := countUsers(got)

if tc.prevPage && !strings.Contains(got, "Previous page") {
t.Fatalf("expected to find Previous page, didn't find it")
}
if tc.nextPage && !strings.Contains(got, "Next page") {
t.Fatalf("expected to find Next page, didn't find it")
}

if tc.expectedNumberOfUsers != numUsers {
t.Fatalf("expected %d, got %d users", tc.expectedNumberOfUsers, numUsers)
}
})
}
}

func countUsers(input string) int {
return strings.Count(input, "#### User #")
}
Loading