nanoapicrudpostgres

package module
v0.0.0-...-fc40b3c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 8, 2022 License: MIT Imports: 11 Imported by: 0

README

nanoapi-crud-postgres

Sample API Setup

package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"time"

	"github.com/digitalcircle-com-br/nanoapi"
	napi "github.com/digitalcircle-com-br/nanoapi"
	nauth "github.com/digitalcircle-com-br/nanoapi-auth-postgres"
	crud "github.com/digitalcircle-com-br/nanoapi-crud-postgres"
	nsession "github.com/digitalcircle-com-br/nanoapi-session-redis"
)

type Master struct {
	crud.BaseVO
	Txt     string
	Details []Detail `gorm:"many2many:master_detail;"`
}

type Detail struct {
	crud.BaseVO
	Txt string
}

type Detail2 struct {
	crud.BaseVO
	Txt string
}
type BRequest struct {
	A string    `json:"a"`
	B time.Time `json:"b"`
	C int       `json:"c"`
}

type BResponse struct {
	ARes string    `json:"ares"`
	BRes time.Time `json:"bres"`
}

func main() {
	napi.Setup() //ligando o motor
	crud.Setup()
	nauth.Setup()    //plugin para auth no postgres
	nsession.Setup() //plugin de sessao no redis
	crud.Register("d", &Detail{})
	crud.Register("d2", &Detail2{})
	crud.Register("m", &Master{})

	m := Master{Details: make([]Detail, 0), Txt: "Master A"}
	m.SetTenant("root")
	for i := 0; i < 10; i++ {
		d := Detail{Txt: fmt.Sprintf("Detail: %v", i)}
		m.Details = append(m.Details, d)
		crud.Db().Save(&d)
		d2 := Detail2{Txt: fmt.Sprintf("Detail: %v", i)}
		crud.Db().Save(&d2)
		// m.D2 = append(m.D2, d2)
	}
	crud.Db().Save(&m)

	nauth.SetupPerm() //habilita permissões
	nauth.AddPerm("*", "a")
	nauth.AddPerm("+", "b", "crud_m", "crud_d")

	//exemplo de middleware
	napi.AddMW(func(nh http.HandlerFunc) http.HandlerFunc {
		return func(rw http.ResponseWriter, r *http.Request) {
			cmd := napi.ReqCmd(r)
			log.Printf("BEFORE - " + cmd)
			nh(rw, r)
			log.Printf("AFTER - " + cmd)
		}
	})

	//handler a é privado
	nanoapi.H("a", func(ctx context.Context, i string) (string, error) {
		log.Printf("Got: " + i)
		return "GOT FROM A: " + i, nil
	})

	//handler b é publico
	nanoapi.H("b", func(ctx context.Context, in BRequest) (BResponse, error) {
		nanoapi.Log(nanoapi.CtxReq(ctx).Header.Get("Content-Type"))
		nanoapi.Log(nanoapi.CtxReq(ctx).URL.RawQuery)
		mpf := nanoapi.CtxMPF(ctx)

		for k, fs := range mpf.File {
			for _, f := range fs {
				r, err := f.Open()
				if err != nil {
					return BResponse{}, err
				}
				defer r.Close()
				nanoapi.Log("Reading: %s:%s, %v", k, f.Filename, f.Size)
				io.Copy(log.Writer(), r)
			}
		}
		log.Printf("%#v", in)
		res := BResponse{ARes: "Got this", BRes: time.Now()}
		return res, nil
	})

	//sera que mudo pra nanoapi.ListenAndServe()?
	http.ListenAndServe(":8080", nanoapi.Mux())

}

Sample Http Operations

###
# @name LOGIN
POST http://localhost:8080/login
Content-Type:  application/json

{
    "username":"root",
    "password":"Aa1234"
}
###
# @name LOGOUT
POST http://localhost:8080/logout
Content-Type:  application/json
Cookie: {{cookie}}

{
    "username":"root",
    "password":"Aa1234"
}
###
# @name CALL_CRUD_D_R
POST http://localhost:8080/crud_d
Content-Type:  application/json
Cookie: {{cookie}}

{
    "op":"R",
    "preload":true
}
###
# @name CALL_CRUD_D_C
POST http://localhost:8080/crud_d
Content-Type:  application/json
Cookie: {{cookie}}

{
    "op":"C",
    "data":{"txt":"from test"}
}
###
# @name CALL_CRUD_M_U
POST http://localhost:8080/crud_m
Content-Type:  application/json
Cookie: {{cookie}}

{
    "op":"U",
    "id":1,
    "data":{"id":1,"details":[{"id":21}]}
}
###
# @name CALL_CRUD_M_ASSOC
POST http://localhost:8080/crud_m
Content-Type:  application/json
Cookie: {{cookie}}

{
    "op":"A",
    "association":"master_detail",
    "masterfield":"master_id",
    "detailfield":"detail_id",
    "masterid":1,
    "detailid":1,
    "id":1,
    "data":{"id":21}
}
###
# @name CALL_CRUD_M_DESSOC
POST http://localhost:8080/crud_m
Content-Type:  application/json
Cookie: {{cookie}}

{
    "op":"X",
    "association":"master_detail",
    "masterfield":"master_id",
    "detailfield":"detail_id",
    "masterid":1,
    "detailid":1,
    "id":1,
    "data":{"id":21}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddQuery

func AddQuery(q, v string)

func Db

func Db() *gorm.DB

func Register

func Register[T VO](t T, opts ...*Opts[T]) error

func Setup

func Setup() error

Types

type BaseVO

type BaseVO struct {
	ID uint   `json:"id"`
	T  string `json:"t"`
}

func (*BaseVO) Id

func (b *BaseVO) Id() uint

func (*BaseVO) SetTenant

func (b *BaseVO) SetTenant(t string)

func (*BaseVO) Tenant

func (b *BaseVO) Tenant() string

type CrudRequest

type CrudRequest[T VO] struct {
	Session     nanoapisession.Session
	Cols        []string          `json:"cols"`
	Id          uint              `json:"id"`
	Data        T                 `json:"data"`
	Op          OP                `json:"op"`
	Q           string            `json:"q"`
	QParams     map[string]string `json:"qparams"`
	Page        int               `json:"page"`
	PageSize    int               `json:"pagesize"`
	Where       string            `json:"where"`
	WParams     []interface{}     `json:"wparams"`
	Preload     bool              `json:"preload"`
	Association string            `json:"association"`
	MasterField string            `json:"masterfield"`
	DetailField string            `json:"detailfield"`
	MasterID    uint              `json:"masterid"`
	DetailID    uint              `json:"detailid"`

	SkipCrudOp bool `json:"skip_crud_op"`
}

type CrudResponse

type CrudResponse[T VO] struct {
	Data         []T   `json:"data"`
	RowsAffected int64 `json:"rowsaffected"`
}

func CrudOp

func CrudOp[T VO](ctx context.Context, t reflect.Type, n string, in *CrudRequest[T]) (*CrudResponse[T], error)

type NONE

type NONE struct{}

type OP

type OP string
const (
	OPCREATE   OP = "C"
	OPRETRIEVE OP = "R"
	OPUPDATE   OP = "U"
	OPDELETE   OP = "D"
	OPASSOC    OP = "A"
	OPDESSOC   OP = "X"
)

type Opts

type Opts[T VO] struct {
	BeforeProcess func(r *CrudRequest[T]) error
	BeforeReply   func(in *CrudRequest[T], out *CrudResponse[T], err error) error
}

type VO

type VO interface {
	SetTenant(t string)
	Tenant() string
	Id() uint
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL