-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
listResources.go
64 lines (54 loc) · 1.66 KB
/
listResources.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
package service
import (
"context"
"fmt"
"io"
"net/http"
"time"
pbGRPC "github.com/plgd-dev/cloud/grpc-gateway/pb"
"github.com/plgd-dev/kit/log"
kitNetGrpc "github.com/plgd-dev/kit/net/grpc"
"github.com/plgd-dev/sdk/schema"
"github.com/valyala/fasthttp"
)
type DeviceResources struct {
Resources map[string]schema.ResourceLink `json:"resources"`
}
type GetResourceLinksResponse struct {
Devices map[string]*DeviceResources `json:"devices"`
}
func (r *RequestHandler) listResources(ctx *fasthttp.RequestCtx, token, sub string) {
log.Debugf("RequestHandler.listResources start")
t := time.Now()
defer func() {
log.Debugf("RequestHandler.listResources takes %v", time.Since(t))
}()
getResourceLinksClient, err := r.rdClient.GetResourceLinks(kitNetGrpc.CtxWithToken(context.Background(), token), &pbGRPC.GetResourceLinksRequest{})
if err != nil {
logAndWriteErrorResponse(fmt.Errorf("cannot list resource directory: %w", err), http.StatusBadRequest, ctx)
return
}
defer getResourceLinksClient.CloseSend()
response := GetResourceLinksResponse{
Devices: make(map[string]*DeviceResources),
}
for {
resLink, err := getResourceLinksClient.Recv()
if err == io.EOF {
break
}
if err != nil {
logAndWriteErrorResponse(fmt.Errorf("cannot list device directory: %w", err), http.StatusBadRequest, ctx)
return
}
device, ok := response.Devices[resLink.GetDeviceId()]
if !ok {
device = &DeviceResources{
Resources: make(map[string]schema.ResourceLink),
}
response.Devices[resLink.GetDeviceId()] = device
}
device.Resources["/"+resLink.GetDeviceId()+resLink.GetHref()] = resLink.ToSchema()
}
writeJson(response, fasthttp.StatusOK, ctx)
}