-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
createResource.go
45 lines (40 loc) · 1.05 KB
/
createResource.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
package client
import (
"context"
"fmt"
"github.com/plgd-dev/hub/v2/grpc-gateway/pb"
"github.com/plgd-dev/hub/v2/resource-aggregate/commands"
)
// CreateResource requests creation of a new resource on a collection resource on a device.
func (c *Client) CreateResource(
ctx context.Context,
deviceID string,
href string,
request interface{},
response interface{},
opts ...CreateOption,
) error {
cfg := createOptions{
codec: GeneralMessageCodec{},
}
for _, o := range opts {
cfg = o.applyOnCreate(cfg)
}
data, err := cfg.codec.Encode(request)
if err != nil {
return err
}
r := pb.CreateResourceRequest{
ResourceId: commands.NewResourceID(deviceID, href),
Content: &pb.Content{
Data: data,
ContentType: cfg.codec.ContentFormat().String(),
},
}
resp, err := c.gateway.CreateResource(ctx, &r)
if err != nil {
return fmt.Errorf("cannot create resource /%v%v: %w", deviceID, href, err)
}
content := resp.GetData().GetContent()
return DecodeContentWithCodec(cfg.codec, content.GetContentType(), content.GetData(), response)
}