You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
1 week ago
|
package internal
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"database/sql"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
type ExampleModel struct {
|
||
|
ID int
|
||
|
CreatedAt time.Time
|
||
|
UpdatedAt time.Time
|
||
|
Title sql.NullString
|
||
|
Content sql.NullString
|
||
|
}
|
||
|
|
||
|
type ExampleModelService struct {
|
||
|
DB *sql.DB
|
||
|
}
|
||
|
|
||
|
func (s *ExampleModelService) CreateExample(ctx context.Context, example *ExampleModel) (int, error) {
|
||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||
|
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
defer tx.Rollback()
|
||
|
|
||
|
id, err := createExample(ctx, tx, example)
|
||
|
if err != nil {
|
||
|
return id, err
|
||
|
}
|
||
|
|
||
|
return id, tx.Commit()
|
||
|
}
|
||
|
|
||
|
func createExample(ctx context.Context, tx *sql.Tx, example *ExampleModel) (int, error) {
|
||
|
// assign current user to model
|
||
|
// userID := UserIDFromContext(ctx)
|
||
|
// if userID == 0 {
|
||
|
// return 0, wtf.Errorf(wtf.EUNAUTHORIZED, "You must be logged in to create a dial.")
|
||
|
// }
|
||
|
// example.UserID = wtf.UserIDFromContext(ctx)
|
||
|
stmt := "INSERT INTO example (title, content) VALUES (?, ?)"
|
||
|
result, err := tx.ExecContext(ctx, stmt, example.Title, example.Content)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
id, err := result.LastInsertId()
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
return int(id), nil
|
||
|
}
|