Friday, 26 May 2017

Node.js: exporting class/prototype vs. instance

As I do most of my programming in Java, I find it compelling to export a class in a Node.js module instead of an object instance, e.g.:

class Connection {
    constructor(db) {
        this.db = db;
    }
    connect(connectionString) {
        this.db.connect(connectionString);
    }
}
exports.Connection = Connection;

Since doing this would require instantiating the class multiple times across dependent modules, I still need to export an already existing instance for use in the rest of the production code. I do it in the same module:

exports.connection = new Connection(require("mongoose"));

This allows for some testability, as the real dependency can be swapped in a test:

const Connection = require("./connection").Connection;

describe("Connection", () => {
    it("connects to a db", () => {
        const connection = new Connection({connect: () => {}});
        // ...
    });
});

This approach works, but it has a strange feel to it as I'm mixing two patterns here: exporting a prototype (for unit tests) and an instance (for the production code). Is this acceptable? Should I continue with this or change to something different? If so, what is the preferred pattern?



via mingos

No comments:

Post a Comment