memos/server/route/api/v2/resource_name.go

85 lines
2.2 KiB
Go
Raw Normal View History

2023-10-27 09:01:17 +08:00
package v2
import (
"fmt"
"strings"
"github.com/pkg/errors"
2023-10-28 09:04:32 +08:00
"github.com/usememos/memos/internal/util"
2023-10-27 09:01:17 +08:00
)
const (
WorkspaceSettingNamePrefix = "settings/"
UserNamePrefix = "users/"
2024-03-18 23:23:53 +08:00
MemoNamePrefix = "memos/"
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
}
func ExtractWorkspaceSettingKeyFromName(name string) (string, error) {
tokens, err := GetNameParentTokens(name, WorkspaceSettingNamePrefix)
if err != nil {
return "", err
}
return tokens[0], nil
}
2024-03-18 12:56:52 +08:00
// ExtractUserIDFromName returns the uid from a resource name.
func ExtractUserIDFromName(name string) (int32, error) {
2023-11-05 23:03:43 +08:00
tokens, err := GetNameParentTokens(name, UserNamePrefix)
if err != nil {
2024-03-18 12:56:52 +08:00
return 0, err
2023-11-05 23:03:43 +08:00
}
2024-03-18 12:56:52 +08:00
id, err := util.ConvertStringToInt32(tokens[0])
if err != nil {
return 0, errors.Errorf("invalid user ID %q", tokens[0])
}
return id, nil
2023-11-05 23:03:43 +08:00
}
2024-03-18 23:23:53 +08:00
// ExtractMemoIDFromName returns the memo ID from a resource name.
func ExtractMemoIDFromName(name string) (int32, error) {
tokens, err := GetNameParentTokens(name, MemoNamePrefix)
if err != nil {
return 0, err
}
id, err := util.ConvertStringToInt32(tokens[0])
if err != nil {
return 0, errors.Errorf("invalid memo ID %q", tokens[0])
}
return id, nil
}
2023-11-05 23:28:09 +08:00
// ExtractInboxIDFromName returns the inbox ID from a resource name.
func ExtractInboxIDFromName(name string) (int32, error) {
2023-10-27 09:01:17 +08:00
tokens, err := GetNameParentTokens(name, InboxNamePrefix)
if err != nil {
return 0, err
}
2023-10-28 09:04:32 +08:00
id, err := util.ConvertStringToInt32(tokens[0])
2023-10-27 09:01:17 +08:00
if err != nil {
return 0, errors.Errorf("invalid inbox ID %q", tokens[0])
}
2023-10-28 09:04:32 +08:00
return id, nil
2023-10-27 09:01:17 +08:00
}