update curd & code logic

This commit is contained in:
Sakurasan
2023-03-29 22:58:02 +08:00
parent 8985c03ac9
commit 312a0b48dc
6 changed files with 344 additions and 177 deletions

View File

@@ -1,18 +1,38 @@
package db
import "gorm.io/gorm"
import "time"
type Key struct {
gorm.Model
ApiKey string
UserId string
ID uint `gorm:"primarykey" json:"id,omitempty"`
Key string `gorm:"unique;not null" json:"key,omitempty"`
Name string `gorm:"unique;not null" json:"name,omitempty"`
UserId string `json:"-,omitempty"`
CreatedAt time.Time `json:"createdAt,omitempty"`
UpdatedAt time.Time `json:"updatedAt,omitempty"`
}
func GetKeyrByName(name string) (*Key, error) {
var key Key
result := db.First(&key, "name = ?", name)
if result.Error != nil {
return nil, result.Error
}
return &key, nil
}
func GetAllKeys() ([]Key, error) {
var keys []Key
if err := db.Find(&keys).Error; err != nil {
return nil, err
}
return keys, nil
}
// 添加记录
func AddKey(apiKey string, userId string) error {
func AddKey(apikey, name string) error {
key := Key{
ApiKey: apiKey,
UserId: userId,
Key: apikey,
Name: name,
}
if err := db.Create(&key).Error; err != nil {
return err
@@ -29,9 +49,9 @@ func DeleteKey(id uint) error {
}
// 更新记录
func UpdateKey(id uint, apiKey string, userId string) error {
func UpdateKey(id uint, apikey string, userId string) error {
key := Key{
ApiKey: apiKey,
Key: apikey,
UserId: userId,
}
if err := db.Model(&Key{}).Where("id = ?", id).Updates(key).Error; err != nil {