streaming-key-server-manager
streaming-key-server-manager copied to clipboard
Improve repository
You can improve the error handling omitting from user the real problem, just leaving it to the log, meanwhile user will receive just a clean error message. Also, it can be a good idea to prepare the statement. You can even cache the statements if you want, since you only have one statement, it would just occupy a small space in memory and speed up the SQL execution.
Here some code example:
type keysRepository struct {
db *sql.DB
stmts map[string]*sql.Stmt
}
func NewKeysRepository(db *sql.DB) (*keysRepository, error) {
stmts := make(map[string]*sql.Stmt)
stmt, err := db.Prepare(`SELECT "name", "stream_key" FROM "Lives" WHERE "name"=$1 AND "stream_key"=$2`)
if err != nil {
return nil, err
}
stmts["FindStreamKey"] = stmt
return &keysRepository{
db: db,
stmts: stmts,
}, nil
}
func (r *keysRepository) FindStreamKey(ctx context.Context, name, key string) (*model.Keys, error) {
keys := &model.Keys{}
stmt, ok := r.stmts["FindStreamKey"]
if !ok {
return nil, errors.New("statement not found")
}
row := stmt.QueryRowContext(ctx, name, key)
err := row.Scan(&keys.Name, &keys.Key)
if err != nil {
log.Println(err.Error())
if errors.Is(err, sql.ErrNoRows) {
return nil, errors.New("streamkey not found")
}
return nil, errors.New("unable to retrieve streamkey")
}
return keys, nil
}