Adding initial code for adding a new poll on the backend

This commit is contained in:
2025-11-04 16:39:10 -05:00
parent 3e2efae4ce
commit 5e8b4e2b61
8 changed files with 147 additions and 51 deletions

41
server/services/poll.go Normal file
View File

@@ -0,0 +1,41 @@
package services
import (
"go-sjles-pta-vote/server/db"
"go-sjles-pta-vote/server/models"
)
func CreatePoll(poll *models.Poll) (*models.Poll, error) {
new_poll := models.Poll{}
db_conn, err := db.Connect()
if err != nil {
return nil, err
}
defer db.Close()
stmt, err := db_conn.Prepare(`
INSERT INTO polls (
question,
expires_at
) VALUES (
$1,
$2
) RETURNING ID;
`)
if err != nil {
return nil, err
}
defer stmt.Close()
res, err := stmt.Exec(poll.Question, poll.ExpiresAt)
if err != nil {
return nil, err
}
new_poll.ID, err = res.LastInsertId()
return &new_poll, err
}

View File

@@ -0,0 +1,45 @@
package services
import (
"os"
"testing"
"time"
"go-sjles-pta-vote/server/config"
"go-sjles-pta-vote/server/db"
"go-sjles-pta-vote/server/models"
)
func TestCreatePoll(t *testing.T) {
tmp_db, err := os.CreateTemp("", "vote_test.*.db")
if err != nil {
t.Errorf(`Failed to create temporary db file: %v`, err)
}
init_conf := &config.Config{
DBPath: string(tmp_db.Name()),
}
config.SetConfig(init_conf)
defer os.Remove(tmp_db.Name())
tmp_db.Close()
if _, err := db.Connect(); err != nil {
t.Errorf(`Failed to create the database: %v`, err)
}
create_poll := &models.Poll{
Question: "TestQuestion",
ExpiresAt: time.Now().Add(time.Hour * 10).Format("2006-01-02 15:04:05"),
}
new_poll, err := CreatePoll(create_poll)
if err != nil {
t.Errorf(`Failed to insert into table: %v`, err)
}
if new_poll.ID != 1 {
t.Errorf(`Failed to insert into table: Index %d: error %v`, new_poll.ID, err)
}
}