Skip to content

chore: sync main from Aceleradora25 - fix ordenar sequence e feat util pagination tests#73

Merged
jauregao merged 9 commits intoaceleradora-TW:mainfrom
Aceleradora25:main
Mar 11, 2026
Merged

chore: sync main from Aceleradora25 - fix ordenar sequence e feat util pagination tests#73
jauregao merged 9 commits intoaceleradora-TW:mainfrom
Aceleradora25:main

Conversation

@jauregao
Copy link
Contributor

Este PR sincroniza as últimas alterações mergeadas na main do Aceleradora25/e-acelera-back para o repositório aceleradora-TW/e-acelera-back.

🆙 CHANGELOG
[#60] fix: bug ordenar sequence (ver PR original)

Corrigida ordenação dos dados retornados pela API do Stackby
Conversão do campo field.sequence para número antes da ordenação
Garantido retorno no formato StackbyDataResponse

[#57] feat: util pagination tests (ver PR original)
Criação de testes para ThemeService validando cálculo de skip, take e objeto meta
Correção do mock no StackbyService.test.ts (de "endpoint" para "Themes")
Implementação da utilitária centralizada de paginação em src/utils/pagination.util.ts
Testes passando: ThemeService.test.ts, StackbyService.test.ts, pagination.test.ts

@jauregao jauregao requested a review from Aceleradora25 March 11, 2026 13:42
@jauregao jauregao self-assigned this Mar 11, 2026
Copilot AI review requested due to automatic review settings March 11, 2026 13:42
@vercel
Copy link

vercel bot commented Mar 11, 2026

@jauregao is attempting to deploy a commit to the Aceleradora Ágil's projects Team on Vercel.

A member of the Team first needs to authorize it.

@vercel
Copy link

vercel bot commented Mar 11, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
e-acelera-back Ready Ready Preview, Comment Mar 11, 2026 1:44pm

@jauregao jauregao merged commit 82c5f66 into aceleradora-TW:main Mar 11, 2026
4 checks passed
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Este PR sincroniza alterações da main do repositório upstream, com foco em corrigir a ordenação por sequence nos dados retornados pelo Stackby e em adicionar/ajustar testes de paginação e de serviços.

Changes:

  • Ajusta StackbyService.fetchStackbyData para normalizar field.sequence e ordenar os itens retornados.
  • Adiciona testes para a util de paginação e para ThemeService.getThemes.
  • Ajusta teste de StackbyService (endpoint) e pequenas alterações de mocks/estilo em testes do login.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 9 comments.

Show a summary per file
File Description
src/utils/pagination.test.ts Adiciona cobertura de testes para cálculo de skip/take e limites permitidos.
src/services/theme/ThemeService.ts Ajusta criação de theme (sequence) e adiciona log de debug durante getThemes.
src/services/theme/ThemeService.test.ts Cria teste para validar parâmetros de paginação passados ao Prisma e meta retornada.
src/services/StackbyService.ts Normaliza sequence para número, ordena o retorno e força shape StackbyDataResponse.
src/services/StackbyService.test.ts Atualiza endpoint usado no teste de fetchStackbyData.
src/controllers/login/LoginController.test.ts Ajustes de formatação e alteração de roles em mocks.
Comments suppressed due to low confidence (1)

src/services/StackbyService.test.ts:35

  • Este teste agora mocka response.json() como { data: "ok" }, mas fetchStackbyData passou a assumir data.data como array para ordenar/mapear. Com o código atual, isso quebra ("ok".map is not a function) e a asserção final também não bate (o service retorna { data: orderedData }). Ajuste o mock para retornar uma estrutura compatível ({ data: [{ field: { sequence: "1", ... }, ... }] }) e atualize a expectativa para refletir o shape retornado.
		it("retorna dados em caso de sucesso", async () => {
			const mockJson = jest.fn().mockResolvedValue({ data: "ok" });
			(fetch as jest.Mock).mockResolvedValue({ json: mockJson, ok: true });
			const result = await service.fetchStackbyData("Themes", null);
			expect(fetch).toHaveBeenCalledWith(
				expect.stringContaining("http://fakeurl/Themes"),
				expect.objectContaining({
					headers: expect.objectContaining({
						"x-api-key": "fakekey",
					}),
					method: "GET",
				}),
			);
			expect(result).toEqual({ data: "ok" });
		});

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

take,
});

themes.forEach(t => console.log(t.title, t.sequence));
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remover este console.log/forEach (debug). Além de poluir logs em produção e impactar performance, pode vazar dados e interfere em ambientes serverless/observabilidade. Se precisar de logging, use o logger padrão do projeto com nível apropriado e behind feature flag.

Suggested change
themes.forEach(t => console.log(t.title, t.sequence));

Copilot uses AI. Check for mistakes.
},
);

return result as StackbyDataResponse;
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cacheOrFetch pode retornar string quando o valor vem do Redis (redis.get), mas aqui o retorno é forçado para StackbyDataResponse via type assertion. Isso pode causar runtime errors em quem consome o resultado (ex.: tentar acessar result.data). Sugestão: fazer JSON.parse quando typeof result === "string" (ou, melhor, ajustar cacheOrFetch para sempre retornar T, parseando o cache).

Suggested change
return result as StackbyDataResponse;
const parsedResult: StackbyDataResponse =
typeof result === "string" ? JSON.parse(result) : result;
return parsedResult;

Copilot uses AI. Check for mistakes.
Comment on lines +53 to +61
const orderedData = data.data
.map((t: any) => ({
...t,
field: {
...t.field,
sequence: Number(t.field.sequence),
},
}))
.sort((a: any, b: any) => a.field.sequence - b.field.sequence);
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A conversão Number(t.field.sequence) pode resultar em NaN se sequence vier vazio/undefined; nesse caso o .sort fica instável e a ordenação pode sair incorreta. Para garantir ordenação determinística, normalize para um número válido (ex.: fallback 0) e/ou trate itens sem field.sequence.

Copilot uses AI. Check for mistakes.
Comment on lines +1 to +4
import { ThemeService } from "./ThemeService";
import prisma from "../../../client";

jest.mock("../../../client", () => ({
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Este teste está usando imports sem sufixo .js (e.g. "./ThemeService", "../../../client"), enquanto o resto do repo (Jest ESM + moduleNameMapper) padroniza imports com .js nos arquivos TS. Sem o sufixo, a resolução pode falhar em ESM. Sugestão: alinhar os imports para "./ThemeService.js" e "../../../client.js" (e manter o mesmo path no jest.mock).

Suggested change
import { ThemeService } from "./ThemeService";
import prisma from "../../../client";
jest.mock("../../../client", () => ({
import { ThemeService } from "./ThemeService.js";
import prisma from "../../../client.js";
jest.mock("../../../client.js", () => ({

Copilot uses AI. Check for mistakes.
Comment on lines +5 to +42
__esModule: true,
default: {
theme: {
findMany: jest.fn(),
count: jest.fn(),
},
},
}));

describe("ThemeService - getThemes", () => {
let service: ThemeService;

beforeEach(() => {
service = new ThemeService();
jest.clearAllMocks();
});

it("deve chamar o prisma com os valores de paginação corretos", async () => {
const mockThemes = [{ id: "1", title: "Tema Teste" }];
(prisma.theme.findMany as jest.Mock).mockResolvedValue(mockThemes);
(prisma.theme.count as jest.Mock).mockResolvedValue(1);

const page = 1;
const limit = 10;

const result = await service.getThemes(undefined, page, limit);

expect(prisma.theme.findMany).toHaveBeenCalledWith(
expect.objectContaining({
skip: 0,
take: 10,
})
);

expect(result.meta.total).toBe(1);
expect(result.meta.totalPages).toBe(1);
expect(result.data).toEqual(mockThemes);
});
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O arquivo está formatado com espaços, mas o Biome do projeto está configurado para indentStyle: "tab" em src/**/*.ts. Isso tende a gerar ruído em diffs e falhas/ajustes automáticos de formatação. Rode o formatter (Biome) ou ajuste a indentação para tabs para manter consistência.

Suggested change
__esModule: true,
default: {
theme: {
findMany: jest.fn(),
count: jest.fn(),
},
},
}));
describe("ThemeService - getThemes", () => {
let service: ThemeService;
beforeEach(() => {
service = new ThemeService();
jest.clearAllMocks();
});
it("deve chamar o prisma com os valores de paginação corretos", async () => {
const mockThemes = [{ id: "1", title: "Tema Teste" }];
(prisma.theme.findMany as jest.Mock).mockResolvedValue(mockThemes);
(prisma.theme.count as jest.Mock).mockResolvedValue(1);
const page = 1;
const limit = 10;
const result = await service.getThemes(undefined, page, limit);
expect(prisma.theme.findMany).toHaveBeenCalledWith(
expect.objectContaining({
skip: 0,
take: 10,
})
);
expect(result.meta.total).toBe(1);
expect(result.meta.totalPages).toBe(1);
expect(result.data).toEqual(mockThemes);
});
__esModule: true,
default: {
theme: {
findMany: jest.fn(),
count: jest.fn(),
},
},
}));
describe("ThemeService - getThemes", () => {
let service: ThemeService;
beforeEach(() => {
service = new ThemeService();
jest.clearAllMocks();
});
it("deve chamar o prisma com os valores de paginação corretos", async () => {
const mockThemes = [{ id: "1", title: "Tema Teste" }];
(prisma.theme.findMany as jest.Mock).mockResolvedValue(mockThemes);
(prisma.theme.count as jest.Mock).mockResolvedValue(1);
const page = 1;
const limit = 10;
const result = await service.getThemes(undefined, page, limit);
expect(prisma.theme.findMany).toHaveBeenCalledWith(
expect.objectContaining({
skip: 0,
take: 10,
})
);
expect(result.meta.total).toBe(1);
expect(result.meta.totalPages).toBe(1);
expect(result.data).toEqual(mockThemes);
});

Copilot uses AI. Check for mistakes.
@@ -0,0 +1,68 @@
process.env.STACKBY_BASE_URL = "http://fakeurl";

import { pagination } from "./pagination";
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Este teste está usando import sem sufixo .js (import { pagination } from "./pagination"), enquanto o repo usa padrão ESM com imports em .js nos arquivos TS. Para evitar problemas de resolução e manter consistência, prefira "./pagination.js".

Suggested change
import { pagination } from "./pagination";
import { pagination } from "./pagination.js";

Copilot uses AI. Check for mistakes.
provider: 'google',
role: Role.VIEWER,
provider: "google",
role: Role.ADMIN,
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nos mocks deste teste o usuário é retornado com role: Role.ADMIN, mas TokenService.registerUser() não define role e o schema Prisma tem default VIEWER. Mesmo que o controller não use o campo hoje, manter o mock alinhado ao comportamento real evita confusão e falsos positivos em futuras validações baseadas em role.

Suggested change
role: Role.ADMIN,
role: Role.VIEWER,

Copilot uses AI. Check for mistakes.
Comment on lines +1 to +2
process.env.STACKBY_BASE_URL = "http://fakeurl";

Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

process.env.STACKBY_BASE_URL é setado aqui, mas esta suíte só testa pagination() e não depende de Stackby/env vars. Isso adiciona ruído e pode mascarar dependências reais de configuração em outros testes. Sugestão: remover essa linha ou manter apenas env vars estritamente necessárias para o teste.

Suggested change
process.env.STACKBY_BASE_URL = "http://fakeurl";

Copilot uses AI. Check for mistakes.
provider: 'github',
role: Role.VIEWER,
provider: "github",
role: Role.ADMIN,
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nos mocks deste teste o usuário criado é retornado com role: Role.ADMIN, mas TokenService.registerUser() não define role e o schema Prisma tem default VIEWER. Mesmo que o controller não use o campo hoje, manter o mock alinhado ao comportamento real evita confusão e falsos positivos em futuras validações baseadas em role.

Suggested change
role: Role.ADMIN,
role: Role.VIEWER,

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants