R/ApiClient.r

Defines functions .onLoad connectToPHISWS checkAuthorization

Documented in connectToPHISWS

# sunagriAPI
#
# An instance of OpenSILEX WebService
#
# OpenAPI spec version: 3.3.0
# 
# Generated by: https://github.com/swagger-api/swagger-codegen.git


#' ApiClient Class
#'
#' Generic API client for Swagger client library builds.
#' Swagger generic API client. This client handles the client-
#' server communication, and is invariant across implementations. Specifics of
#' the methods and models for each application are generated from the Swagger
#' templates.
#'
#' NOTE: This class is auto generated by the swagger code generator program.
#' Ref: https://github.com/swagger-api/swagger-codegen
#' Do not edit the class manually.
#'
#' @export
ApiClient  <- R6::R6Class(
  'ApiClient',
  public = list(
    basePath =  sub("/$", "",get("BASE_PATH",opensilexWSClientR:::configWS)),
    configuration = NULL,
    userAgent = NULL,
    defaultHeaders = NULL,
    initialize = function(basePath, configuration, defaultHeaders){
        if (!missing(basePath)) {
            self$basePath <- basePath
        }

        if (!missing(configuration)) {
            self$configuration <- configuration
        }

        if (!missing(defaultHeaders)) {
            self$defaultHeaders <- defaultHeaders
        }

        self$`userAgent` <- 'Swagger-Codegen/3.3.0/r'
    },
    callApi = function(url, method, queryParams, headerParams, body, ...){
       
        checkAuthorization()
        access_token = paste('Bearer',get("TOKEN_VALUE",opensilexWSClientR:::configWS))
        headerParams[['Authorization']] = access_token
        headers <- httr::add_headers(headerParams)

        if (method == "GET") {
            httr::GET(url,query = queryParams, headers, ...)
        }
        else if (method == "POST") {
            httr::POST(url, query = queryParams, headers, body = body, httr::content_type_json(), ...)
        }
        else if (method == "PUT") {
            httr::PUT(url, query = queryParams, headers, body = body, ...)
        }
        else if (method == "PATCH") {
            httr::PATCH(url, query = queryParams, headers, body = body, ...)
        }
        else if (method == "HEAD") {
            httr::HEAD(url, query = queryParams, headers, ...)
        }
        else if (method == "DELETE") {
            httr::DELETE(url,query = queryParams, headers, ...)
        }
        else {
            stop("http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`.")
        }
    }
  )
)


checkAuthorization <-function(){
    if(!get("USER_VALID",opensilexWSClientR:::configWS)) stop("You must first connect to an OpenSILEX Instance using connectToOpenSILEXWS() function")
        if(!get("TOKEN_VALID",opensilexWSClientR:::configWS)){ #  token not valid 
          if(get("RECONNECT_ON_DISCONNECTION",opensilexWSClientR:::configWS)){ # try to reconnect
            logging::loginfo("Token expired. Reconnecting to WS ... ")
            connectToOpenSILEXWS(get("USERNAME",opensilexWSClientR:::configWS),get("PASSWORD",opensilexWSClientR:::configWS),get("BASE_PATH",opensilexWSClientR:::configWS))
            if(!get("TOKEN_VALID",opensilexWSClientR:::configWS)) stop("The reconnection has failed")
            logging::loginfo("Reconnected to WS ... ")
          }else{ 
            stop("You must first connect to an OpenSILEX Instance using connectToOpenSILEXWS() function")
          }
        }
}

##' @title connectToPHISWS
##' @param apiID character, a character name of an API ("ws_public" or "ws_private")
##' @param url character, if apiID is private add the url of the chosen API, containing the IP,
##'            the full url with the protocol. e.g. 'http://www.opensilex.org/openSilexAPI/rest/'
##' @param username login of the user to create the token
##' @param password password of the user to create the token
##' @param reconnection to force the client reconnection
##' @import opensilexWSClientR
##' @description load name space and connexion parameters of the webservice.
##' Execute only once at the beginning of the requests.
##' In the case of a WebService change of address or a renaming of services, please edit this list.
##' and execute the function.
##' Demonstration instances : 
##' \describe{
##' \item{WS1}{connectToPHISWS(apiID="ws_1_public","guestphis@supagro.inra.fr","guestphis")}
##' \item{WS2}{connectToPHISWS(apiID="ws_2_public","guest@opensilex.org","guest")}
##' \item{WS2}{connectToPHISWS(apiID="ws_private",username="guest@opensilex.org",password="guest", 
##' url = "http://www.opensilex.org/openSilexAPI/rest/")}
##' }
##' @export
connectToPHISWS<-function(apiID, username = NULL, password = NULL, url = NULL, reconnection = TRUE){
  
  # if apiID is public then we use the public configWS given by the package
  if (apiID == "ws_1_public") {
    username = get("WS_1_PUBLIC_USERNAME",configWS)
    password = get("WS_1_PUBLIC_PASSWORD",configWS)
    url = get("WS_1_PUBLIC_PATH",configWS)
  }
  
  if (apiID == "ws_2_public") {
    username = get("WS_2_PUBLIC_USERNAME",configWS)
    password = get("WS_2_PUBLIC_PASSWORD",configWS)
    url = get("WS_2_PUBLIC_PATH",configWS)
  }
  
  # configWS is an environment with specific variables to opensilex web service
  # if apiID is private, we use the url given by the user
  
  if (apiID == "ws_private") {
    if (is.null(username)) {
      stop("Please, give an username")
    }
    if (is.null(password)) {
      stop("Please, give an user password")
    }  
    if(is.null(url)){
      stop("Please, give an OpenSILEX WS full URL")
    }
  }
  opensilexWSClientR::connectToOpenSILEXWS(username = username,
                                           password = password,
                                           url = url)

} 

configWS<-new.env(emptyenv())

.onLoad <- function(libname, pkgname){
  
  # connectToPHIS parameters
  assign("WS_1_PUBLIC_PATH","http://147.100.179.156:8080/phenomeapi/resources/", configWS)
  assign("WS_1_PUBLIC_USERNAME","guestphis@supagro.inra.fr", configWS)
  assign("WS_1_PUBLIC_PASSWORD","guestphis", configWS)
  
  assign("WS_2_PUBLIC_PATH","http://www.opensilex.org/openSilexAPI/rest/", configWS)
  assign("WS_2_PUBLIC_USERNAME","guest@opensilex.org", configWS)
  assign("WS_2_PUBLIC_PASSWORD","guest", configWS)
  
}
OpenSILEX/phis-ws-client-r-tool documentation built on Sept. 10, 2020, 8:42 a.m.