Skip to content

Commit

Permalink
Merge branch 'feature/swagger-routes' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
agleicesousa committed Dec 17, 2024
2 parents b05b150 + 880dcf4 commit fdd8f88
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 45 deletions.
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"@types/bcrypt": "^5.0.2",
"bcrypt": "^5.1.1",
"cors": "2.8.5",
"express": "^4.21.0",
"express": "^4.21.1",
"express-validator": "^7.2.0",
"mongodb": "5.9.0",
"mysql2": "3.11.3",
Expand Down
76 changes: 51 additions & 25 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,35 +12,61 @@ import professorRouter from './routes/professorRoutes';
import alunoRouter from './routes/alunoRoutes';
import loginRouter from './routes/loginRoutes';
import pdiRouter from './routes/pdiRoutes';
MysqlDataSource.initialize()
.then(() => {
console.log('Database initialized!');
})
.catch((err) => {
console.error('Database Error: ', err);
});

const app = express();
// Função para iniciar o banco de dados
const initializeDatabase = async () => {
try {
await MysqlDataSource.initialize();
console.log('✅ Database initialized!');
} catch (err) {
console.error('❌ Database initialization failed:', err);
process.exit(1); // Encerra o processo em caso de erro
}
};

// Função para configurar o Swagger
const setupSwagger = (app: express.Application) => {
const swaggerSpec = swaggerJSDoc(swaggerConfig);
app.use('/swagger', swaggerUI.serve, swaggerUI.setup(swaggerSpec));
app.get('/swagger.json', (_req, res) => res.send(swaggerSpec));
console.log('✅ Swagger configured at /swagger');
};

const main = async () => {
await initializeDatabase();

app.use(express.json());
app.use(cors({ origin: true }));
const app = express();

app.use('/admin', adminRouter);
app.use('/membros', membrosRouter);
app.use('/turmas', turmasRouter);
app.use('/professores', professorRouter);
app.use('/alunos', alunoRouter);
app.use('/auth', loginRouter);
app.use('/pdi', pdiRouter);
app.use(errorHandler);
// Middlewares
app.use(express.json());
app.use(cors({ origin: true }));

const swaggerSpec = swaggerJSDoc(swaggerConfig);
// Rotas
app.use('/admin', adminRouter);
app.use('/membros', membrosRouter);
app.use('/turmas', turmasRouter);
app.use('/professores', professorRouter);
app.use('/pdi', pdiRouter);
app.use('/alunos', alunoRouter);
app.use('/auth', loginRouter);

app.use('/swagger', swaggerUI.serve, swaggerUI.setup(swaggerSpec));
app.get('/swagger.json', (_req, res) => res.send(swaggerSpec));
// Configuração do Swagger
setupSwagger(app);

console.log(`Add swagger on /swagger`);
// Middleware de erros
app.use(errorHandler);

// Validação de variáveis de ambiente
const PORT = process.env.SERVER_PORT || 3000;
if (!PORT) {
console.error('❌ SERVER_PORT não definido nas variáveis de ambiente.');
process.exit(1);
}

// Inicia o servidor
app.listen(PORT, () => {
console.log(`✅ Server listening on port ${PORT}`);
});
};

app.listen(process.env.SERVER_PORT, () => {
console.log(`Server listening on port ${process.env.SERVER_PORT}`);
});
main();
30 changes: 19 additions & 11 deletions src/config/swagger.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,37 @@
import swaggerJSDoc from 'swagger-jsdoc';

export const swaggerConfig: swaggerJSDoc.OAS3Options = {
swaggerDefinition: {
export const swaggerConfig: swaggerJSDoc.Options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Civitas API',
description: 'Documentação da API do projeto Civitas',
version: '1.0.0'
},
host: 'localhost:4444',
// Não obrigatório, serve apenas para definir a ordem das categorias
tags: [],
servers: [
{
url: 'http://localhost:4444', // URL do servidor de desenvolvimento
description: 'Servidor Local'
}
],
externalDocs: {
description: 'View swagger.json',
url: '../swagger.json'
description: 'Swagger JSON',
url: '../swagger.json' // Confirme se esse caminho é acessível
},
components: {
securitySchemes: {
BearerAuth: {
in: 'header',
type: 'http',
scheme: 'bearer'
scheme: 'bearer',
bearerFormat: 'JWT' // Especifique que o formato esperado é JWT
}
}
}
},
security: [
{
BearerAuth: [] // Aplica a autenticação BearerAuth globalmente (se necessário)
}
]
},
apis: ['src/routes/*.ts', 'routes/*.js']
apis: ['src/routes/*.ts', 'routes/*.js'] // Caminhos para buscar as rotas
};
61 changes: 61 additions & 0 deletions src/routes/loginRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,67 @@ import { LoginController } from '../controller/loginController';
const loginRoutes = Router();
const controller = new LoginController();

/**
* @swagger
* tags:
* name: Login
* description: Autenticação e gerenciamento de login
*/

/**
* @swagger
* /login:
* post:
* summary: Realiza o login de um usuário
* tags: [Login]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* email:
* type: string
* description: Email do usuário
* example: usuario@example.com
* password:
* type: string
* description: Senha do usuário
* format: password
* example: "12345678"
* responses:
* 200:
* description: Login bem-sucedido.
* content:
* application/json:
* schema:
* type: object
* properties:
* token:
* type: string
* description: Token de autenticação
* 400:
* description: Erro na requisição (dados inválidos).
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* description: Mensagem de erro detalhada
* 401:
* description: Credenciais inválidas.
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* description: Mensagem de erro detalhada
*/
loginRoutes.post('/login', (req, res) => controller.login(req, res));

export default loginRoutes;

0 comments on commit fdd8f88

Please sign in to comment.