add const
This commit is contained in:
59
server/ids/ids.go
Normal file
59
server/ids/ids.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package ids
|
||||
|
||||
// this package is at such a high level in the hierarchy because
|
||||
// it's used by both `server/db` (for now) and `server/ctrlsubsonic`
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrBadSeparator = errors.New("bad separator")
|
||||
ErrNotAnInt = errors.New("not an int")
|
||||
ErrBadPrefix = errors.New("bad prefix")
|
||||
)
|
||||
|
||||
type ID string
|
||||
|
||||
const (
|
||||
// type values copied from subsonic
|
||||
Artist ID = "ar"
|
||||
Album ID = "al"
|
||||
Track ID = "tr"
|
||||
)
|
||||
|
||||
var accepted = []ID{Artist,
|
||||
Album,
|
||||
Track,
|
||||
}
|
||||
|
||||
type IDV struct {
|
||||
Type ID
|
||||
Value int
|
||||
}
|
||||
|
||||
func (i IDV) String() string {
|
||||
return fmt.Sprintf("%s-%d", i.Type, i.Value)
|
||||
}
|
||||
|
||||
func Parse(in string) (IDV, error) {
|
||||
parts := strings.Split(in, "-")
|
||||
if len(parts) != 2 {
|
||||
return IDV{}, ErrBadSeparator
|
||||
}
|
||||
partType := parts[0]
|
||||
partValue := parts[1]
|
||||
val, err := strconv.Atoi(partValue)
|
||||
if err != nil {
|
||||
return IDV{}, fmt.Errorf("%q: %w", partValue, ErrNotAnInt)
|
||||
}
|
||||
for _, acc := range accepted {
|
||||
if partType == string(acc) {
|
||||
return IDV{Type: acc, Value: val}, nil
|
||||
}
|
||||
}
|
||||
return IDV{}, fmt.Errorf("%q: %w", partType, ErrBadPrefix)
|
||||
}
|
||||
35
server/ids/ids_test.go
Normal file
35
server/ids/ids_test.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package ids
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
tcases := []struct {
|
||||
param string
|
||||
expType ID
|
||||
expValue int
|
||||
expErr error
|
||||
}{
|
||||
{param: "al-45", expType: Album, expValue: 45},
|
||||
{param: "ar-2", expType: Artist, expValue: 2},
|
||||
{param: "tr-43", expType: Track, expValue: 43},
|
||||
{param: "xx-1", expErr: ErrBadPrefix},
|
||||
{param: "al-howdy", expErr: ErrNotAnInt},
|
||||
}
|
||||
for _, tcase := range tcases {
|
||||
t.Run(tcase.param, func(t *testing.T) {
|
||||
act, err := Parse(tcase.param)
|
||||
if !errors.Is(err, tcase.expErr) {
|
||||
t.Fatalf("expected err %q, got %q", tcase.expErr, err)
|
||||
}
|
||||
if act.Value != tcase.expValue {
|
||||
t.Errorf("expected value %d, got %d", tcase.expValue, act.Value)
|
||||
}
|
||||
if act.Type != tcase.expType {
|
||||
t.Errorf("expected type %v, got %v", tcase.expType, act.Type)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user