2024-11-26 18:30:58 -05:00
|
|
|
package service
|
2024-11-26 18:28:48 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-12-05 15:50:02 -08:00
|
|
|
"errors"
|
2024-11-26 18:28:48 -05:00
|
|
|
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
|
|
|
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
2024-11-29 15:49:25 -08:00
|
|
|
"github.com/nats-io/nats.go"
|
2024-11-26 18:28:48 -05:00
|
|
|
)
|
|
|
|
|
2024-12-05 15:50:02 -08:00
|
|
|
var (
|
|
|
|
// ErrPermissionDenied caller does not have the required role
|
|
|
|
ErrPermissionDenied = errors.New("Permission denied")
|
|
|
|
// ErrUserInfo user info is missing for some reason
|
|
|
|
ErrUserInfo = errors.New("Missing user info")
|
|
|
|
)
|
|
|
|
|
2024-11-26 18:30:58 -05:00
|
|
|
type Service struct {
|
2024-12-12 17:29:20 -05:00
|
|
|
DB datastore.Datastore
|
2024-12-10 19:30:14 -08:00
|
|
|
Nats nats.JetStreamContext
|
2024-11-26 18:28:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewError creates *ErrorStatusCode from error returned by handler.
|
|
|
|
//
|
|
|
|
// Used for common default response.
|
2024-11-26 18:30:58 -05:00
|
|
|
func (svc *Service) NewError(ctx context.Context, err error) *api.ErrorStatusCode {
|
2024-12-10 21:49:03 -08:00
|
|
|
status := 500
|
2024-12-17 14:36:44 -08:00
|
|
|
if errors.Is(err, datastore.ErrNotExist) {
|
|
|
|
status = 404
|
|
|
|
}
|
2024-12-12 17:29:20 -05:00
|
|
|
if errors.Is(err, ErrPermissionDenied) {
|
2024-12-10 21:49:03 -08:00
|
|
|
status = 403
|
|
|
|
}
|
2024-12-12 17:29:20 -05:00
|
|
|
if errors.Is(err, ErrUserInfo) {
|
2024-12-10 21:49:03 -08:00
|
|
|
status = 401
|
|
|
|
}
|
2024-11-26 18:28:48 -05:00
|
|
|
return &api.ErrorStatusCode{
|
2024-12-10 21:49:03 -08:00
|
|
|
StatusCode: status,
|
2024-12-12 17:29:20 -05:00
|
|
|
Response: api.Error{
|
|
|
|
Code: int64(status),
|
2024-12-10 21:49:03 -08:00
|
|
|
Message: err.Error(),
|
|
|
|
},
|
2024-11-26 18:28:48 -05:00
|
|
|
}
|
|
|
|
}
|