My app is based around a custom REST API we have built. I have built a module that I require in lua, and can then call when I wish to make an API request. I have done it this way because there is a chunk of processing code that needs to get run every time (like preparing variables, authentication with API, etc), so it makes sense to be a module.
I am calling the API module like so:
api.request( 'users/me', 'GET' )
This in turn tells the module to to a network.request() with various parameters required to get a valid response.
Now this all works fine. My issue is how I can return the response that my network.request listener receives to the original api.request call. At present there is a function called networkListener within the api module. This obviously doesn’t work as I need it to…
I know that network.request() is asynchronus, as such it cannot possibly return the response from the network request. However, there must be some weird and wonderful way I can do what I need to do. One possibility I have thought of would be to create a function in my calling code before I call api.request, and this overrides the default function found in the api module. I wouldn’t know how to do this though, so any input is great. As an example of what I’m thinking it would look like the below:
Anywhere within the code:
[lua]api:listener = function(){
print ( ‘network response here some how’ )
}
api.request( ‘users/me’, ‘GET’ )[/lua]
Within the API module:
[lua]api = {};
api:listener = function(){
– default behaviour
}
function api.request( path, method ){
– Lots of processing and whatnot here, not important for this example
– …
– …
network.request ( apiUrl … path, method, api:listener, params )
}
return api;[/lua]
Hope this makes sense. Any help hugely appreciated.
[import]uid: 61422 topic_id: 25503 reply_id: 325503[/import]