Adding our Show Handler

Background

The show method is conventionally used to return a single record from our database. When we created the route we used /users/:userId as the pattern which added the userId key to the rc scope. Our show method is going to pass that userId onto our allUsers method which we are going to refactor.

Creating out Show Method

Our show method is fairly straightforward

    function show(event, rc, prc){
        var allUsers = userService.allUsers( rc.userId );
        prc.response.setData(allusers);
    }

Adapting our allusers() method

  1. First we need to add a parameter for the is we're going to search for

        function allUsers( numeric userId ){
            return qb.from("users").get();
        }
  2. Next let's adapt our query to search with the userId as a criteria

        function allUsers( numeric userId ){
            return qb.from("users")
                .where("id",arguments.userId)
                .get();
        }
  3. However, this change means we can't use it to return all of our users unless we put in some conditionals so let's put in a default value of 0 for the userId and only use the userid criteria the userid is over 0. Notice we also had to change what the conditional referred to, it's no longer in the arguments scope of where it is because it is now in the closure.

        function allUsers(numeric userId=0){
            return qb.from("users")
                .when(arguments.userid>0,(q)=>{
                    q.where("id",userId)
                })
                .get();
        }
    
  4. That formatting doesn't look very good so let's use cfformat to clean it up.

    1. From CommandBox, type install commandbox-cfformat

    2. From CommandBox from the root of the website type cfformat run models/UserService.cfc --overwrite

    3. This will automatically clean up the formatting. The rules can be changed as desired. The ColdBox app comes with the rules that Ortus uses by default. Note: Those rules are not necessarily reflected here because of formatting differences between the IDE and gitbook.

    	function allUsers( numeric userId = 0 ){
    		return qb
    			.from( "users" )
    			.when( arguments.userid > 0, ( q ) => {
    				q.where( "id", userId )
    			} )
    			.get();
    	}

Last updated