canape/backend/models/explorer.go
Grégoire Delattre 1197e6ce6c Move the tokens into the models
By the way, move he sqly package in the models as well
2020-03-02 13:07:04 +01:00

70 lines
1.7 KiB
Go

package models
import (
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
const (
upsertExternalMediaQuery = `
INSERT INTO external_medias (type, source, category, ids)
VALUES (:type, :source, :category, :ids)
ON CONFLICT (type, source, category)
DO UPDATE SET type=:type, source=:source, category=:category, ids=:ids
RETURNING id;`
getExternalMediaQuery = `SELECT * FROM external_medias WHERE type=$1 AND source=$2 AND category=$3 LIMIT 1;`
getExternalMediaOptions = `
SELECT
source, category
FROM external_medias
WHERE type=$1;`
)
// Media represents an external media
type Media struct {
BaseModel
Type string `db:"type"`
Source string `db:"source"`
Category string `db:"category"`
IDs pq.StringArray `db:"ids"`
}
// Explore will return an array of Medias from the DB
func Explore(db *sqlx.DB, mtype, msrc, mcat string) (*Media, error) {
m := &Media{}
if err := db.QueryRowx(getExternalMediaQuery, mtype, msrc, mcat).StructScan(m); err != nil {
return nil, err
}
return m, nil
}
// Upsert adds or updates the Media in the database
func (m *Media) Upsert(db *sqlx.DB) error {
r, err := db.NamedQuery(upsertExternalMediaQuery, m)
if err != nil {
return err
}
defer r.Close()
return nil
}
func GetMediaOptions(db *sqlx.DB, mtype string) (map[string][]string, error) {
type mediaAvailable struct {
Source string `db:"source"`
Category string `db:"category"`
}
m := []*mediaAvailable{}
if err := db.Select(&m, getExternalMediaOptions, mtype); err != nil {
return nil, err
}
availableMedia := map[string][]string{}
for _, p := range m {
availableMedia[p.Source] = append(availableMedia[p.Source], p.Category)
}
return availableMedia, nil
}