spark-java

Need to return object before/ignoring path in spark java


I want to write my own very basic caching inside my sparkjava server.

My thought is to cache the response somewhere, and have some code in a before block that checks if the incoming path is one that should return the cached string/response or should carry on to the appropriate path and calculate the response (storing it in the cache for future calls).

My question is, if i understand sparkjava properly, is how can i return the response from inside the before block and not carry on into the path

Or maybe it's not possible?

Alternatively, i can check inside every path at the beginning of each, to either use the cached response or create a fresh one, but writing this in every path block instead of writing it once in a before feels wrong/is needlessly duplicating.


Solution

  • I think you can return any string data in a halt() statement during your before-filter. This approach is outlined in the Spark documentation located at: http://sparkjava.com/documentation#halting.

    Example:

    before( (req, res) -> {
    
       // somehow prove the request matches a request that was previously cached
       if(req.contextPath() == known_cached_path){
          halt(304, cached_data);
       }
    });