forked from ebhomengo/niki
1
0
Fork 0
niki/repository/mysql/kind_box_req/get_all.go

70 lines
2.4 KiB
Go
Raw Normal View History

package mysqlkindboxreq
import (
"context"
"git.gocasts.ir/ebhomengo/niki/entity"
paginationparam "git.gocasts.ir/ebhomengo/niki/param"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (d DB) GetAllKindBoxReq(ctx context.Context, pagination paginationparam.PaginationRequest) ([]entity.KindBoxReq, paginationparam.PaginationResponse, error) {
const op = "mysqlkindboxreq.GetAllKindBoxReq"
// TODO: create getCount function
var count uint
rows, err := d.conn.Conn().QueryContext(ctx, "SELECT COUNT(*) FROM kind_box_reqs")
if err != nil {
return nil, paginationparam.PaginationResponse{},
richerror.New(op).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithErr(err).WithKind(richerror.KindUnexpected)
}
defer rows.Close()
// Iterate through the rows (should only be one) and extract the count:
for rows.Next() {
err := rows.Scan(&count)
if err != nil {
panic(err)
}
}
if rErr := rows.Err(); rErr != nil {
return nil, paginationparam.PaginationResponse{}, richerror.New(op).WithErr(rErr).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
// TODO - add sort and filter
rows, err = d.conn.Conn().QueryContext(ctx, "select * from kind_box_reqs limit ? offset ?", pagination.GetPageSize(), pagination.GetOffset())
if err != nil {
return nil, paginationparam.PaginationResponse{},
richerror.New(op).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithErr(err).WithKind(richerror.KindUnexpected)
}
defer rows.Close()
// An album slice to hold data from returned rows.
var kindBoxReqs []entity.KindBoxReq
// Loop through rows, using Scan to assign column data to struct fields.
for rows.Next() {
kindBoxReq, sErr := scanKindBoxReq(rows)
if sErr != nil {
return nil, paginationparam.PaginationResponse{}, richerror.New(op).WithErr(sErr).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
kindBoxReqs = append(kindBoxReqs, kindBoxReq)
}
if rErr := rows.Err(); rErr != nil {
return nil, paginationparam.PaginationResponse{}, richerror.New(op).WithErr(rErr).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return kindBoxReqs, paginationparam.PaginationResponse{
PageSize: pagination.GetPageSize(),
PageNumber: pagination.GetPageNumber(),
Total: count,
}, nil
}