Skip to content

Commit

Permalink
Merge pull request #73 from sev-2/feature/model-runner-binding
Browse files Browse the repository at this point in the history
FEAT Model binding on Model Runner
  • Loading branch information
toopay authored Sep 27, 2024
2 parents 8695817 + 899f04e commit a269643
Show file tree
Hide file tree
Showing 12 changed files with 83 additions and 52 deletions.
3 changes: 2 additions & 1 deletion pkg/db/aggregate.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ func (q *Query) Count(opts ...CountOptions) (int, error) {
headers["Prefer"] = "count=" + countVal
headers["Range-Unit"] = "items"

_, resp, err := PostgrestRequest(q.Context, fasthttp.MethodHead, url, nil, headers)
var a interface{}
resp, err := PostgrestRequestBind(q.Context, fasthttp.MethodHead, url, nil, headers, q.ByPass, &a)
if err != nil {
return 0, err
}
Expand Down
23 changes: 15 additions & 8 deletions pkg/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type Query struct {
LimitValue int
OffsetValue int
Errors []error
ByPass bool
}

type ModelBase struct {
Expand All @@ -34,6 +35,7 @@ func (q *Query) HasError() bool {
func NewQuery(ctx raiden.Context) *Query {
return &Query{
Context: ctx,
ByPass: false,
}
}

Expand All @@ -47,6 +49,11 @@ func (q *Query) From(m interface{}) *Query {
return q
}

func (q *Query) AsSystem() *Query {
q.ByPass = true
return q
}

func GetTable(m interface{}) string {
t := reflect.TypeOf(m)

Expand All @@ -69,35 +76,35 @@ func (m *ModelBase) Execute() (model *ModelBase) {
return m
}

func (q Query) Get() ([]byte, error) {
func (q Query) Get(collection interface{}) error {

url := q.GetUrl()

headers := make(map[string]string)
headers["Content-Type"] = "application/json"
headers["Prefer"] = "return=representation"

resp, _, err := PostgrestRequest(q.Context, fasthttp.MethodGet, url, nil, headers)
_, err := PostgrestRequestBind(q.Context, fasthttp.MethodGet, url, nil, headers, q.ByPass, collection)
if err != nil {
return nil, err
return err
}

return resp, nil
return nil
}

func (q Query) Single() ([]byte, error) {
func (q Query) Single(model interface{}) error {
url := q.Limit(1).GetUrl()

headers := make(map[string]string)

headers["Accept"] = "application/vnd.pgrst.object+json"

res, _, err := PostgrestRequest(q.Context, "GET", url, nil, headers)
_, err := PostgrestRequestBind(q.Context, "GET", url, nil, headers, q.ByPass, model)
if err != nil {
return nil, err
return err
}

return res, nil
return nil
}

func (q Query) GetUrl() string {
Expand Down
13 changes: 11 additions & 2 deletions pkg/db/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,22 @@ func TestGetTable(t *testing.T) {
}

func TestSingle(t *testing.T) {
_, err := NewQuery(&mockRaidenContext).Model(articleMockModel).Single()
var articleMockModel = ArticleMockModel{}
err := NewQuery(&mockRaidenContext).Model(articleMockModel).Single(&articleMockModel)

assert.NoError(t, err)
}

func TestGet(t *testing.T) {
_, err := NewQuery(&mockRaidenContext).Model(articleMockModel).Get()
var collection interface{}
err := NewQuery(&mockRaidenContext).Model(articleMockModel).Get(&collection)

assert.NoError(t, err)
}

func TestByPass(t *testing.T) {
var collection interface{}
err := NewQuery(&mockRaidenContext).Model(articleMockModel).AsSystem().Get(&collection)

assert.NoError(t, err)
}
9 changes: 5 additions & 4 deletions pkg/db/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@ import (
"github.com/valyala/fasthttp"
)

func (q *Query) Delete() ([]byte, error) {
func (q *Query) Delete() error {
url := q.GetUrl()

headers := make(map[string]string)
headers["Content-Type"] = "application/json"
headers["Prefer"] = "return=representation"

resp, _, err := PostgrestRequest(q.Context, fasthttp.MethodDelete, url, nil, headers)
var a interface{}
_, err := PostgrestRequestBind(q.Context, fasthttp.MethodDelete, url, nil, headers, q.ByPass, &a)
if err != nil {
return nil, err
return err
}

return resp, nil
return nil
}
2 changes: 1 addition & 1 deletion pkg/db/delete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

func TestDelete(t *testing.T) {
_, err := NewQuery(&mockRaidenContext).Model(articleMockModel).Delete()
err := NewQuery(&mockRaidenContext).Model(articleMockModel).Delete()

assert.NoError(t, err)
}
12 changes: 6 additions & 6 deletions pkg/db/insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import (
"github.com/valyala/fasthttp"
)

func (q *Query) Insert(payload interface{}) ([]byte, error) {
func (q *Query) Insert(payload interface{}, model interface{}) error {
jsonData, err := json.Marshal(payload)
if err != nil {
return nil, err
return err
}

url := q.GetUrl()
Expand All @@ -18,10 +18,10 @@ func (q *Query) Insert(payload interface{}) ([]byte, error) {
headers["Content-Type"] = "application/json"
headers["Prefer"] = "return=representation"

body, _, err := PostgrestRequest(q.Context, fasthttp.MethodPost, url, jsonData, headers)
if err != nil {
return nil, err
_, err0 := PostgrestRequestBind(q.Context, fasthttp.MethodPost, url, jsonData, headers, q.ByPass, model)
if err0 != nil {
return err0
}

return body, nil
return nil
}
4 changes: 2 additions & 2 deletions pkg/db/insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ func TestInsert(t *testing.T) {
CreatedAt: time.Now(),
}

_, err := NewQuery(&mockRaidenContext).
err := NewQuery(&mockRaidenContext).
Model(articleMockModel).
Insert(article)
Insert(article, &articleMockModel)

assert.NoError(t, err)
}
38 changes: 25 additions & 13 deletions pkg/db/postgrest_request.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package db

import (
"encoding/json"
"flag"
"fmt"
"strings"
Expand All @@ -9,10 +10,10 @@ import (
"github.com/valyala/fasthttp"
)

func PostgrestRequest(ctx raiden.Context, method string, url string, payload []byte, headers map[string]string) ([]byte, *fasthttp.Response, error) {
func PostgrestRequestBind(ctx raiden.Context, method string, url string, payload []byte, headers map[string]string, bypass bool, result interface{}) (*fasthttp.Response, error) {

if !isAllowedMethod(method) {
return nil, nil, fmt.Errorf("method %s is not allowed", method)
return nil, fmt.Errorf("method %s is not allowed", method)
}

client := &fasthttp.Client{}
Expand All @@ -38,15 +39,20 @@ func PostgrestRequest(ctx raiden.Context, method string, url string, payload []b
req.SetRequestURI(url)
req.Header.SetMethod(method)

apikey := string(ctx.RequestContext().Request.Header.Peek("apikey"))
if apikey != "" {
req.Header.Set("apikey", apikey)
}

bearerToken := string(ctx.RequestContext().Request.Header.Peek("Authorization"))
if bearerToken != "" && strings.HasPrefix(bearerToken, "Bearer ") {
bearerToken = strings.TrimSpace(strings.TrimPrefix(bearerToken, "Bearer "))
req.Header.Set("Authorization", bearerToken)
if bypass {
if flag.Lookup("test.v") == nil {
req.Header.Set("apikey", getConfig().ServiceKey)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", getConfig().ServiceKey))
}
} else {
apikey := string(ctx.RequestContext().Request.Header.Peek("apikey"))
if apikey != "" {
req.Header.Set("apikey", apikey)
}
bearerToken := string(ctx.RequestContext().Request.Header.Peek("Authorization"))
if bearerToken != "" && strings.HasPrefix(bearerToken, "Bearer ") {
req.Header.Set("Authorization", bearerToken)
}
}

for key, value := range headers {
Expand All @@ -61,12 +67,18 @@ func PostgrestRequest(ctx raiden.Context, method string, url string, payload []b
defer fasthttp.ReleaseResponse(res)

if err := client.Do(req, res); err != nil {
return nil, res, err
return res, err
}

body := res.Body()

return body, res, nil
if result != nil {
if err := json.Unmarshal(body, result); err != nil {
return res, fmt.Errorf("failed to unmarshal response body: %w", err)
}
}

return res, nil
}

func isAllowedMethod(method string) bool {
Expand Down
12 changes: 6 additions & 6 deletions pkg/db/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
"github.com/valyala/fasthttp"
)

func (q *Query) Update(p interface{}) ([]byte, error) {
func (q *Query) Update(p interface{}, model interface{}) error {
jsonData, err := json.Marshal(p)
if err != nil {
return nil, err
return err
}

url := q.GetUrl()
Expand All @@ -29,10 +29,10 @@ func (q *Query) Update(p interface{}) ([]byte, error) {
headers["Content-Type"] = "application/json"
headers["Prefer"] = "return=representation"

body, _, err := PostgrestRequest(q.Context, fasthttp.MethodPatch, url, jsonData, headers)
if err != nil {
return nil, err
_, err0 := PostgrestRequestBind(q.Context, fasthttp.MethodPatch, url, jsonData, headers, q.ByPass, model)
if err0 != nil {
return err0
}

return body, nil
return nil
}
4 changes: 2 additions & 2 deletions pkg/db/update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ func TestUpdate(t *testing.T) {
CreatedAt: time.Now(),
}

_, err := NewQuery(&mockRaidenContext).
err := NewQuery(&mockRaidenContext).
Model(articleMockModel).
Eq("id", 1).
Update(article)
Update(article, &articleMockModel)

assert.NoError(t, err)
}
13 changes: 7 additions & 6 deletions pkg/db/upsert.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ const (
IgnoreDuplicates = "ignore-duplicates"
)

func (q *Query) Upsert(payload []interface{}, opt UpsertOptions) ([]byte, error) {
func (q *Query) Upsert(payload []interface{}, opt UpsertOptions) error {
jsonData, err := json.Marshal(payload)
if err != nil {
return nil, err
return err
}

url := q.GetUrl()
Expand All @@ -27,10 +27,11 @@ func (q *Query) Upsert(payload []interface{}, opt UpsertOptions) ([]byte, error)
headers["Content-Type"] = "application/json"
headers["Prefer"] = "resolution=" + opt.OnConflict

resp, _, err := PostgrestRequest(q.Context, fasthttp.MethodPost, url, jsonData, headers)
if err != nil {
return nil, err
var a interface{}
_, err0 := PostgrestRequestBind(q.Context, fasthttp.MethodPost, url, jsonData, headers, q.ByPass, &a)
if err0 != nil {
return err0
}

return resp, nil
return nil
}
2 changes: 1 addition & 1 deletion pkg/db/upsert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func TestUpsert(t *testing.T) {
OnConflict: MergeDuplicates,
}

_, err := NewQuery(&mockRaidenContext).
err := NewQuery(&mockRaidenContext).
Model(articleMockModel).
Upsert(payload, opt)

Expand Down

0 comments on commit a269643

Please sign in to comment.