MCPcopy Create free account
hub / github.com/astercloud/aster / AddPreference

Method AddPreference

pkg/memory/preference.go:105–140  ·  view source on GitHub ↗

AddPreference 添加偏好

(ctx context.Context, pref *Preference)

Source from the content-addressed store, hash-verified

103
104// AddPreference 添加偏好
105func (pm *PreferenceManager) AddPreference(ctx context.Context, pref *Preference) error {
106 pm.mu.Lock()
107 defer pm.mu.Unlock()
108
109 // 检查是否已存在相同的偏好
110 existing := pm.findExistingPreference(pref.UserID, pref.Category, pref.Key)
111
112 if existing != nil {
113 // 处理冲突
114 return pm.handleConflict(existing, pref)
115 }
116
117 // 检查偏好数量限制
118 if len(pm.preferences[pref.UserID]) >= pm.config.MaxPreferencesPerUser {
119 return fmt.Errorf("max preferences limit reached for user %s", pref.UserID)
120 }
121
122 // 生成 ID
123 if pref.ID == "" {
124 pref.ID = fmt.Sprintf("pref-%s-%d", pref.UserID, time.Now().UnixNano())
125 }
126
127 // 设置时间戳
128 now := time.Now()
129 pref.CreatedAt = now
130 pref.UpdatedAt = now
131
132 // 添加到存储
133 pm.preferences[pref.UserID] = append(pm.preferences[pref.UserID], pref)
134
135 // 更新索引
136 indexKey := fmt.Sprintf("%s:%s", pref.UserID, pref.Category)
137 pm.categoryIndex[indexKey] = append(pm.categoryIndex[indexKey], pref)
138
139 return nil
140}
141
142// findExistingPreference 查找已存在的偏好
143func (pm *PreferenceManager) findExistingPreference(

Calls 2

handleConflictMethod · 0.95