Refactoring With QB
Background
Currently our users handler simply passes the data on to our UserService model and then hands the results back to the UI. The allUsers() function in the UserService looks like this:
function allUsers(){
return queryExecute("select * from users");
}
We just added a route to retrieve only one user but have not created the handler for it nor decided how the data is going to be retrieved. According to the DRY (Don't Repeat Yourself) paradigm, we probably do not what to create another separate function simply to add a criteria to the query. However, to reuse the current allUsers() function, we need to start building our query by concatenating one large string using if then statements which can get very tedious, be difficult to read and error prone. There is a much better way by using QB - Query Builder - a module by Eric Peterson which is an open source project in ForgeBox.
Adding QB to our Application
From CommandBox in the root of our site, type
install qb.In our UserService.cfc model, add
property name="qb" inject="provider:QueryBuilder@qb";to the top of the component. This will tell Wirebox to make QB available to the UserService.cfc model.Change the allUsers function to look like this
function allUsers(){ return qb.from("users").get(); }Reinit the application by visiting https://justenough.local/?fwreinit=1 or restarting the server and either open https://justenough.local/users in a browser or hit it from the companion app.
Last updated