-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
clientCreateHandler.go
66 lines (57 loc) · 2.21 KB
/
clientCreateHandler.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
package service
import (
"fmt"
coapMessage "github.com/plgd-dev/go-coap/v2/message"
coapCodes "github.com/plgd-dev/go-coap/v2/message/codes"
"github.com/plgd-dev/go-coap/v2/mux"
"github.com/plgd-dev/go-coap/v2/tcp/message/pool"
"github.com/plgd-dev/hub/v2/coap-gateway/coapconv"
"github.com/plgd-dev/hub/v2/coap-gateway/service/message"
"github.com/plgd-dev/hub/v2/resource-aggregate/commands"
)
const errFmtCreateResource = "cannot handle create resource%v: %w"
func getCreateResourceErr(err error) error {
if err == nil {
return nil
}
return fmt.Errorf(errFmtCreateResource, "", err)
}
func clientCreateHandler(req *mux.Message, client *Client) (*pool.Message, error) {
_, err := client.GetAuthorizationContext()
if err != nil {
return nil, statusErrorf(coapCodes.Unauthorized, "%w", getCreateResourceErr(err))
}
deviceID, href, err := message.URIToDeviceIDHref(req)
if err != nil {
return nil, statusErrorf(coapCodes.BadRequest, "%w", getCreateResourceErr(err))
}
code := coapCodes.Created
content, err := clientCreateDeviceHandler(req, client, deviceID, href)
if err != nil {
code = coapconv.GrpcErr2CoapCode(err, coapconv.Create)
return nil, statusErrorf(code, errFmtCreateResource, fmt.Sprintf(" /%v%v", deviceID, href), err)
}
if content == nil || len(content.Data) == 0 {
return client.createResponse(code, req.Token, coapMessage.TextPlain, nil), nil
}
mediaType, err := coapconv.MakeMediaType(-1, content.ContentType)
if err != nil {
return nil, statusErrorf(coapCodes.BadRequest, "cannot encode response for create resource %v: %w", fmt.Sprintf(" /%v%v", deviceID, href), err)
}
return client.createResponse(code, req.Token, mediaType, content.Data), nil
}
func clientCreateDeviceHandler(req *mux.Message, client *Client, deviceID, href string) (*commands.Content, error) {
createCommand, err := coapconv.NewCreateResourceRequest(commands.NewResourceID(deviceID, href), req, client.RemoteAddr().String())
if err != nil {
return nil, err
}
createdEvent, err := client.server.raClient.SyncCreateResource(req.Context, "*", createCommand)
if err != nil {
return nil, err
}
content, err := commands.EventContentToContent(createdEvent)
if err != nil {
return nil, err
}
return content, nil
}