# HG changeset patch # User Sascha L. Teichmann # Date 1544783368 -3600 # Node ID e0bd82f6ee14bdc111901b41c75960cc9d25a0af # Parent 2888bfacd331a1c006ab9d033745be7370bb6890 Added PUT /api/imports/scheduler to add a import configuration. diff -r 2888bfacd331 -r e0bd82f6ee14 pkg/controllers/routes.go --- 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) diff -r 2888bfacd331 -r e0bd82f6ee14 pkg/controllers/scheduler.go --- 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,