storj/satellite/console/consoleweb/consoleapi/buckets.go
Vitalii Shpital d30fd77652 satellite/console: new endpoint to get total usage and limits for all the projects user owns
Added new endpoint and service method to return total usage and limits for all the projects that user owns.
It is needed for new paid tier UI

Change-Id: Ic5b67ca7b275ec4930d976a007168235c0500b70
2021-06-25 21:22:59 +00:00

90 lines
2.2 KiB
Go

// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
package consoleapi
import (
"encoding/json"
"net/http"
"github.com/zeebo/errs"
"go.uber.org/zap"
"storj.io/common/uuid"
"storj.io/storj/satellite/console"
)
var (
// ErrBucketsAPI - console buckets api error type.
ErrBucketsAPI = errs.Class("console api buckets")
)
// Buckets is an api controller that exposes all buckets related functionality.
type Buckets struct {
log *zap.Logger
service *console.Service
}
// NewBuckets is a constructor for api buckets controller.
func NewBuckets(log *zap.Logger, service *console.Service) *Buckets {
return &Buckets{
log: log,
service: service,
}
}
// AllBucketNames returns all bucket names for a specific project.
func (b *Buckets) AllBucketNames(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var err error
defer mon.Task()(&ctx)(&err)
w.Header().Set("Content-Type", "application/json")
projectIDString := r.URL.Query().Get("projectID")
projectID, err := uuid.FromString(projectIDString)
if err != nil {
b.serveJSONError(w, http.StatusInternalServerError, err)
return
}
bucketNames, err := b.service.GetAllBucketNames(ctx, projectID)
if err != nil {
if console.ErrUnauthorized.Has(err) {
b.serveJSONError(w, http.StatusUnauthorized, err)
return
}
b.serveJSONError(w, http.StatusInternalServerError, err)
return
}
err = json.NewEncoder(w).Encode(bucketNames)
if err != nil {
b.log.Error("failed to write json all bucket names response", zap.Error(ErrBucketsAPI.Wrap(err)))
}
}
// serveJSONError writes JSON error to response output stream.
func (b *Buckets) serveJSONError(w http.ResponseWriter, status int, err error) {
if status == http.StatusInternalServerError {
b.log.Error("returning error to client", zap.Int("code", status), zap.Error(err))
} else {
b.log.Debug("returning error to client", zap.Int("code", status), zap.Error(err))
}
w.WriteHeader(status)
var response struct {
Error string `json:"error"`
}
response.Error = err.Error()
err = json.NewEncoder(w).Encode(response)
if err != nil {
b.log.Error("failed to write json error response", zap.Error(ErrBucketsAPI.Wrap(err)))
}
}