2018-09-23 12:40:06 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2019-03-03 04:14:42 +08:00
|
|
|
"github.com/lib/pq"
|
2018-09-23 12:40:06 +08:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2019-03-03 04:14:42 +08:00
|
|
|
func commentCount(domain string, paths []string) (map[string]int, error) {
|
|
|
|
commentCounts := map[string]int{}
|
|
|
|
|
2018-09-23 12:40:06 +08:00
|
|
|
if domain == "" {
|
2019-03-03 04:14:42 +08:00
|
|
|
return nil, errorMissingField
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(paths) == 0 {
|
|
|
|
return nil, errorEmptyPaths
|
2018-09-23 12:40:06 +08:00
|
|
|
}
|
|
|
|
|
2019-03-03 04:14:42 +08:00
|
|
|
statement := `
|
|
|
|
SELECT path, commentCount
|
|
|
|
FROM pages
|
|
|
|
WHERE domain = $1 AND path = ANY($2);
|
|
|
|
`
|
|
|
|
rows, err := db.Query(statement, domain, pq.Array(paths))
|
2018-09-23 12:40:06 +08:00
|
|
|
if err != nil {
|
2019-03-03 04:14:42 +08:00
|
|
|
logger.Errorf("cannot get comments: %v", err)
|
|
|
|
return nil, errorInternal
|
|
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
var path string
|
|
|
|
var commentCount int
|
|
|
|
if err = rows.Scan(&path, &commentCount); err != nil {
|
|
|
|
logger.Errorf("cannot scan path and commentCount: %v", err)
|
|
|
|
return nil, errorInternal
|
|
|
|
}
|
|
|
|
|
|
|
|
commentCounts[path] = commentCount
|
2018-09-23 12:40:06 +08:00
|
|
|
}
|
|
|
|
|
2019-03-03 04:14:42 +08:00
|
|
|
return commentCounts, nil
|
2018-09-23 12:40:06 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func commentCountHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
type request struct {
|
2019-03-03 04:14:42 +08:00
|
|
|
Domain *string `json:"domain"`
|
|
|
|
Paths *[]string `json:"paths"`
|
2018-09-23 12:40:06 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
var x request
|
|
|
|
if err := bodyUnmarshal(r, &x); err != nil {
|
|
|
|
bodyMarshal(w, response{"success": false, "message": err.Error()})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
domain := domainStrip(*x.Domain)
|
|
|
|
|
2019-03-03 04:14:42 +08:00
|
|
|
commentCounts, err := commentCount(domain, *x.Paths)
|
2018-09-23 12:40:06 +08:00
|
|
|
if err != nil {
|
|
|
|
bodyMarshal(w, response{"success": false, "message": err.Error()})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-03-03 04:14:42 +08:00
|
|
|
bodyMarshal(w, response{"success": true, "commentCounts": commentCounts})
|
2018-09-23 12:40:06 +08:00
|
|
|
}
|