UPDATE (UPDATE/PUT)
To UPDATE a record is a 2 part task. Populate form. Update a record using JSON.
1-8. Get data and fill the form
The first 8 steps are similar to the READ process. The difference is that the data should fill the form "dynamically".
function api3fill(path) { var url = "https://api3.go4webdev.org/"+path; var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.responseType = 'json'; xhr.onload = function() { if (xhr.readyState === 4) { fillform(this.response) } }; xhr.send(); } function fillform(data) { const { elements } = document.querySelector('form') for (const [key, value] of Object.entries(data)) { const field = elements.namedItem(key) if (field) field.value = value } }
9. Edit record
10+11. Extract JSON and send via AJAX POST Request
This function extract the JSON from the HTML form and send this to the API
function api3update(elem, event) { event.preventDefault(); //get JSON values from form var form = elem; var formData = new FormData(form) var object = {}; formData.forEach(function(value, key) { object[key] = value; }); var path = object.path var json = JSON.stringify(object) //call API var url = "https://api3.go4webdev.org/" + path; var xhr = new XMLHttpRequest(); xhr.open("PUT", url); xhr.setRequestHeader("Accept", "application/json"); xhr.send(json); }
12+13. Lookup and get SQL Query from the REST call
The Go API first get the desired SQL Query from Postgresql lookup database.
func Getquery(path string) string { // get query from lookup db var query string err := db.QueryRow("SELECT sql_query FROM sqls WHERE sql_id=$1", path).Scan(&query) if err != nil { path = "" } fmt.Println(query) return query }
The lookup Query look like this with a parameter $1 that is filled with JSON from the form previously.
WITH list AS (SELECT * FROM json_populate_record (null::tsk,$1)) UPDATE tsk SET (tsk_subject,tsk_desc) = (SELECT tsk_subject,tsk_desc FROM list) WHERE tsk_id=(SELECT tsk_id FROM list)
14+15. Execute the SQL Query
The PUT endpoint in the Go API looks like this:
package main import ( "io/ioutil" "net/http" "net/url" ) func Update(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { log(err.Error()) } scope, action, val := getpath(r) val = string(body) val, _ = url.QueryUnescape(val) switch action { case "edit": query := Getquery(scope + "_" + action) edit(query, val) } } // edit record func edit(query string, val string) { db.MustExec(query, val) }