Skip to content

Commit

Permalink
Add example app
Browse files Browse the repository at this point in the history
  • Loading branch information
mikogs committed Jan 10, 2025
1 parent e5c0f6b commit 3ffd92a
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 15 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/cmd/sample-user/sample-user
25 changes: 25 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
.DEFAULT_GOAL := help

.PHONY: help test

test: ## Runs tests
go test

start-db:
@echo "* Creating docker container with PostgreSQL"
docker run --name crud-sample-user-db -d -e POSTGRES_PASSWORD=crudpass -e POSTGRES_USER=cruduser -e POSTGRES_DB=crud -p 54321:5432 postgres:13
@echo "* Sleeping for 10 seconds to give database time to initialize..."
@sleep 10

run-sample-user: clean start-db ## Runs sample-user app
@echo "* Building and starting application..."
@echo "* Please run 'make clean' after terminating the application!"
cd cmd/sample-user && go build .
cd cmd/sample-user && ./sample-user

clean: ## Removes all created dockers
@echo "* Removing previously created docker container..."
docker rm -f crud-sample-user-db

help: ## Displays this help
@awk 'BEGIN {FS = ":.*##"; printf "$(MAKEFILE_NAME)\n\nUsage:\n make \033[1;36m<target>\033[0m\n\nTargets:\n"} /^[a-zA-Z0-9_-]+:.*?##/ { printf " \033[1;36m%-25s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST)
28 changes: 14 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ defer conn.Close()
c := crud.NewController(conn, "app1_", nil)
user := &User{}
err = c.CreateTable(user) // Run 'CREATE TABLE'
// Database tables have to be created. This could be done using some ORM like struct-db-postgres or it can be done manually.
```

#### ControllerConfig
Expand All @@ -119,43 +119,43 @@ meant to change when permorming update, `User_UpdatePassword` is an additional s
password, and finally - fields in `User_List` will be visible when listing users or reading one user. (You can
define these as you like).
```
type User_Create {
type User_Create struct {
ID int `json:"user_id"`
Name string `json:"name" crud:"req lenmin:2 lenmax:50"`
Email string `json:"email" crud:"req"`
Password string `json:"password"`
}
type User_Update {
type User_Update struct {
ID int `json:"user_id"`
Name string `json:"name" crud:"req lenmin:2 lenmax:50"`
Email string `json:"email" crud:"req"`
}
type User_UpdatePassword {
type User_UpdatePassword struct {
ID int `json:"user_id"`
Password string `json:"password"`
}
type User_List {
type User_List struct {
ID int `json:"user_id"`
Name string `json:"name"
Name string `json:"name"`
}
```

```
var parentFunc = func() interface{} { return &User; }
var createFunc = func() interface{} { return &User_Create; }
var readFunc = func() interface{} { return &User_List; }
var updateFunc = func() interface{} { return &User_Update; }
var listFunc = func() interface{} { return &User_List; }
var parentFunc = func() interface{} { return &User{}; }
var createFunc = func() interface{} { return &User_Create{}; }
var readFunc = func() interface{} { return &User_List{}; }
var updateFunc = func() interface{} { return &User_Update{}; }
var listFunc = func() interface{} { return &User_List{}; }
var updatePasswordFunc = func() interface{} { return &User_UpdatePassword; }
var updatePasswordFunc = func() interface{} { return &User_UpdatePassword{}; }
http.HandleFunc("/users/", c.Handler("/users/", parentFunc, HandlerOptions{
http.Handle("/users/", c.Handler("/users/", parentFunc, HandlerOptions{
CreateConstructor: createFunc, // input fields (and JSON payload) for creating
ReadConstructor: readFunc, // output fields (and JSON output) for reading
UpdateConstructor: updateFunc, // input fields (and JSON payload) for updating
ListConstructor: listFunc, // fields to appear when listing items (and JSON output)
}))
http.HandleFunc("/users/password/", c.Handler("/users/password/", parentFunc, HandlerOptions{
http.Handle("/users/password/", c.Handler("/users/password/", parentFunc, HandlerOptions{
UpdateConstructor: updatePasswordFunc, // input fields for that one updating endpoint
Operations: OpUpdate, // only updating will be allowed
}))
Expand Down
60 changes: 60 additions & 0 deletions cmd/sample-user/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"database/sql"
"log"
"net/http"

"github.com/go-phings/crud"
structdbpostgres "github.com/go-phings/struct-db-postgres"
_ "github.com/lib/pq"
"golang.org/x/crypto/bcrypt"
)

const dbDSN = "host=localhost user=cruduser password=crudpass port=54321 dbname=crud sslmode=disable"
const tblPrefix = "p_"

func main() {
db, err := sql.Open("postgres", dbDSN)
if err != nil {
log.Fatal("Error connecting to db")
}

orm := structdbpostgres.NewController(db, tblPrefix, &structdbpostgres.ControllerConfig{
TagName: "crud",
})
err = orm.CreateTable(&User{})
if err != nil {
log.Fatalf("Error creating table: %s", err.Error())
}

api := crud.NewController(db, tblPrefix, &crud.ControllerConfig{
PasswordGenerator: func(pass string) string {
passEncrypted, err := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)
if err != nil {
return ""
}
return string(passEncrypted)
},
})

var userConstructor = func() interface{} { return &User{} }
var userConstructorForCreate = func() interface{} { return &User_Create{} }
var userConstructorForRead = func() interface{} { return &User_List{} }
var userConstructorForUpdate = func() interface{} { return &User_Update{} }
var userConstructorForList = func() interface{} { return &User_List{} }

var userConstructorForUpdatePassword = func() interface{} { return &User_UpdatePassword{} }

http.Handle("/users/", api.Handler("/users/", userConstructor, crud.HandlerOptions{
CreateConstructor: userConstructorForCreate, // input fields (and JSON payload) for creating
ReadConstructor: userConstructorForRead, // output fields (and JSON output) for reading
UpdateConstructor: userConstructorForUpdate, // input fields (and JSON payload) for updating
ListConstructor: userConstructorForList, // fields to appear when listing items (and JSON output)
}))
http.Handle("/users/password/", api.Handler("/users/password/", userConstructor, crud.HandlerOptions{
UpdateConstructor: userConstructorForUpdatePassword, // input fields for that one updating endpoint
Operations: crud.OpUpdate, // only updating will be allowed
}))
log.Fatal(http.ListenAndServe(":9001", nil))
}
37 changes: 37 additions & 0 deletions cmd/sample-user/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package main

type User struct {
ID int64 `json:"user_id"`
Flags int64 `json:"flags"`
Name string `json:"name" crud:"lenmin:0 lenmax:50"`
Email string `json:"email" crud:"req"`
Password string `json:"password" crud:"hidden password"`
EmailActivationKey string `json:"email_activation_key" crud:"hidden"`
CreatedAt int64 `json:"created_at"`
CreatedBy int64 `json:"created_by"`
LastModifiedAt int64 `json:"last_modified_at"`
LastModifiedBy int64 `json:"last_modified_by"`
}

type User_Create struct {
ID int `json:"user_id"`
Name string `json:"name" crud:"req lenmin:2 lenmax:50"`
Email string `json:"email" crud:"req"`
Password string `json:"password" crud:"req password"`
}

type User_Update struct {
ID int `json:"user_id"`
Name string `json:"name" crud:"req lenmin:2 lenmax:50"`
Email string `json:"email" crud:"req"`
}

type User_UpdatePassword struct {
ID int `json:"user_id"`
Password string `json:"password" crud:"req password"`
}

type User_List struct {
ID int `json:"user_id"`
Name string `json:"name"`
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/go-phings/struct-validator v0.4.7
github.com/lib/pq v1.10.9
github.com/ory/dockertest/v3 v3.11.0
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
)

require (
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
Expand Down
2 changes: 1 addition & 1 deletion version.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package crud

const VERSION="0.8.0"
const VERSION = "0.8.0"

0 comments on commit 3ffd92a

Please sign in to comment.