Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I wrap all my express server in a class with typescript?

I consider myself enough competent with nodeJs. I have recently decided to change my applications by starting to develop with Typescript. I have recently seen many blogs (like this one) that when creating a RESTful API, they wrapped all the modules and above all the entry point of the app in a class. Is it correct or can I continue to develop my apps with typescript as I had before?

like image 860
Niccolò Caselli Avatar asked Oct 22 '18 12:10

Niccolò Caselli


1 Answers

This is a matter of style rather than anything else. But Express doesn't promote OOP for its units and there are no distinct benefits from defining an app as a class:

class App {

    public app: express.Application;

    constructor() {
        this.app = express();
        this.config();        
    }

    private config(): void{
        // support application/json type post data
        this.app.use(bodyParser.json());

        //support application/x-www-form-urlencoded post data
        this.app.use(bodyParser.urlencoded({ extended: false }));
    }

}

export default new App().app;

App is a singleton that isn't supposed to be reused. It doesn't provide any benefits that classes are known for like reusability or testability. This is unnecessarily complicated version of:

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

export default app;
like image 172
Estus Flask Avatar answered Nov 05 '22 00:11

Estus Flask