Search code examples
javascriptjqueryaemsling

JS: Check if Sling resource exists without creating 404 error


I want to check if a Sling ressource already exists. Currently I use CQ.HTTP.get(url) to accomplish this. The problem is that if the ressource does not exist, JS logs a 404 error to the console which I think is ugly.

Is there a better way to check if a ressource exists which doesn't pollute the console?


Solution

  • Here is a simple servlet that does what you're asking:

    /**
     * Servlet that checks if resource exists.
     */
    @SlingServlet
    (
        paths = "/bin/exists",
        extensions = "html",
        methods = "GET"
    )
    public class ResourceExistsServlet extends SlingSafeMethodsServlet {
    
        @Override
        protected void doGet(final SlingHttpServletRequest request,
                             final SlingHttpServletResponse response) throws ServletException, IOException {
            // get the resource by the suffix
            // for example, in the request /bin/exists.htm/apps, "/apps" is the suffix and that's the resource obtained here.
            Resource resource = request.getRequestPathInfo().getSuffixResource();
            // resource is null, does not exist, not null, exists
            boolean exists = resource != null;
            // make the response content type JSON
            response.setContentType(JSONResponse.APPLICATION_JSON_UTF8);
            // Write the json to the response
            // TODO: use a library for more complicated JSON, like google's gson. In this case, this string suffices.
            response.getWriter().write("{\"exists\": "+exists+"}");
        }
    }
    

    And here is some sample JS to call the servlet:

    // Check if a path exists exists
    function exists(path){
      return $.getJSON("/bin/exists.html"+path);
    }
    
    // check if /apps exists
    exists("/apps")
    .then(function(res){console.log(res.exists)})
    // prints: true
    
    
    // check if /apps123 exists
    exists("/apps123")
    .then(function(res){console.log(res.exists)})
    // prints: false