admin管理员组

文章数量:1278858

I consider myself enough petent 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?

I consider myself enough petent 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?

Share Improve this question asked Oct 22, 2018 at 12:33 Niccolò CaselliNiccolò Caselli 8822 gold badges12 silver badges32 bronze badges 3
  • 2 Consider providing the code you're talking about in the question. The question should be understandable without visiting offsite links. Links can go offline. – Estus Flask Commented Oct 22, 2018 at 12:56
  • @estus you're absolutely right, but I found it difficult to find examples to explain what I mean – Niccolò Caselli Commented Oct 22, 2018 at 13:00
  • 1 Vanilla Express basically doesn't need classes, it's pretty much barebone. But you can check NestJS (it is based on Express) for some ideas how Express can fit OOP design. – Estus Flask Commented Oct 22, 2018 at 13:04
Add a ment  | 

1 Answer 1

Reset to default 13

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 plicated version of:

const app = express();

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

export default app;

本文标签: javascriptShould I wrap all my express server in a class with typescriptStack Overflow