diff --git a/posts/handler-service-presentation.md b/posts/handler-service-presentation.md index 117d846..df7ecc4 100644 --- a/posts/handler-service-presentation.md +++ b/posts/handler-service-presentation.md @@ -20,3 +20,46 @@ I am going to be talking about this pattern in relationship to JavaScript and wh ## The Application Like the previous post, I talked about building this blog with Bun and Hono. I am going to do the same here, however the application we are going to build is the all time classic - The TODO Application. + +## JavaScript + +One of the important things about JavaScript that alluded me for far too long was how the modules actually worked with Node.js. A module before ES6 was simply a JavaScript file that declares a `module.exports` value with the code you want to expose to other modules with the `require` function. Like so: + +```js +function doSomething() { + // ... +} + +module.exports = doSomething; +``` +_`example.js`_ + +Then we can pull in `doSomething` with `require`: + +```js +const doSomething = require('./example'); +``` +_`index.js`_ + +I don't know why I didn't know this, but the code in the `example.js` file is evaluated **and** run during the `require()` call. + +In my past life I would try and build a Singleton class for holding onto an application's Connection Pool to a database. But because of how the Modules in Node.js work, we only need to instantiate the Pool and export it. Here's an example of how we can set up a single pool using the MariaDB official package: + +```js +const mariadb = require('mariadb'); + +const config = { ... }; +const pool = mariadb.createPool(config); + +module.eports = pool; +``` +_`pool.js`_ + +Now the connection pool is only created once and you can require this + + + + + + +