Introduce survey and question cache

This commit is contained in:
nemunaire 2022-09-02 14:08:03 +02:00
parent 02a232b1fa
commit ab88195607
4 changed files with 93 additions and 2 deletions

View file

@ -4,12 +4,18 @@ import (
"log"
"net/http"
"strconv"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/russross/blackfriday/v2"
)
var (
_questions_cache = map[int64]*Question{}
_questions_cache_mutex = sync.RWMutex{}
)
func declareAPIAuthQuestionsRoutes(router *gin.RouterGroup) {
router.GET("/questions", func(c *gin.Context) {
var s *Survey
@ -252,16 +258,38 @@ func (s *Survey) GetQuestions() (questions []*Question, err error) {
}
func getQuestion(id int) (q *Question, err error) {
_questions_cache_mutex.RLock()
question, ok := _questions_cache[int64(id)]
_questions_cache_mutex.RUnlock()
if ok {
return question, nil
}
q = new(Question)
err = DBQueryRow("SELECT id_question, id_survey, title, description, placeholder, kind FROM survey_quests WHERE id_question=?", id).Scan(&q.Id, &q.IdSurvey, &q.Title, &q.DescriptionRaw, &q.Placeholder, &q.Kind)
q.Description = string(blackfriday.Run([]byte(q.DescriptionRaw)))
_questions_cache_mutex.Lock()
_questions_cache[int64(id)] = q
_questions_cache_mutex.Unlock()
return
}
func (s *Survey) GetQuestion(id int) (q *Question, err error) {
_questions_cache_mutex.RLock()
question, ok := _questions_cache[int64(id)]
_questions_cache_mutex.RUnlock()
if ok {
return question, nil
}
q = new(Question)
err = DBQueryRow("SELECT id_question, id_survey, title, description, placeholder, kind FROM survey_quests WHERE id_question=? AND id_survey=?", id, s.Id).Scan(&q.Id, &q.IdSurvey, &q.Title, &q.DescriptionRaw, &q.Placeholder, &q.Kind)
q.Description = string(blackfriday.Run([]byte(q.DescriptionRaw)))
_questions_cache_mutex.Lock()
_questions_cache[int64(id)] = q
_questions_cache_mutex.Unlock()
return
}
@ -283,6 +311,9 @@ func (q *Question) Update() (*Question, error) {
if _, err := DBExec("UPDATE survey_quests SET id_survey = ?, title = ?, description = ?, placeholder = ?, kind = ? WHERE id_question = ?", q.IdSurvey, q.Title, q.DescriptionRaw, q.Placeholder, q.Kind, q.Id); err != nil {
return nil, err
} else {
_questions_cache_mutex.Lock()
_questions_cache[q.Id] = q
_questions_cache_mutex.Unlock()
return q, err
}
}
@ -293,6 +324,9 @@ func (q *Question) Delete() (int64, error) {
} else if nb, err := res.RowsAffected(); err != nil {
return 0, err
} else {
_questions_cache_mutex.Lock()
delete(_questions_cache, q.Id)
_questions_cache_mutex.Unlock()
return nb, err
}
}
@ -303,6 +337,9 @@ func ClearQuestions() (int64, error) {
} else if nb, err := res.RowsAffected(); err != nil {
return 0, err
} else {
_questions_cache_mutex.Lock()
_questions_cache = map[int64]*Question{}
_questions_cache_mutex.Unlock()
return nb, err
}
}