# HG changeset patch # User Sascha L. Teichmann # Date 1549627576 -3600 # Node ID 0627565fb4d22118b6d31ce86a53775c6e8516b5 # Parent 7444b75d549740e12bf94f58fe6ba99bce94f444 Print templates: Implemented /api/templates/print/{name} PATCH to update print templates. diff -r 7444b75d5497 -r 0627565fb4d2 pkg/controllers/printtemplates.go --- 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 } diff -r 7444b75d5497 -r 0627565fb4d2 pkg/controllers/routes.go --- 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.