Skip to content

Instantly share code, notes, and snippets.

@ortense
Forked from andregardi/index.ts
Created February 4, 2019 14:20
Show Gist options
  • Save ortense/8aa6a5676532c5a27569d80178a88c71 to your computer and use it in GitHub Desktop.
Save ortense/8aa6a5676532c5a27569d80178a88c71 to your computer and use it in GitHub Desktop.
import "reflect-metadata";
import { createConnection } from "typeorm";
import * as express from "express";
import * as bodyParser from "body-parser";
import * as helmet from "helmet";
import * as cors from "cors";
//Connects to the Database -> then starts the express
createConnection()
.then(async connection => {
// Create a new express application instance
const app: express.Application = express();
// Call midlewares
app.use(cors());
app.use(helmet());
app.use(bodyParser.json());
//Set all routes from routes folder
const index = require("./routes/");
app.use("/", index);
app.listen(3000, function() {
console.log("Server started on port 3000!");
});
})
.catch(error => console.log(error));
@ortense
Copy link
Author

ortense commented Feb 4, 2019

Eu removeria a criação do app de dentro do callback da conexão

Inclusive separaria em dois arquivos

Um app.ts focado na configuração do servidor.

import * as express from "express";
import * as bodyParser from "body-parser";
import * as helmet from "helmet";
import * as cors from "cors";
import * as routes from "./routes/";

// Create a new express application instance
export const app = express();

// Call midlewares
app.use(cors());
app.use(helmet());
app.use(bodyParser.json());

//Set all routes from routes folder
app.use("/", index);

Outro main.ts, start.ts, boot.ts, ou algo assim, focado apenas na inicialização da api

import "reflect-metadata";
import { createConnection } from "typeorm";
import { app } from "./app"

createConnection()
  .then(() => app
    .listen(3000, () => console.log("Server started on port 3000!")))
  .catch(console.error);

Isso é util principalmente para para testes integrados, se você quiser isolar as requests sem necessariamente subir o banco.

@ortense
Copy link
Author

ortense commented Feb 4, 2019

Salvas exceções dê preferência a para arrow functions em callback.

Evite misturar require e import, principalmente se o requireestiver dentro de um callback, nesse exemplo não existe impacto por se tratar de boot, mas em produção vc gera um I/O síncrono em runtime, que bloqueia a thread principal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment