Hi all,
I've started reimplementing a clumsy old C# web API as a way to get to know node.js. This is also the first time I'll be using modern JS for anything practical. So, I'm well aware that I might be biting off more than I can chew here :)
To begin with, I made the rookie error of slamming everything into a single JS file. Since it worked (but was ugly), I'm now trying to refactor into something reasonably sensible.
To explain, I'm using:
- express (web server, routing, etc)
- tedious (connection to a Microsoft SQL Server database)
- tedious-connection-pool
I've now got a main.js file which defines the routes, launches the server and receives requests (with routes/methods organised RESTfully). Originally, I had too much database-related stuff in my route handlers - *facepalm*. So, I've now also got a dblayer.js file containing a class to encapsulate db queries via tedious.
The dblayer class provides an execute function with these parameters:
- sql - the sql statement to execute
- params - an array of parameter objects. Optional, but required if sql is parameterised
- response - an express response object. Optional - If present, the function will stream the SQL result as JSON to the response as each row is received -- keeps men usage low for large queries. If absent, then the result array is stored in memory and returned via the callback function
- callback - a function to call when the query is complete. If response is null, then the callback function will receive any result set as an in-memory array.
So, for db access, the main route handlers instantiate a new dblayer instance on each request which, depending on what the operation is (e.g. GET), may either directly stream the result set as json to the express response object, or may execute a provided callback. Also, a tedious-connection-pool is shared amongst the instances of the class so that each call to .execute() may draw on the pool.
Now... this all seems sort of logical to me. There's clearly use-cases I've not implemented yet, but I should be able to add them without too much cruft. However, I'd like to know if this is a sensible way to go?
Many thanks,
Chris