Search code examples
coldfusionlucee

how can i store the value returned by my init to be used in my functions


I have the init code and it returns me a structure

public any function init() {
    httpService = new http();
    httpService.setUrl("#Application.baseURL#security/oauth2/token");
    httpService.setMethod("POST");
    httpService.addParam(type="header", name="Content-Type", value="application/x-www-form-urlencoded");
    httpService.addParam(type="body", value="client_id=#application.clientID#&client_secret=#application.clientsecretID#&grant_type=#application.grant_type#");
    result = httpService.send().getPrefix();
    return this;
}

problem how can i use the token returned by the method in other methods, if i dump the init, i am just getting the functions, how can i use the data returned by the http

just not getting in my head, because the token is alive for 3600

Thanks


Solution

  • As James says, you should store the result of the http call as an instance variable. Here's one way of doing it using a property and specifying accessors=true for the component so that you can call setHttpResult() and getHttpResult() without having to write those methods. using the variables scope which will make it available to other methods within the component, but not outside.

    /* Test.cfc */
    component name="test"{
    
        property name="httpResult" type="struct";
    
        public any function init(){
            //use "var" to ensure the variable is local to the function only
            var httpService = new http();
            httpService.setUrl("#Application.baseURL#security/oauth2/token");
            httpService.setMethod("POST");
            httpService.addParam(type="header", name="Content-Type", value="application/x-www-form-urlencoded");
            httpService.addParam(type="body", value="client_id=#application.clientID#&client_secret=#application.clientsecretID#&grant_type=#application.grant_type#");
            //store the result privately in the instance
            variables.httpResult = httpService.send().getPrefix();
            return this;
        }
    
        public void function someOtherMethod(){
            // this method can access the result struct
            var returnedContent = variables.httpResult.fileContent;
        }
    
    
    }
    

    You can then use getHttpResult() inside or outside your component. For example from an external script:

    test = New test(); // calls the init() method
    WriteDump( test.getHttpResult() ); //auto-generated "getter"