first commit

This commit is contained in:
Sas Andy
2024-12-09 09:51:19 +07:00
commit ecc5dfd9c0
69 changed files with 5365 additions and 0 deletions

82
services/order/store.go Normal file
View File

@@ -0,0 +1,82 @@
package order
import (
"context"
"github.com/jmoiron/sqlx"
"sismedika.com/sas/westone/types"
)
type Store struct {
db *sqlx.DB
}
func NewStore(db *sqlx.DB) *Store {
return &Store{db: db}
}
func (s *Store) CreateOrder(order types.Order) (int, error) {
// Start a new transaction
tx, err := s.db.BeginTxx(context.Background(), nil)
if err != nil {
return 0, err
}
// Defer rollback to ensure transaction is rolled back in case of an error
defer func() {
if err != nil {
tx.Rollback()
}
}()
query := `INSERT INTO orders (userId, total, status, address)
VALUES (:userId, :total, :status, :address)`
// Using tx.NamedExec to insert the order within the transaction
res, err := tx.NamedExec(query, order)
if err != nil {
return 0, err
}
// Retrieving the last inserted ID
id, err := res.LastInsertId()
if err != nil {
return 0, err
}
// Commit the transaction if everything succeeded
if err = tx.Commit(); err != nil {
return 0, err
}
return int(id), nil
}
func (s *Store) CreateOrderItem(orderItem types.OrderItem) error {
// Start a new transaction
tx, err := s.db.BeginTxx(context.Background(), nil)
if err != nil {
return err
}
// Defer rollback to ensure transaction is rolled back in case of an error
defer func() {
if err != nil {
tx.Rollback()
}
}()
query := `INSERT INTO order_items (orderId, productId, quantity, price)
VALUES (:orderId, :productId, :quantity, :price)`
// Using tx.NamedExec to insert the order item within the transaction
_, err = tx.NamedExec(query, orderItem)
if err != nil {
return err
}
// Commit the transaction if everything succeeded
if err = tx.Commit(); err != nil {
return err
}
return nil
}