-
Couldn't load subscription status.
- Fork 2
Us10 exportar dados #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Brunocrzz
wants to merge
9
commits into
main
Choose a base branch
from
us10_exportar_dados
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
60c11d5
feat: new export modulo, controller and service for export csv function
Brunocrzz fe75577
feat: new tests for module and export
Brunocrzz 0da5e10
feat: tests and remake export functions
Brunocrzz f0a708d
Merge branch 'main' of https://github.com/fga-eps-mds/2024.2-LIVRO-LI…
matheusyanmonteiro d1fa677
fix:lint
matheusyanmonteiro 0606a19
feat: fix export function and new tests
Brunocrzz 9667eae
Merge branch 'us10_exportar_dados' of https://github.com/fga-eps-mds/…
Brunocrzz 690e94b
fix tests and export service
Brunocrzz e06aff2
adjust lint
Brunocrzz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -244,5 +244,47 @@ describe('AuthService', () => { | |
| ); | ||
| expect(sendMailMock).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should send a recovery email when user is found', async () => { | ||
| const email = '[email protected]'; | ||
| const user = new User(); | ||
| user.id = '123'; | ||
| user.email = email; | ||
|
|
||
| jest.spyOn(userRepository, 'findOneBy').mockResolvedValueOnce(user); | ||
| jest.spyOn(jwtService, 'signAsync').mockResolvedValueOnce('mocked-token'); | ||
| sendMailMock.mockResolvedValueOnce(true); | ||
|
|
||
| const result = await service.recoverPassword(email); | ||
|
|
||
| expect(result).toEqual({ success: true }); | ||
| expect(userRepository.findOneBy).toHaveBeenCalledWith({ email }); | ||
| expect(jwtService.signAsync).toHaveBeenCalledWith( | ||
| { sub: user.id }, | ||
| { expiresIn: '30m' }, | ||
| ); | ||
| expect(sendMailMock).toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('changePassword', () => { | ||
| it('should successfully change the password if user exists', async () => { | ||
| const userId = '123'; | ||
| const newPassword = 'newSecurePassword'; | ||
| const user = new User(); | ||
| user.id = userId; | ||
| user.password = 'oldPassword'; | ||
|
|
||
| jest.spyOn(userRepository, 'findOneBy').mockResolvedValueOnce(user); | ||
| jest.spyOn(bcrypt, 'hash').mockResolvedValueOnce('hashed-new-password'); | ||
| jest.spyOn(userRepository, 'save').mockResolvedValueOnce(user); | ||
|
|
||
| const result = await service.changePassword(userId, newPassword); | ||
|
|
||
| expect(result).toEqual({ success: true }); | ||
| expect(userRepository.findOneBy).toHaveBeenCalledWith({ id: userId }); | ||
| expect(bcrypt.hash).toHaveBeenCalledWith(newPassword, expect.any(Number)); | ||
| expect(userRepository.save).toHaveBeenCalledWith(user); | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { Controller, Get, Query, Res } from '@nestjs/common'; | ||
| import { ExportService, ExportOptions } from './export.service'; | ||
| import { Response } from 'express'; | ||
|
|
||
| @Controller('export') | ||
| export class ExportController { | ||
| constructor(private readonly exportService: ExportService) {} | ||
|
|
||
| @Get() | ||
| async exportToCsv( | ||
| @Query('userIds') userIds: string | undefined, | ||
| @Query('bookIds') bookIds: string | undefined, | ||
| @Res() res: Response, | ||
| ) { | ||
| try { | ||
| if (!userIds && !bookIds) { | ||
| console.log('Nenhum userId ou bookIds foi fornecido na query.'); | ||
| return res.status(400).json({ | ||
| message: 'Parâmetro "userIds" ou "bookIds" é obrigatório.', | ||
| }); | ||
| } | ||
|
|
||
| const userIdsArray = userIds | ||
| ? userIds.split(',').map((id) => id.trim()) | ||
| : []; | ||
| const bookIdsArray = bookIds | ||
| ? bookIds.split(',').map((id) => id.trim()) | ||
| : []; | ||
|
|
||
| const options: ExportOptions = { | ||
| userIds: userIdsArray, | ||
| bookIds: bookIdsArray, | ||
| }; | ||
|
|
||
| const csv = await this.exportService.generateCsv(options); | ||
|
|
||
| res.header('Content-Type', 'text/csv'); | ||
| res.attachment('export.csv'); | ||
| return res.send(csv); | ||
| } catch (error) { | ||
| console.log(`Erro ao gerar o CSV: ${error.message}`); | ||
| return res.status(500).json({ | ||
| message: error.message, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export default ExportController; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import { Injectable } from '@nestjs/common'; | ||
|
|
||
| export interface Book { | ||
| id: string; | ||
| titulo: string; | ||
| autor: string; | ||
| tema: string; | ||
| rating: number; | ||
| imageUrl: string; | ||
| } | ||
|
|
||
| @Injectable() | ||
| export class BooksService { | ||
| private books: Book[] = Array.from({ length: 120 }, (_, i) => ({ | ||
| id: `${i + 1}`, | ||
| titulo: `Título ${Math.floor(i / 2) + 1}`, | ||
| autor: `Autor ${(i % 28) + 1}`, | ||
| tema: `Tema ${i + 1}`, | ||
| rating: parseFloat((Math.random() * 5).toFixed(2)), | ||
| imageUrl: | ||
| 'https://plus.unsplash.com/premium_photo-1682125773446-259ce64f9dd7?q=80&w=1171&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D', | ||
| })); | ||
|
|
||
| async findBooksByIds(bookIds: string[]): Promise<Book[]> { | ||
| return this.books.filter((book) => bookIds.includes(book.id)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { Module } from '@nestjs/common'; | ||
| import { ExportController } from './export.controller'; | ||
| import { ExportService } from './export.service'; | ||
| import { UsersModule } from '../users/users.module'; | ||
| import { BooksService } from './export.mockBooks'; | ||
|
|
||
| @Module({ | ||
| imports: [UsersModule], | ||
| controllers: [ExportController], | ||
| providers: [ExportService, BooksService], | ||
| }) | ||
| export class ExportModule {} |
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Os testes estão falhando por conta de timeout excedendo o limite padrão do Jest, possível solução:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| import { Test, TestingModule } from '@nestjs/testing'; | ||
| import { ExportService, ExportOptions } from './export.service'; | ||
| import { UsersService } from '../users/users.service'; | ||
| import { BooksService } from './export.mockBooks'; | ||
| import { parse } from 'json2csv'; | ||
|
|
||
| describe('ExportService', () => { | ||
| let exportService: ExportService; | ||
|
|
||
| const mockUsersService = { | ||
| findByIds: jest.fn(), | ||
| }; | ||
|
|
||
| const mockBooksService = { | ||
| findBooksByIds: jest.fn(), | ||
| }; | ||
|
|
||
| beforeEach(async () => { | ||
| const module: TestingModule = await Test.createTestingModule({ | ||
| providers: [ | ||
| ExportService, | ||
| { provide: UsersService, useValue: mockUsersService }, | ||
| { provide: BooksService, useValue: mockBooksService }, | ||
| ], | ||
| }).compile(); | ||
|
|
||
| exportService = module.get<ExportService>(ExportService); | ||
| }); | ||
|
|
||
| it('should be defined', () => { | ||
| expect(exportService).toBeDefined(); | ||
| }); | ||
|
|
||
| describe('generateCsv', () => { | ||
| it('should generate a valid CSV for users and books', async () => { | ||
| const mockUsers = [ | ||
| { | ||
| id: '1', | ||
| firstName: 'Bruno', | ||
| lastName: 'Cruz', | ||
| email: '[email protected]', | ||
| phone: '123456789', | ||
| createdAt: new Date().toISOString(), | ||
| updatedAt: new Date().toISOString(), | ||
| }, | ||
| ]; | ||
| const mockBooks = [ | ||
| { | ||
| id: '101', | ||
| titulo: 'Titulo do livro', | ||
| autor: 'Author do livro', | ||
| tema: 'Tema do livro', | ||
| rating: 5, | ||
| imageUrl: 'image.jpg', | ||
| }, | ||
| ]; | ||
|
|
||
| mockUsersService.findByIds.mockResolvedValue(mockUsers); | ||
| mockBooksService.findBooksByIds.mockResolvedValue(mockBooks); | ||
|
|
||
| const options: ExportOptions = { userIds: ['1'], bookIds: ['101'] }; | ||
| const result = await exportService.generateCsv(options); | ||
|
|
||
| const expectedUserCsv = parse( | ||
| mockUsers.map((user) => ({ | ||
| id: user.id, | ||
| name: `${user.firstName} ${user.lastName}`, | ||
| lastName: user.lastName, | ||
| email: user.email, | ||
| phone: user.phone, | ||
| createdAt: user.createdAt, | ||
| updatedAt: user.updatedAt, | ||
| })), | ||
| { | ||
| fields: [ | ||
| { label: 'ID', value: 'id' }, | ||
| { label: 'Nome', value: 'name' }, | ||
| { label: 'Sobrenome', value: 'lastName' }, | ||
| { label: 'Email', value: 'email' }, | ||
| { label: 'Telefone', value: 'phone' }, | ||
| { label: 'Criado em', value: 'createdAt' }, | ||
| { label: 'Atualizado em', value: 'updatedAt' }, | ||
| ], | ||
| }, | ||
| ); | ||
|
|
||
| const expectedBookCsv = parse(mockBooks, { | ||
| fields: [ | ||
| { label: 'ID', value: 'id' }, | ||
| { label: 'Titulo', value: 'titulo' }, | ||
| { label: 'Autor', value: 'autor' }, | ||
| { label: 'Tema', value: 'tema' }, | ||
| { label: 'Avaliacao', value: 'rating' }, | ||
| { label: 'Capa', value: 'imageUrl' }, | ||
| ], | ||
| }); | ||
|
|
||
| expect(result).toEqual(`${expectedUserCsv}\n${expectedBookCsv}`); | ||
| }); | ||
|
|
||
| it('should throw an error if no userIds or bookIds are provided', async () => { | ||
| const options: ExportOptions = {}; | ||
| await expect(exportService.generateCsv(options)).rejects.toThrowError( | ||
| 'Nenhum usuário ou livro encontrado para exportação. Verifique os IDs fornecidos.', | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw an error if some bookIds are not found', async () => { | ||
| mockBooksService.findBooksByIds.mockResolvedValue([]); | ||
| const options: ExportOptions = { bookIds: ['999'] }; | ||
| await expect(exportService.generateCsv(options)).rejects.toThrowError( | ||
| 'Os seguintes IDs de livros não foram encontrados no banco de dados: 999', | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw an error if some userIds are not found', async () => { | ||
| mockBooksService.findBooksByIds.mockResolvedValue([]); | ||
| const options: ExportOptions = { userIds: ['888'] }; | ||
| await expect(exportService.generateCsv(options)).rejects.toThrowError( | ||
| 'Os seguintes IDs de usuários não foram encontrados no banco de dados: 888', | ||
| ); | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Corrigir lint e testes que estão falhando se for possivel