O
O
Oscar S2019-07-25 10:34:28
Node.js
Oscar S, 2019-07-25 10:34:28

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

2 answer(s)
R
RidgeA, 2019-07-25
@RidgeA

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));

a similar approach can be done using objects and classes, where you pass dependencies to the constructor, while you must not lose this when passing the function as a handler
2. ExpressJS allows you to assign some objects to the response context or the context of the application itself.
- answer - expressjs.com/en/4x/api.html#res.locals
- application - expressjs.com/en/4x/api.html#app.locals
3. There are packages in npm that implement DI, but nothing here Can't recommend - haven't used it.
You can do this, but it's not entirely obvious

L
longclaps, 2017-11-11
@kuznecov85

SELECT movie.*
FROM movie
  JOIN movie_genre A ON movie.id = A.movie_id
  JOIN movie_genre B ON movie.id = B.movie_id
WHERE A.genre_name = 'horror' AND B.genre_name = 'comedy';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question