Lección 5 de 11
Copilot Chat y Code Reviews
Copilot Chat: Conversaciones con Código
Chat interactivo sobre tu código. Code reviewer 24/7.
Acceso
- Panel: Ctrl+Shift+I
- Inline: Ctrl+I
- Quick: @ para comandos
Comandos Slash
/explain
// Código complejo:
const memoFib = (() => {
const cache = new Map();
return function fib(n) {
if (n <= 1) return n;
if (cache.has(n)) return cache.get(n);
const result = fib(n-1) + fib(n-2);
cache.set(n, result);
return result;
};
})();
// Explica:
"IIFE + closure privado
Map cache memoización
Recursión O(n) optimizada"/fix
// Bug:
function getAverage(users) {
let total = 0;
for (let i = 0; i <= users.length; i++) { // <=
total += users[i].age;
}
return total / users.length;
}
// /fix arregla:
function getAverage(users) {
if (!users?.length) return 0;
let total = 0;
for (let i = 0; i < users.length; i++) { // <
total += users[i].age;
}
return total / users.length;
}
// "Off-by-one (<=) + validación vacío"/tests
// Función:
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
// /tests genera:
describe("validateEmail", () => {
it("valid emails", () => {
expect(validateEmail("[email protected]")).toBe(true);
expect(validateEmail("[email protected]")).toBe(true);
});
it("invalid emails", () => {
expect(validateEmail("invalid")).toBe(false);
expect(validateEmail("@example.com")).toBe(false);
expect(validateEmail("user@")).toBe(false);
});
it("edge cases", () => {
expect(validateEmail("")).toBe(false);
expect(validateEmail(null)).toBe(false);
});
});/doc
// Sin docs:
async function fetchWithRetry(url, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) return response;
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(r => setTimeout(r, 1000 * (i + 1)));
}
}
}
// /doc genera:
/**
* Fetch con retry automático
* @async
* @param {string} url - URL
* @param {RequestInit} options - Fetch options
* @param {number} [maxRetries=3] - Max intentos
* @returns {Promise}
* @throws {Error} Si todos fallan
* @example
* const data = await fetchWithRetry("/api/data");
* @description
* Retry con backoff exponencial: 1s, 2s, 3s
*/ Code Reviews
Review Completo
// Prompt:
"Revisa como senior developer.
Identifica:
1. Bugs
2. Performance
3. Mejoras
4. Security
5. Best practices
[código PR]"
// Respuesta:
"## Análisis
### 🐛 Bugs:
1. useEffect sin cleanup - memory leak
2. No valida antes de map() - error
### ⚡ Performance:
1. Re-renders - falta React.memo
2. Cálculo caro - usar useMemo
3. Inline onClick - useCallback
### ✨ Mejoras:
1. Custom hook para fetch
2. Error boundary
3. TypeScript strict
4. Loading skeleton
### 🔒 Security:
1. URL no sanitizada
2. XSS en dangerouslySetInnerHTML
[Código mejorado]"Security Review
"Analiza auth. Busca:
- SQL injection
- XSS, CSRF
- Passwords
- Input validation
[código]"
// Identifica:
"⚠️ CRÍTICO:
1. SQL Injection: Query concat
FIX: Prepared statements
2. Password: Plaintext
FIX: bcrypt 12+ rounds
3. CSRF: No token
FIX: CSRF middleware
4. Session: ID predecible
FIX: crypto.randomBytes(32)"Refactoring Interactivo
// Legacy:
var users = [];
function addUser(name, email) {
users.push({name: name, email: email});
}
function findUser(email) {
for (var i = 0; i < users.length; i++) {
if (users[i].email === email) return users[i];
}
return null;
}
// Chat: "Refactor ES6+ TypeScript"
// Resultado:
interface User {
name: string;
email: string;
}
const users: User[] = [];
const addUser = (name: string, email: string): void => {
users.push({ name, email });
};
const findUser = (email: string): User | undefined => {
return users.find(user => user.email === email);
};Workspace Commands
// @workspace pregunta sobre proyecto:
"@workspace ¿Dónde está auth?"
"@workspace ¿Componentes con useAuth?"
"@workspace Endpoints API"
"@workspace Tests para UserService"Debugging
// Error:
"TypeError: Cannot read property map of undefined
at UserList.tsx:23"
// Chat:
"Error: [copiar]
Código:
const UserList = ({ users }) => {
return {users.map(u => - {u.name}
)}
;
};
¿Problema y fix?"
// Respuesta:
"users undefined. CAUSAS:
1. Prop no pasada
2. Fetch no completo
3. Parent sin users
SOLUCIÓN:
const UserList = ({ users = [] }) => {
if (!users.length) return No users
;
return {users.map(...)}
;
};
BEST PRACTICE:
- Validar props
- Manejar: loading, empty, error
- TypeScript"Prompts Avanzados
Arquitectura
"Diseña notificaciones real-time:
- WebSockets
- Persistencia DB
- Push móvil
- Escalable 1M+ users
Incluye:
- Diagrama
- Stack tech
- Patrones
- Performance"Migration
"Migra JS → TypeScript:
1. Analiza archivo
2. Infiere tipos
3. Interfaces
4. Strict mode
5. Explica cambios
[código JS]"Performance Audit
"Audita performance React:
- Re-renders
- Memoización
- Computaciones caras
- Virtual scroll
- Lazy loading
[componente]"Tips Reviews
- Context first
- Aspectos específicos
- Incluye tests
- Security focus
- Performance check
Workflow
1. Código (autocompleta)
2. /tests
3. /doc
4. Chat: "Review"
5. Aplicar sugerencias
6. /fix bugs
7. Commit & PRCode reviewer 24/7. Usa constantemente para calidad.