Skip to content

Commit

Permalink
Merge pull request #17 from fga-eps-mds/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
HenriqueAmorim20 authored Nov 1, 2023
2 parents 4f20522 + 90aa762 commit 8e145fc
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 6 deletions.
1 change: 1 addition & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ jobs:
docker-compose -f docker-compose.test.yml up -V --force-recreate --build --abort-on-container-exit --exit-code-from gerocuidado-usuario-api-test
env:
TEST: e2e

36 changes: 31 additions & 5 deletions e2e/usuario.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ describe('E2E - Usuario', () => {
email: '[email protected]',
senha,
admin: false,
foto: '1' as any,
};

beforeAll(async () => {
Expand All @@ -33,7 +34,7 @@ describe('E2E - Usuario', () => {
AppModule,
ClientsModule.register([
{
name: 'AUTH_CLIENT_TEST',
name: 'USUARIO_CLIENT_TEST',
transport: Transport.TCP,
options: {
host: '0.0.0.0',
Expand Down Expand Up @@ -69,7 +70,7 @@ describe('E2E - Usuario', () => {
await app.startAllMicroservices();
await app.init();

client = app.get('AUTH_CLIENT_TEST');
client = app.get('USUARIO_CLIENT_TEST');
await client.connect();

repository = app.get<Repository<Usuario>>(getRepositoryToken(Usuario));
Expand All @@ -92,6 +93,7 @@ describe('E2E - Usuario', () => {

Object.assign(user, res.body.data);
delete user.senha;
delete user.foto;
});

it('should not successfully add a new "usuario" when email is already registered', async () => {
Expand Down Expand Up @@ -196,6 +198,26 @@ describe('E2E - Usuario', () => {
});
});

describe('GET TCP - api/usuario', () => {
it('should find one usuario TCP', async () => {
const request = client
.send({ role: 'info', cmd: 'get' }, { id: user.id })
.pipe(timeout(5000));

const response = await lastValueFrom(request);
expect(response.id).toBe(user.id);
});

it('should find all usuario TCP', async () => {
const request = client
.send({ role: 'info', cmd: 'getAll' }, { ids: [user.id] })
.pipe(timeout(5000));

const response = await lastValueFrom(request);
expect(response.length).toBe(1);
});
});

describe('GET - /api/usuario/:id', () => {
it('should successfully get "usuario" by id', async () => {
const res = await request(app.getHttpServer())
Expand All @@ -206,7 +228,9 @@ describe('E2E - Usuario', () => {

expect(res.statusCode).toEqual(200);
expect(res.body.message).toBeNull();
expect(res.body.data).toMatchObject(user);
const data = res.body.data;
delete data.foto;
expect(data).toMatchObject(user);
});

it('should return status 400 when id is invalid', async () => {
Expand Down Expand Up @@ -252,7 +276,7 @@ describe('E2E - Usuario', () => {

expect(res.statusCode).toEqual(200);
expect(res.body.message).toBeNull();
expect(res.body.data).toEqual([user]);
expect(res.body.data.length).toEqual(1);
});
});

Expand All @@ -270,7 +294,9 @@ describe('E2E - Usuario', () => {

expect(res.statusCode).toEqual(200);
expect(res.body.message).toBe('Atualizado com sucesso!');
expect(res.body.data).toMatchObject(user);
const data = res.body.data;
delete data.foto;
expect(data).toMatchObject(user);
});
});

Expand Down
18 changes: 18 additions & 0 deletions src/shared/helpers/sql-query-helper.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
getWhereClauseArrayNumber,
getWhereClauseBoolean,
getWhereClauseIN,
getWhereClauseNumber,
getWhereClauseString,
} from './sql-query-helper';
Expand Down Expand Up @@ -67,3 +68,20 @@ describe('Where Clause ARRAY NUMBER', () => {
expect(where).toBe(" AND id && '{1}'::integer[]");
});
});

describe('Where Clause IN', () => {
it('should return empty string if value is undefined', () => {
const where = getWhereClauseIN(undefined, 'teste');
expect(where).toEqual('');
});

it('should return empty string if value is empty', () => {
const where = getWhereClauseIN([], 'teste');
expect(where).toEqual('');
});

it('should return where string based on given value and tableColumn', () => {
const where = getWhereClauseIN([1], 'teste');
expect(where).toBe(' AND teste IN(1)');
});
});
8 changes: 8 additions & 0 deletions src/shared/helpers/sql-query-helper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
export type ClauseNumber = number | string | undefined;

export function getWhereClauseIN(
value: number[] | undefined,
tableColumn: string,
): string {
if (!value || value.length < 1) return '';
return ` AND ${tableColumn} IN(${value})`;
}

export function getWhereClauseString(
value: string | undefined,
tableColumn: string,
Expand Down
17 changes: 17 additions & 0 deletions src/usuario/usuario.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ describe('UsuarioController', () => {
remove: jest.fn(),
update: jest.fn(),
findAll: jest.fn(),
findAllToPublicacao: jest.fn(),
},
},
{
Expand Down Expand Up @@ -126,4 +127,20 @@ describe('UsuarioController', () => {
expect(data).toEqual([user]);
});
});

it('should find Usuario TCP', async () => {
jest.spyOn(service, 'findOne').mockReturnValue(Promise.resolve(user));

const response = await controller.findOneTCP({ id: 1 });
expect(response).toEqual(user);
});

it('should find all Usuario TCP', async () => {
jest
.spyOn(service, 'findAllToPublicacao')
.mockReturnValue(Promise.resolve([user]));

const response = await controller.findAllTCP({ ids: [1] });
expect(response).toEqual([user]);
});
});
11 changes: 11 additions & 0 deletions src/usuario/usuario.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Patch,
Post,
} from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { HttpResponse } from '../shared/classes/http-response';
import { Filtering, Filtrate } from '../shared/decorators/filtrate.decorator';
import { Ordenate, Ordering } from '../shared/decorators/ordenate.decorator';
Expand Down Expand Up @@ -61,4 +62,14 @@ export class UsuarioController {
const deleted = await this._service.remove(param.id);
return new HttpResponse(deleted).onDeleted();
}

@MessagePattern({ role: 'info', cmd: 'get' })
async findOneTCP(data: { id: number }): Promise<Usuario> {
return this._service.findOne(data.id, true);
}

@MessagePattern({ role: 'info', cmd: 'getAll' })
async findAllTCP(data: { ids: number[] }): Promise<Usuario[]> {
return this._service.findAllToPublicacao(data.ids);
}
}
39 changes: 39 additions & 0 deletions src/usuario/usuario.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,20 @@ describe('UsuarioService', () => {
expect(found).toEqual({ id: 1, nome: 'Henrique' });
});

it('should update Usuario with photo', async () => {
jest.spyOn(repository, 'findOneOrFail').mockReturnValue({ id: 1 } as any);
jest
.spyOn(repository, 'save')
.mockReturnValue({ id: 1, nome: 'Henrique', foto: '1' } as any);

const found = await service.update(1, { nome: 'Henrique' });
expect(found).toEqual({
id: 1,
nome: 'Henrique',
foto: 'data:image/png;base64,1',
});
});

describe('findAll', () => {
const usuario = {
id: 1,
Expand Down Expand Up @@ -169,4 +183,29 @@ describe('UsuarioService', () => {
expect((data as Usuario[])[0]).toEqual(usuario);
});
});

describe('findAllToPublicacao', () => {
const usuario = {
id: 1,
nome: 'Henrique',
email: '[email protected]',
foto: '1',
};

it('should findAllToPublicacao', async () => {
jest.spyOn(repository, 'createQueryBuilder').mockReturnValue({
where: () => ({
getMany: jest.fn().mockResolvedValueOnce([usuario]),
}),
} as any);

const expectedUser = {
...usuario,
foto: 'data:image/png;base64,1',
};

const data = await service.findAllToPublicacao([1]);
expect(data).toEqual([expectedUser]);
});
});
});
27 changes: 26 additions & 1 deletion src/usuario/usuario.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Ordering } from '../shared/decorators/ordenate.decorator';
import { Pagination } from '../shared/decorators/paginate.decorator';
import { getImageUri } from '../shared/helpers/buffer-to-image';
import {
getWhereClauseIN,
getWhereClauseNumber,
getWhereClauseString,
} from '../shared/helpers/sql-query-helper';
Expand Down Expand Up @@ -65,7 +66,14 @@ export class UsuarioService {
async update(id: number, body: UpdateUsuarioDto): Promise<Usuario> {
const found = await this.findOne(id);
const merged = Object.assign(found, body);
return this._repository.save(merged);

const updated = await this._repository.save(merged);

if (updated.foto) {
updated.foto = getImageUri(updated.foto) as unknown as Buffer & string;
}

return updated;
}

async remove(id: number) {
Expand Down Expand Up @@ -108,4 +116,21 @@ export class UsuarioService {

return whereClause;
}

async findAllToPublicacao(ids: number[]): Promise<Usuario[]> {
const where = `1 = 1 ${getWhereClauseIN(ids, 'usuario.id')}`;

const usuarios = await this._repository
.createQueryBuilder('usuario')
.where(`${where}`)
.getMany();

return usuarios.map((usuario) => {
if (usuario.foto) {
usuario.foto = getImageUri(usuario.foto) as unknown as Buffer;
}

return usuario;
});
}
}

0 comments on commit 8e145fc

Please sign in to comment.