Answer the question
In order to leave comments, you need to log in
Best practice for connecting 3rd party libraries to express js application without hard linking?
Good afternoon!
Tell me how to correctly implement the project structure in express? I myself have been working on PhalconPHP for a long time and I want to rewrite some projects on express, but I met with a problem: the architecture of the express js project, in particular with DI, Module Require. And I can’t figure out how best to connect third-party libraries without DI, and how to do it with Module Require, so that there is no hard connection with libraries.
I'm doing it this way now, but I'm not sure if it's right.
//db.js
var mysql = require('promise-mysql');
var config = require('../config');
var pool = mysql.createPool(config.db);
module.exports = pool;
//users.js
var express = require('express');
var router = express.Router();
router.get('/', async function(req, res, next) {
var db = await require('lib/db');
var result = await db.query("SELECT 1 + 1 AS test");
res.send(result);
});
module.exports = router;
Структура
routes/users.js
lib/db.js
app.js
config.js
Answer the question
In order to leave comments, you need to log in
Although this approach works, I would not divide it like that - this just creates a hard binding between the library and the called function. It will be difficult to test this.
How can you do it:
1. Pass dependencies to the handler function through a closure, for example:
async handler (db) {
return (req, res, next) => {
var result = await db.query("SELECT 1 + 1 AS test");
res.send(result);
}
})
db = require('lib/db');
router.get('/', handler(db));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question