2.5 KiB
title | description | date | tags | slug | draft | ||||
---|---|---|---|---|---|---|---|---|---|
HS(D)P | Describing the architecture of Handlers, Services, (Domains), and Presentation | 2024-08-11 |
|
hsdp | true |
Handlers, Services, (Domains?), Presentation
In my last blog post I talked about how I have stopped thinking of my Node.js applications as Model-View-Controller and started thinking of the applications in a new, fun acronym: Handlers, Services, (sometimes Domains), and Prfesentation. I thought this would be a good topic for a new blog post. So here it is.
I am going to be talking about this pattern in relationship to JavaScript and why the language lends itself to the pattern when working on applications.
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:
function doSomething() {
// ...
}
module.exports = doSomething;
example.js
Then we can pull in doSomething
with require
:
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:
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
Outline:
- Explain what I know about JavaScript
- How does this differ to my experience with PHP
- Describe modules
- Describe how we can set up singletons thinking in modules
- Talk about avoiding classes
- Talk about big express applications
- And how I used to make MVC applications