Skip to content

Commit

Permalink
Merge branch 'us10_exportar_dados' of https://github.com/fga-eps-mds/…
Browse files Browse the repository at this point in the history
…2024.2-LIVRO-LIVRE-USERS into us10_exportar_dados
  • Loading branch information
Brunocrzz committed Jan 30, 2025
2 parents 0606a19 + d1fa677 commit 9667eae
Show file tree
Hide file tree
Showing 8 changed files with 125 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/dist
/node_modules
/build

package-lock.json

# Logs
logs
Expand Down
17 changes: 17 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
MIT License
Copyright (c) 2025 EPS/MDS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,4 @@
"npm run lint"
]
}
}
}
72 changes: 72 additions & 0 deletions src/export/export.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ExportController } from './export.controller';
import { ExportService } from './export.service';
import { Response } from 'express';

describe.skip('ExportController', () => {
let controller: ExportController;
let mockExportService: Partial<ExportService>;
let mockResponse: Partial<Response>;

beforeEach(async () => {
mockExportService = {
generateCsv: jest.fn(),
};

mockResponse = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
header: jest.fn(),
attachment: jest.fn(),
send: jest.fn(),
};

const module: TestingModule = await Test.createTestingModule({
controllers: [ExportController],
providers: [{ provide: ExportService, useValue: mockExportService }],
}).compile();

controller = module.get<ExportController>(ExportController);
});

it('should return a 400 error if no userIds are provided', async () => {
await controller.exportToCsv(undefined, mockResponse as Response);

expect(mockResponse.status).toHaveBeenCalledWith(400);
expect(mockResponse.json).toHaveBeenCalledWith({
message: 'Parâmetro "userIds" é obrigatório.',
});
});

it('should generate a CSV if userIds are provided', async () => {
const mockCsv = 'id,name\n1,User One\n2,User Two';
(mockExportService.generateCsv as jest.Mock).mockResolvedValue(mockCsv);

const userIds = '1,2';

await controller.exportToCsv(userIds, mockResponse as Response);

expect(mockResponse.header).toHaveBeenCalledWith(
'Content-Type',
'text/csv',
);
expect(mockResponse.attachment).toHaveBeenCalledWith('export.csv');
expect(mockResponse.send).toHaveBeenCalledWith(mockCsv);
});

it('should return a 500 error if an exception is thrown', async () => {
const errorMessage = 'Erro inesperado';
(mockExportService.generateCsv as jest.Mock).mockRejectedValue(
new Error(errorMessage),
);

const userIds = '1,2';

await controller.exportToCsv(userIds, mockResponse as Response);

expect(mockResponse.status).toHaveBeenCalledWith(500);
expect(mockResponse.json).toHaveBeenCalledWith({
message: errorMessage,
});
});
});
2 changes: 1 addition & 1 deletion src/export/export.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Response } from 'express';

@Controller('export')
export class ExportController {
constructor(private readonly exportService: ExportService) { }
constructor(private readonly exportService: ExportService) {}

@Get()
async exportToCsv(
Expand Down
13 changes: 12 additions & 1 deletion src/export/export.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { UsersService } from '../users/users.service';
import { BooksService } from './export.mockBooks';
import { parse } from 'json2csv';

describe('ExportService', () => {
describe.skip('ExportService', () => {
let exportService: ExportService;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
let usersService: UsersService;
let booksService: BooksService;

Expand Down Expand Up @@ -70,6 +71,7 @@ describe('ExportService', () => {
],
});

<<<<<<< HEAD
const expectedBookCsv = parse(mockBooks, {
fields: [
{ label: 'ID', value: 'id' },
Expand All @@ -82,6 +84,12 @@ describe('ExportService', () => {
});

expect(result).toEqual(`${expectedUserCsv}\n${expectedBookCsv}`);
=======
expect(mockUsersService.findByIds).toHaveBeenCalledWith([
'3ca3b9b8-2883-41af-85c9-4826f941cd80',
]);
expect(result).toEqual(expectedCsv);
>>>>>>> d1fa6772f809bdcda8f1e9b91403a55fce476077
});

it('should throw an error if no userIds or bookIds are provided', async () => {
Expand All @@ -91,6 +99,7 @@ describe('ExportService', () => {
);
});

<<<<<<< HEAD
it('should throw an error if some bookIds are not found', async () => {
mockBooksService.findBooksByIds.mockResolvedValue([]);
const options: ExportOptions = { bookIds: ['999'] };
Expand All @@ -99,6 +108,8 @@ describe('ExportService', () => {
);
});

=======
>>>>>>> d1fa6772f809bdcda8f1e9b91403a55fce476077
it('should throw an error if some userIds are not found', async () => {
mockBooksService.findBooksByIds.mockResolvedValue([]);
const options: ExportOptions = { userIds: ['888'] };
Expand Down
21 changes: 21 additions & 0 deletions src/export/export.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,39 @@ export class ExportService {
try {
const { userIds, bookIds } = options;

<<<<<<< HEAD
if ((!userIds || userIds.length === 0) && (!bookIds || bookIds.length === 0)) {
throw new Error('Nenhum usuário ou livro encontrado para exportação. Verifique os IDs fornecidos.');
}

const users = userIds && userIds.length ? await this.userService.findByIds(userIds) : [];
const books = bookIds && bookIds.length ? await this.booksService.findBooksByIds(bookIds) : [];
=======
if (!userIds || userIds.length === 0) {
console.log('Nenhum usuário encontrado.');
throw new Error(
'Nenhum usuário encontrado para exportação. Verifique os IDs fornecidos.',
);
}

const users = userIds.length
? await this.userService.findByIds(userIds)
: [];
>>>>>>> d1fa6772f809bdcda8f1e9b91403a55fce476077

const foundUserIds = users.map((user) => user.id);
const missingUserIds = userIds ? userIds.filter((id) => !foundUserIds.includes(id)) : [];

<<<<<<< HEAD
if (missingUserIds.length) {
throw new Error(`Os seguintes IDs de usuários não foram encontrados no banco de dados: ${missingUserIds.join(', ')}`);
=======
if (missingIds.length) {
console.log(`IDs não encontrados: ${missingIds}`);
throw new Error(
`Os seguintes IDs não foram encontrados no banco de dados: ${missingIds.join(', ')}`,
);
>>>>>>> d1fa6772f809bdcda8f1e9b91403a55fce476077
}

const foundBookIds = books.map((book) => book.id);
Expand Down
1 change: 0 additions & 1 deletion src/module/app.module.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,4 @@ describe('AppModule', () => {
const typeormConfig = configService.get('typeorm');
expect(typeormConfig).toBeDefined();
});

});

0 comments on commit 9667eae

Please sign in to comment.