|
|
package postgres
import ( "context" "database/sql" "git.aiterp.net/rpdata/api/database/postgres/psqlcore" "git.aiterp.net/rpdata/api/internal/generate" "git.aiterp.net/rpdata/api/models" )
type keyRepository struct { db *sql.DB insertWithIDs bool }
func (r *keyRepository) Find(ctx context.Context, id string) (*models.Key, error) { key, err := psqlcore.New(r.db).SelectKey(ctx, id) if err != nil { return nil, err }
return &models.Key{ ID: key.ID, Name: key.Name, User: key.User, Secret: key.Secret, }, nil }
func (r *keyRepository) List(ctx context.Context, filter models.KeyFilter) ([]*models.Key, error) { var keys []psqlcore.Key
if filter.UserID != nil { keys2, err := psqlcore.New(r.db).SelectKeysByUser(ctx, *filter.UserID) if err != nil { return nil, err }
keys = keys2 } else { keys2, err := psqlcore.New(r.db).SelectKeys(ctx) if err != nil { return nil, err }
keys = keys2 }
results := make([]*models.Key, 0, len(keys)) for _, key := range keys { results = append(results, &models.Key{ ID: key.ID, Name: key.Name, User: key.User, Secret: key.Secret, }) }
return results, nil }
func (r *keyRepository) Insert(ctx context.Context, key models.Key) (*models.Key, error) { if !r.insertWithIDs || len(key.ID) < 4 { key.ID = generate.KeyID() }
err := psqlcore.New(r.db).InsertKey(ctx, psqlcore.InsertKeyParams{ ID: key.ID, Name: key.Name, UserID: key.User, Secret: key.Secret, }) if err != nil { return nil, err }
return &key, nil }
func (r *keyRepository) Delete(ctx context.Context, key models.Key) error { return psqlcore.New(r.db).DeleteKey(ctx, key.ID) }
|