GoCRUD
Hub
goCRUD

API #3 – READ (SELECT/GET)

The READ part of REST API is rather simple. Fetch one or several rows. The challenge is to make it dynamic.

1. Create an AJAX call
var url = "https://api3.go4webdev.org/tsk/all";

var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");

xhr.onload = function () {
   if (xhr.readyState === 4) {
      document.getElementById("put").innerHTML = this.responseText
   }};

xhr.send();
2. Get the SQL lookup query
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 fetched query: SELECT * FROM tsk when using .../tsk/all

3. Execute the sql query from AXAJ Call
package main

import (
  "encoding/json"
  "fmt"
  "net/http"
)

func Get(w http.ResponseWriter, r *http.Request) {
  scope, cmd, val := getpath(r)
  var data interface{}

  switch cmd {
  case "id":
    query := Getquery(scope)
    data = getid(query, val)
  case "all":
    query := Getquery(scope + "_" + cmd)
    fmt.Println(query)
    data = getall(query)
  }
  // convert to json and write
  json.NewEncoder(w).Encode(data)
}

// return a single row
func getid(query string, val string) interface{} {
  if len(query) > 0 {
    row := make(map[string]interface{})
    db.QueryRowx(query, val).MapScan(row)
    return (row)
  }
  return nil
}

// query to return a list
func getall(query string) interface{} {
  fmt.Println(query)
  if len(query) > 0 {
    var list []map[string]interface{}
    rows, err := db.Queryx(query)

    if err != nil {
      log("no records")
    }

    defer rows.Close()

    for rows.Next() {
      row := make(map[string]interface{})
      err = rows.MapScan(row)
      if err != nil {
        log(err.Error())
      }
      list = append(list, row)
    }

    rows.Close()
    if len(list) == 0 {
      return ("norec")
    }
    return list
  }
  return nil
}

All steps above put together:

The result"