I am trying to wrap a function into REST API using plumber R Package. As a Input , function takes a shape file and returns GeoJSON as Output after the transformation.
#* Return Spatial Polygon Object in form of GeoJSON
#* @param dsn:character Path to Shapefile with Name
#* @param design:character one or two
#* @post /sprayermap
sprayer_map <-
function(dsn,
design = c("one", "two")) {
# library
require(rgeos)
require(rgdal)
require(sp)
require(raster)
require(cleangeo)
#Import Shapefile
a_shape <- raster::shapefile(dsn)
result <-
list("success" = F,
additional_info = NULL ,
GeoJSON = NULL)
if (class(a_shape) == "SpatialPolygonsDataFrame") {
a_shape <- tryCatch (
rgeos::gBuffer(a_shape, byid = TRUE, width = 0),
error = function(err) {
return(paste("sprayer map : ", err))
}
)
if (design == "one") {
sprayer_map <- tryCatch (
aggregate(a_shape, "Rx"),
error = function(err) {
return(paste("sprayer map : ", err))
}
)
sprayer_map@data$Rx <- as.integer(sprayer_map@data$Rx)
} else if (design == "two") {
return(paste0("Design Two !"))
}
temppath <- file.path(tempdir(), "sprayermap.GeoJSON")
rgdal::writeOGR(
sprayer_map,
dsn = temppath,
layer = "geojson",
driver = "GeoJSON",
overwrite_layer = TRUE
)
if (file.exists(temppath)) {
GeoJSON <- readLines(temppath)
result$success <- T
result$GeoJSON = GeoJSON
return(result)
} else {
return(paste0("GeoJSON Creation Failed!"))
}
} else {
return(paste0("Please provide spatial polygon object !"))
}
}
Now to make REST API more generic in terms of implementation and use , Input of the REST API need to change into GeoJSON as request body (req$postBody) instead of shape file path import method. Looking for guidance how to achieve the same in this case. Test Input Shape file as well as GeoJSON