memos/api/v2/resource_name.go

47 lines
1.1 KiB
Go
Raw Normal View History

2023-10-27 09:01:17 +08:00
package v2
import (
"fmt"
"strconv"
"strings"
"github.com/pkg/errors"
)
const (
2023-10-28 02:43:46 +08:00
InboxNamePrefix = "inboxes/"
2023-10-27 09:01:17 +08:00
)
// GetNameParentTokens returns the tokens from a resource name.
func GetNameParentTokens(name string, tokenPrefixes ...string) ([]string, error) {
parts := strings.Split(name, "/")
if len(parts) != 2*len(tokenPrefixes) {
return nil, errors.Errorf("invalid request %q", name)
}
var tokens []string
for i, tokenPrefix := range tokenPrefixes {
if fmt.Sprintf("%s/", parts[2*i]) != tokenPrefix {
return nil, errors.Errorf("invalid prefix %q in request %q", tokenPrefix, name)
}
if parts[2*i+1] == "" {
return nil, errors.Errorf("invalid request %q with empty prefix %q", name, tokenPrefix)
}
tokens = append(tokens, parts[2*i+1])
}
return tokens, nil
}
// GetInboxID returns the inbox ID from a resource name.
func GetInboxID(name string) (int32, error) {
tokens, err := GetNameParentTokens(name, InboxNamePrefix)
if err != nil {
return 0, err
}
id, err := strconv.Atoi(tokens[0])
if err != nil {
return 0, errors.Errorf("invalid inbox ID %q", tokens[0])
}
return int32(id), nil
}