weather-api/api/rest-api.go
2021-04-24 23:38:58 +02:00

233 lines
6.4 KiB
Go

package api
import (
"encoding/json"
"fmt"
"net/http"
"weather-data/storage"
"weather-data/weathersource"
"github.com/google/uuid"
"github.com/gorilla/mux"
)
type weatherRestApi struct {
connection string
weaterStorage storage.WeatherStorage
weatherSource weathersource.WeatherSourceBase
sensorRegistry storage.SensorRegistry
}
//SetupAPI sets the REST-API up
func NewRestAPI(connection string, weatherStorage storage.WeatherStorage, sensorRegistry storage.SensorRegistry) *weatherRestApi {
api := new(weatherRestApi)
api.connection = connection
api.weaterStorage = weatherStorage
api.sensorRegistry = sensorRegistry
return api
}
//Start a new Rest-API instance
func (api *weatherRestApi) Start() error {
handler := api.handleRequests()
return http.ListenAndServe(api.connection, handler)
}
//Close the rest api
func (api *weatherRestApi) Close() {
}
func (api *weatherRestApi) handleRequests() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", api.homePageHandler)
router.HandleFunc("/{_dummy:(?i)random}", api.randomWeatherHandler).Methods("GET")
router.HandleFunc("/{_dummy:(?i)randomlist}", api.randomWeatherListHandler).Methods("GET")
router.HandleFunc("/{_dummy:(?i)sensor}/{id}/{_dummy:(?i)weather-data}", api.getWeatherDataHandler).Methods("GET")
router.HandleFunc("/{_dummy:(?i)sensor}/{id}/{_dummy:(?i)weather-data}", api.addWeatherDataHandler).Methods("POST")
router.HandleFunc("/{_dummy:(?i)sensor}/{id}", api.getWeatherSensorHandler).Methods("GET")
router.HandleFunc("/{_dummy:(?i)sensor}/{id}", api.updateWeatherSensorHandler).Methods("PUT")
router.HandleFunc("/{_dummy:(?i)sensor}/{id}", api.deleteWeatherSensorHandler).Methods("DELETE")
router.HandleFunc("/{_dummy:(?i)register/sensor}/{name}", api.registerWeatherSensorHandler).Methods("POST")
return router
}
func (api *weatherRestApi) randomWeatherHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(storage.NewRandomWeatherData().ToMap())
}
func (api *weatherRestApi) randomWeatherListHandler(w http.ResponseWriter, r *http.Request) {
var datapoints = make([]*storage.WeatherData, 0)
for i := 0; i < 10; i++ {
datapoints = append(datapoints, storage.NewRandomWeatherData())
}
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(storage.ToMap(datapoints))
}
func (api *weatherRestApi) getWeatherDataHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
query, err := storage.ParseFromUrlQuery(r.URL.Query())
if err != nil {
http.Error(w, fmt.Sprintf("could not parse query: %v", err.Error()), http.StatusBadRequest)
return
}
query.SensorId, err = uuid.Parse(id)
if err != nil {
http.Error(w, "could not parse id of sensor", http.StatusBadRequest)
return
}
data, err := api.weaterStorage.GetData(query)
if err != nil {
http.Error(w, "error executing query", http.StatusBadRequest)
return
}
res := storage.ToMap(storage.GetOnlyQueriedFields(data, query))
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(res)
}
func (api *weatherRestApi) addWeatherDataHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
var data = make(map[string]interface{})
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
delete(data, "sensorId")
weatherData, err := storage.FromMap(data)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
weatherData.SensorId, err = uuid.Parse(id)
if err != nil {
http.Error(w, "could not parse id of sensor", http.StatusBadRequest)
return
}
err = api.addNewWeatherData(*weatherData)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(weatherData.ToMap())
}
func (api *weatherRestApi) registerWeatherSensorHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
name := vars["name"]
sensor, err := api.sensorRegistry.RegisterSensorByName(name)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(sensor)
}
func (api *weatherRestApi) updateWeatherSensorHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
sensorId, err := uuid.Parse(id)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var sensor storage.WeatherSensor
err = json.NewDecoder(r.Body).Decode(&sensor)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
sensor.Id = sensorId
api.sensorRegistry.UpdateSensor(&sensor)
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(sensor)
}
func (api *weatherRestApi) getWeatherSensorHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
sensorId, err := uuid.Parse(id)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
weatherSensor, err := api.sensorRegistry.ResolveSensorById(sensorId)
if err != nil {
http.Error(w, "sensor not exists", http.StatusNotFound)
return
}
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(weatherSensor)
}
func (api *weatherRestApi) deleteWeatherSensorHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
sensorId, err := uuid.Parse(id)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = api.sensorRegistry.DeleteSensor(sensorId)
if err != nil {
http.Error(w, "", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (api *weatherRestApi) homePageHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the Weather API!")
}
//AddNewWeatherDataCallback adds a new callbackMethod for incoming weather data
func (api *weatherRestApi) AddNewWeatherDataCallback(callback weathersource.NewWeatherDataCallbackFunc) {
api.weatherSource.AddNewWeatherDataCallback(callback)
}
func (api *weatherRestApi) addNewWeatherData(weatherData storage.WeatherData) error {
return api.weatherSource.NewWeatherData(weatherData)
}