Last week I shared that I was feeling overwhelmed. I’m responsible for the REST API for our project. If you recall, I mentioned that our project requires CRUD operations for 14 different services, each requiring 10 – 15 pieces of information. The thought of manually validating that much data was mind boggling. I needed structure and fast! So I took some time to research Object Relational Mapping or ORM.
I had heard of Object Relational Mapping during both my databases and cloud courses. Essentially, I was told not to use it. I’m a little disheartened that no one taught it to us. I found a library called gstore-node that allows me to create schemas for each of my fourteen services, and it integrates with Datastore, simplifying the query process. Here’s some example code from my cloud portfolio project using Datastore. I really hated this code but I didn’t know to improve it at the time. Also please notice how this code is in a file containing 300 lines of code!
After reading the gstore-node documentation and reviewing several sample projects, I finally started to understand best practices. I separated each pest control service (i.e. feature) into their own directories containing a model, controller, and router. I read that this method is preferable to having three directories named model, controller, and router containing several feature files. For more information, follow this link.
As I began work on the next service, I realized that roach.controller.js
contains the same logic for every single feature. So I removed that file into it’s own controller
directory and changed the function names to be more generic.
Now to the server code… compare my previous portfolio project POST request without an ORM to my current POST request using gstore-node. The entire file is 19 lines of code.
It certainly helps to separate code blocks into files, but hopefully you can see how the ORM does the heavy lifting. The largest file here contains only 55 lines of code, instead of hundreds. Functions like sanitize(), save(), update(), schema(), and plain() abstract away extra steps that cluttered my cloud portfolio project. Though it took me a few days to learn gstore-node and get my first working route, I spent about five minutes on the second route. Now I feel confident that I can knock out 12 more including testing and documentation in an hour or two. That’s the power of using an ORM. There is an upfront cost but it’s so much simpler in the long run. There is a better way, and the way is Object Relational Mapping.