Create

CREATE (INSERT/POST)

CREATE

The CREATE part of REST API is a bit trickier. Save as JSON from the form and create a new record using the JSON.

1. Input from HTML Form

Returning inserted tsk_id
2+3. Extract JSON and send AJAX POST Request

This function extract the JSON from the HTML form and send this to the API with id as return value

function api3create(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("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function() {
if (xhr.readyState === 4) {
document.getElementById("id").innerHTML = "returning id: "+this.responseText
}
};
xhr.send(json);
}
4+5. Lookup and get SQL Query from the REST call

Instead of storing each Query in the API, the query is stored in a database (almost similar to the Postgresql view function) fetched for each request. This means easier to maintain and more generic API (fewer endpoints)

The query is fetced with an id "tsk_new" from the REST call https://api3.go4webdev.org/tsk/new

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 that is filled with JSON from the form in the next step

INSERT INTO tsk (tsk_subject,tsk_desc)
SELECT tsk_subject,tsk_desc 
FROM json_populate_record (NULL::tsk, $1) 
RETURNING tsk_id
6+7+8. Execute the SQL Query and return new ID

The CREATE endpoint in the Go API contains both executing the query as well as return an ID back to the client.

package main

import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
)

func Create(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)
var data interface{}
val, _ = url.QueryUnescape(val)

switch action {
case "new":
query := Getquery(scope + "_" + action)
data = new(query, val)
}

json.NewEncoder(w).Encode(data)  //return ID
}

// add new record
func new(query string, val string) interface{} {
var id int
err := db.QueryRowx(query, val).Scan(&id)
if err != nil {
return nil
}
return (id)
}
9+10. Recieve ID and update HTML

The request #3 include the code to receive ID from the API and insert the ID in the element with id="id"

...
xhr.onload = function() {
if (xhr.readyState === 4) {
document.getElementById("id").innerHTML = "returning id: "+this.responseText
}
};
...