Commit 1d27efd1 authored by zauberstuhl's avatar zauberstuhl

Add CreateOrUpdate func to Repo struct

In case a db entry was found update it with the given struct
parent 9a9c09c7
......@@ -19,8 +19,6 @@ package main
import (
"net/http"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"html/template"
"fmt"
"golang.org/x/oauth2"
......@@ -57,16 +55,8 @@ func render(w http.ResponseWriter, name string, s interface{}) {
}
func indexPage(w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open(databaseDriver, databaseDSN)
if err != nil {
logger.Println(err)
render(w, "error.html", "Cannot connect to database")
return
}
defer db.Close()
var repos Repos
err = db.Find(&repos).Error
err := repos.FindAll()
if err != nil {
logger.Println(err)
render(w, "error.html", "No repositories found")
......@@ -82,14 +72,6 @@ func resultPage(w http.ResponseWriter, r *http.Request) {
project := r.URL.Query().Get("project")
if accessToken != "" && repo != "" && project != "" {
db, err := gorm.Open(databaseDriver, databaseDSN)
if err != nil {
logger.Println(err)
render(w, "error.html", "Cannot connect to database")
return
}
defer db.Close()
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: accessToken},
......@@ -136,17 +118,17 @@ func resultPage(w http.ResponseWriter, r *http.Request) {
}
if !devMode {
_, _, err = client.Repositories.CreateHook(ctx, repoSlice[0], repoSlice[1], &hook)
_, _, err := client.Repositories.CreateHook(ctx, repoSlice[0], repoSlice[1], &hook)
if err != nil {
logger.Println(err)
render(w, "error.html", "Cannot create the repository hook")
return
}
err = db.Create(&repo).Error
err = repo.CreateOrUpdate()
if err != nil {
logger.Println(err)
render(w, "error.html", "Cannot insert into database (probably the project already exists)")
render(w, "error.html", "Cannot insert/update the database record")
return
}
}
......
......@@ -19,6 +19,7 @@ package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type Repo struct {
......@@ -33,3 +34,39 @@ type Repo struct {
}
type Repos []Repo
func (repos *Repos) FindAll() error {
db, err := gorm.Open(databaseDriver, databaseDSN)
if err != nil {
return err
}
defer db.Close()
return db.Find(repos).Error
}
func (repo *Repo) CreateOrUpdate() error {
db, err := gorm.Open(databaseDriver, databaseDSN)
if err != nil {
return err
}
defer db.Close()
var oldRecord Repo
err = db.Where(
"project = ? and slug = ?", repo.Project, repo.Slug,
).Find(&oldRecord).Error
if err == gorm.ErrRecordNotFound {
err = db.Create(repo).Error
if err != nil {
return err
}
} else if err == nil {
repo.ID = oldRecord.ID
err = db.Update(repo).Error
if err != nil {
return err
}
}
return err
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment