niki/repository/mysql/address/get.go

72 lines
2.2 KiB
Go
Raw Permalink Normal View History

package mysqladdress
import (
"context"
"database/sql"
"errors"
"time"
"git.gocasts.ir/ebhomengo/niki/entity"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
"git.gocasts.ir/ebhomengo/niki/repository/mysql"
)
// TODO - use this approach or return (bool,entity.Address,error).
2024-01-19 16:37:15 +00:00
func (d *DB) GetAddressByID(ctx context.Context, id uint) (*entity.Address, error) {
const op = "mysqladdress.IsExistAddressByID"
row := d.conn.Conn().QueryRowContext(ctx, `select * from addresses where id = ? and deleted_at is null`, id)
address, err := scanAddress(row)
if err != nil {
sErr := sql.ErrNoRows
//TODO-errorsas: second argument to errors.As should not be *error
//nolint
if errors.As(err, &sErr) {
return nil, nil
}
// TODO - log unexpected error for better observability
return nil, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
return &address, nil
}
2024-06-01 00:29:11 +00:00
func (d *DB) GetAddress(ctx context.Context, addressID uint, benefactorID uint) (entity.Address, error) {
const op = "mysqladdress.GetAddress"
row := d.conn.Conn().QueryRowContext(ctx, `select * from addresses where id = ? and benefactor_id = ? and deleted_at is null`, addressID, benefactorID)
2024-06-01 00:29:11 +00:00
address, err := scanAddress(row)
if err != nil {
sErr := sql.ErrNoRows
//TODO-errorsas: second argument to errors.As should not be *error
//nolint
if errors.As(err, &sErr) {
return entity.Address{}, richerror.New(op).WithMessage(errmsg.ErrorMsgNotFound).
WithKind(richerror.KindNotFound)
}
// TODO - log unexpected error for better observability
return entity.Address{}, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
return address, nil
}
func scanAddress(scanner mysql.Scanner) (entity.Address, error) {
2024-05-14 13:07:09 +00:00
var createdAt, updatedAt time.Time
var deletedAt sql.NullTime
var address entity.Address
err := scanner.Scan(&address.ID, &address.PostalCode, &address.Address, &address.Lat, &address.Lon,
&address.Name, &address.CityID, &address.ProvinceID, &address.BenefactorID,
&createdAt, &updatedAt, &deletedAt)
return address, err
}