changeset 2162:0627565fb4d2

Print templates: Implemented /api/templates/print/{name} PATCH to update print templates.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Fri, 08 Feb 2019 13:06:16 +0100
parents 7444b75d5497
children b6b699385302
files pkg/controllers/printtemplates.go pkg/controllers/routes.go
diffstat 2 files changed, 66 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/pkg/controllers/printtemplates.go	Fri Feb 08 12:56:33 2019 +0100
+++ b/pkg/controllers/printtemplates.go	Fri Feb 08 13:06:16 2019 +0100
@@ -49,6 +49,9 @@
 	insertPrintTemplateSQL = `
 INSERT INTO users.templates (template_name, template_data)
 VALUES ($1, $2)`
+
+	updatePrintTemplateSQL = `
+UPDATE user.templates template_data = $2 WHERE template_name = $1`
 )
 
 func listPrintTemplates(
@@ -232,10 +235,69 @@
 }
 
 func updatePrintTemplate(
-	_ interface{},
+	input interface{},
 	req *http.Request,
 	conn *sql.Conn,
 ) (jr JSONResult, err error) {
-	// TODO: Implement me!
+
+	ctx := req.Context()
+	name := mux.Vars(req)["name"]
+	in := input.(*json.RawMessage)
+
+	if name == "" {
+		err = JSONError{
+			Code:    http.StatusBadRequest,
+			Message: "Template must have a none empty name",
+		}
+		return
+	}
+	if len(*in) == 0 {
+		err = JSONError{
+			Code:    http.StatusBadRequest,
+			Message: "Template must have a none empty template",
+		}
+		return
+	}
+	var tx *sql.Tx
+	if tx, err = conn.BeginTx(ctx, nil); err != nil {
+		return
+	}
+	defer tx.Rollback()
+
+	var dummy bool
+	err = tx.QueryRowContext(ctx, hasPrintTemplateSQL, name).Scan(&dummy)
+
+	switch {
+	case err == sql.ErrNoRows:
+		err = JSONError{
+			Code:    http.StatusNotFound,
+			Message: "No such template found",
+		}
+		return
+	case err != nil:
+		return
+	case !dummy:
+		err = JSONError{
+			Code:    http.StatusInternalServerError,
+			Message: "Unexpected return value from database query",
+		}
+		return
+	}
+	data := pgtype.Bytea{Bytes: *in, Status: pgtype.Present}
+
+	if _, err = tx.ExecContext(ctx, updatePrintTemplateSQL, name, &data); err != nil {
+		return
+	}
+
+	if err = tx.Commit(); err != nil {
+		return
+	}
+
+	jr = JSONResult{
+		Code: http.StatusOK,
+		Result: map[string]string{
+			"updated": name,
+		},
+	}
 	return
 }
--- a/pkg/controllers/routes.go	Fri Feb 08 12:56:33 2019 +0100
+++ b/pkg/controllers/routes.go	Fri Feb 08 13:06:16 2019 +0100
@@ -115,7 +115,9 @@
 	})).Methods(http.MethodDelete)
 
 	api.Handle("/templates/print/{name}", waterwayAdmin(&JSONHandler{
+		Input:  func(*http.Request) interface{} { return &json.RawMessage{} },
 		Handle: updatePrintTemplate,
+		Limit:  maxPrintTemplateSize,
 	})).Methods(http.MethodPatch)
 
 	// External proxies.