D
D
Delakey Blackhole2017-04-09 22:18:56
MongoDB
Delakey Blackhole, 2017-04-09 22:18:56

How to use single class in express js?

I have app.ts and several classes for routing
, they must use a connection to the database (mongoose), but how can I implement so that the class (service) for working with the database is passed to these classes for routing?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Coder321, 2017-04-10
@Coder321

Any exported class will be a singleton.

class Service {}

export.module = new Service();

or just to be sure
class Service {}
let service = () => {
    let instance
    function init() {
        let opt = new Service()
        return opt
    }
    return {
        getInstance: function () {
            if (!instance) {
                instance = init()
            }
            return instance
        }
    }
}

module.export = service().getInstance()

H
hufawoso, 2017-04-09
@hufawoso

The simplest is to attach it to the app object.
Those. so that at any time you can contact: app.db

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question