-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaction.go
76 lines (60 loc) · 1.75 KB
/
action.go
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
package appserver
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
)
var ErrActionMissingAction = errors.New("missing action or entity")
type ActionHandlerNotFoundError struct {
entity string
action string
}
func (e ActionHandlerNotFoundError) Error() string {
return fmt.Sprintf("no action handler found for entity %s, action %s", e.entity, e.action)
}
type ActionHandler func(ctx context.Context, action ActionRequest, api *APIClient) error
type ActionRequest struct {
*AppRequest
Data struct {
IDs []string `json:"ids"`
Entity string `json:"entity"`
Action string `json:"action"`
} `json:"data"`
Meta struct {
Timestamp int64 `json:"timestamp"`
ReferenceID string `json:"reference"`
LanguageID string `json:"language"`
} `json:"meta"`
}
func (srv *Server) HandleAction(req *http.Request) error {
if err := srv.verifyPayloadSignature(req); err != nil {
return err
}
body, err := extractBody(req)
if err != nil {
return fmt.Errorf("extract body: %w", err)
}
actionReq := ActionRequest{}
err = json.Unmarshal(body, &actionReq)
if err != nil {
return fmt.Errorf("parse body: %w", err)
}
if len(actionReq.Data.Action) == 0 || len(actionReq.Data.Entity) == 0 {
return ErrActionMissingAction
}
h, ok := srv.actions[actionReq.Data.Entity+actionReq.Data.Action]
if !ok {
return ActionHandlerNotFoundError{entity: actionReq.Data.Entity, action: actionReq.Data.Action}
}
credentials, err := srv.credentialStore.Get(req.Context(), actionReq.Source.ShopID)
if err != nil {
return fmt.Errorf("get shop credentials: %w", err)
}
err = h(req.Context(), actionReq, newAPIClient(srv.httpClient, srv.appName, credentials, srv.tokenStore))
if err != nil {
return fmt.Errorf("handler: %w", err)
}
return nil
}