changeset 1589:e0bd82f6ee14

Added PUT /api/imports/scheduler to add a import configuration.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Fri, 14 Dec 2018 11:29:28 +0100
parents 2888bfacd331
children 2fdd8e57542d
files pkg/controllers/routes.go pkg/controllers/scheduler.go
diffstat 2 files changed, 90 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/pkg/controllers/routes.go	Fri Dec 14 11:24:50 2018 +0100
+++ b/pkg/controllers/routes.go	Fri Dec 14 11:29:28 2018 +0100
@@ -178,6 +178,12 @@
 	// Import scheduler configuration
 	api.Handle("/imports/scheduler",
 		waterwayAdmin(&JSONHandler{
+			Input:  func() interface{} { return new(models.ImportConfig) },
+			Handle: addSchedule,
+		})).Methods(http.MethodPost)
+
+	api.Handle("/imports/scheduler",
+		waterwayAdmin(&JSONHandler{
 			Handle: listScheduler,
 		})).Methods(http.MethodGet)
 
--- a/pkg/controllers/scheduler.go	Fri Dec 14 11:24:50 2018 +0100
+++ b/pkg/controllers/scheduler.go	Fri Dec 14 11:29:28 2018 +0100
@@ -17,7 +17,9 @@
 	"database/sql"
 	"net/http"
 
+	"gemma.intevation.de/gemma/pkg/auth"
 	"gemma.intevation.de/gemma/pkg/models"
+	"gemma.intevation.de/gemma/pkg/scheduler"
 )
 
 const (
@@ -32,8 +34,90 @@
   url
 FROM waterway.import_configuration
 ORDER by id`
+
+	insertImportConfigurationSQL = `
+INSERT INTO waterway.import_configuration
+(username, kind, cron, send_email, auto_accept, url)
+VALUES ($1, $2, $3, $4, $5, $6)
+RETURNING id`
 )
 
+func addSchedule(
+	input interface{},
+	req *http.Request,
+	conn *sql.Conn,
+) (jr JSONResult, err error) {
+
+	importConfig := input.(*models.ImportConfig)
+
+	session, _ := auth.GetSession(req)
+
+	var cron, url sql.NullString
+
+	if importConfig.Cron != nil {
+		cron = sql.NullString{String: string(*importConfig.Cron), Valid: true}
+	}
+	if importConfig.URL != nil {
+		url = sql.NullString{String: *importConfig.URL, Valid: true}
+	}
+
+	ctx := req.Context()
+
+	var tx *sql.Tx
+
+	if tx, err = conn.BeginTx(ctx, nil); err != nil {
+		return
+	}
+	defer tx.Rollback()
+
+	var id int64
+	if err = tx.QueryRowContext(
+		ctx,
+		insertImportConfigurationSQL,
+		session.User,
+		string(importConfig.Kind),
+		cron,
+		importConfig.SendEMail,
+		importConfig.AutoAccept,
+		url,
+	).Scan(&id); err != nil {
+		return
+	}
+
+	// Need to start a scheduler job right away?
+	if importConfig.Cron != nil {
+		if err = scheduler.BindAction(
+			string(importConfig.Kind),
+			string(*importConfig.Cron),
+			session.User,
+			&id,
+		); err != nil {
+			return
+		}
+	}
+
+	if err = tx.Commit(); err != nil {
+		scheduler.UnbindAction(
+			string(importConfig.Kind),
+			session.User,
+			&id,
+		)
+		return
+	}
+
+	var result = struct {
+		ID int64 `json:"id"`
+	}{
+		ID: id,
+	}
+
+	jr = JSONResult{
+		Code:   http.StatusCreated,
+		Result: &result,
+	}
+	return
+}
+
 func listScheduler(
 	_ interface{},
 	req *http.Request,