Fix slow-ass code

This commit is contained in:
2025-01-13 20:06:55 +01:00
parent ee847020f7
commit d1225d3258
5 changed files with 41 additions and 23 deletions

View File

@ -90,12 +90,12 @@ func (app *application) CreateElection(w http.ResponseWriter, r *http.Request) {
voterIdentities := make([]string, 0, request.MaxVoters) // TODO: this is way too slow
for i := 0; i < request.MaxVoters; i++ {
randomIdentity := randomVoterIdentity()
_, err := app.voters.Insert(randomIdentity, electionId)
if err != nil {
app.serverError(w, r, err)
}
voterIdentities = append(voterIdentities, randomIdentity)
}
_, err := app.voters.InsertMultiple(voterIdentities, electionId)
if err != nil {
app.serverError(w, r, err)
}
res, err = json.Marshal(api.CreateElectionResponse{VoterIdentities: &voterIdentities})
if err != nil {
@ -248,7 +248,7 @@ func (app *application) createVotesHandleUnknownVotersElection(w http.ResponseWr
return "", fmt.Errorf(message)
}
_, err = app.voters.Insert(voterIdentity, election.ID)
_, err = app.voters.InsertMultiple([]string{voterIdentity}, election.ID)
if err != nil {
app.serverError(w, r, err)
return "", err

View File

@ -243,8 +243,8 @@ func TestCreateVotes_UnknownVotersElection(t *testing.T) {
On("Exists", mock.Anything, mock.Anything).
Return(false, nil)
mockVoters.
On("Insert", mock.Anything, mock.Anything).
Return(1, nil)
On("InsertMultiple", mock.Anything, mock.Anything).
Return([]int{1}, nil)
mockVoters.
On("CountByElection", mock.Anything).
Return(0, nil)
@ -634,8 +634,8 @@ func TestCreateVotes_UnknownVotersElectionMaxVotersReached(t *testing.T) {
On("Exists", mock.Anything, mock.Anything).
Return(false, nil)
mockVoters.
On("Insert", mock.Anything, mock.Anything).
Return(1, nil)
On("InsertMultiple", mock.Anything, mock.Anything).
Return([]int{1}, nil)
mockVoters.
On("CountByElection", mock.Anything).
Return(10, nil)

View File

@ -48,7 +48,7 @@ func main() {
Addr: addr,
Handler: app.routes(),
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelError),
IdleTimeout: 6 * time.Minute,
IdleTimeout: time.Minute,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}

View File

@ -62,9 +62,9 @@ type mockVoterModel struct {
mock.Mock
}
func (v *mockVoterModel) Insert(identity string, electionID int) (int, error) {
args := v.Called(identity, electionID)
return args.Int(0), args.Error(1)
func (v *mockVoterModel) InsertMultiple(identities []string, electionID int) ([]int, error) {
args := v.Called(identities, electionID)
return args.Get(0).([]int), args.Error(1)
}
func (v *mockVoterModel) CountByElection(electionID int) (int, error) {