🎯 JavaScript - Partie 6

Spécialisations Professionnelles : TypeScript, Node.js, React, Tests, GraphQL, CI/CD

🚀 Niveau Spécialiste / Fullstack
0%

1. TypeScript Avancé TypeScript

Types avancés, generics, decorators, et utility types.

// Types avancés type User = { id: number; name: string; email: string; role: 'admin' | 'user' | 'guest'; createdAt: Date; }; // Partial, Pick, Omit (Utility Types) type UserPreview = Pick; type UserWithoutEmail = Omit; type PartialUser = Partial; // Generics avec contraintes interface Repository { findById(id: T['id']): Promise; save(entity: T): Promise; delete(id: T['id']): Promise; } // Decorators (expérimental) function LogMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const original = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`Appel de ${propertyKey} avec:`, args); return original.apply(this, args); }; return descriptor; }
📘 TypeScript en action (simulation)

2. Node.js & Backend Node.js

Serveurs HTTP, Express, File System, Streams, Event Emitter.

// Serveur Express basique const express = require('express'); const app = express(); app.use(express.json()); app.get('/api/users', (req, res) => { res.json({ users: ['Alice', 'Bob'] }); }); app.post('/api/users', (req, res) => { const { name } = req.body; res.status(201).json({ id: Date.now(), name }); }); // Streams pour fichiers volumineux const { createReadStream } = require('fs'); const { pipeline } = require('stream/promises'); async function streamLargeFile(filePath) { const stream = createReadStream(filePath); for await (const chunk of stream) { process.stdout.write(chunk); } } // Event Emitter personnalisé const EventEmitter = require('events'); class OrderService extends EventEmitter { createOrder(order) { this.emit('order:created', order); return order; } }
🖥️ Simulation API Node.js

3. React 18+ & Hooks React

Hooks avancés, Context, Performance, Patterns.

// Custom Hook function useLocalStorage(key: string, initialValue: T) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch { return initialValue; } }); const setValue = (value: T | ((val: T) => T)) => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.log(error); } }; return [storedValue, setValue]; } // useMemo et useCallback pour performance const expensiveComputation = useMemo(() => { return computeExpensiveValue(a, b); }, [a, b]); const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]); // Context API const ThemeContext = React.createContext({ theme: 'light', toggleTheme: () => {} });
⚛️ Simulation React

4. Tests Unitaires & E2E Jest/Cypress

Jest, Vitest, React Testing Library, Cypress, Playwright.

// Test Jest describe('Calculator', () => { test('adds 1 + 2 to equal 3', () => { expect(add(1, 2)).toBe(3); }); test('async test', async () => { const data = await fetchData(); expect(data).toHaveProperty('id'); }); test('mock function', () => { const mockFn = jest.fn(); mockFn('hello'); expect(mockFn).toHaveBeenCalledWith('hello'); }); }); // React Testing Library import { render, screen, fireEvent } from '@testing-library/react'; test('button increments counter', () => { render(); const button = screen.getByText('Increment'); fireEvent.click(button); expect(screen.getByText('Count: 1')).toBeInTheDocument(); }); // Cypress E2E describe('Login Flow', () => { it('should login successfully', () => { cy.visit('/login'); cy.get('[data-testid=email]').type('user@test.com'); cy.get('[data-testid=password]').type('password123'); cy.get('[data-testid=submit]').click(); cy.url().should('include', '/dashboard'); }); });
🧪 Exécuter des tests (simulation)

5. GraphQL & tRPC GraphQL

APIs modernes typées.

# Schéma GraphQL type User { id: ID! name: String! email: String! posts: [Post!]! } type Query { user(id: ID!): User users: [User!]! } type Mutation { createUser(name: String!, email: String!): User! } // Requête GraphQL const query = ` query GetUser($id: ID!) { user(id: $id) { name email posts { title } } } `; // tRPC - Type-safe RPC const appRouter = trpc.router({ getUser: trpc.procedure .input(z.object({ id: z.string() })) .query(async ({ input }) => { return db.user.findById(input.id); }), createUser: trpc.procedure .input(z.object({ name: z.string(), email: z.string() })) .mutation(async ({ input }) => { return db.user.create(input); }) });
🔮 Requêtes GraphQL (simulation)

6. CI/CD & GitHub Actions DevOps

Intégration et déploiement continus.

# .github/workflows/ci.yml name: CI/CD Pipeline on: push: branches: [main, develop] pull_request: branches: [main] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' - run: npm ci - run: npm run lint - run: npm run test - run: npm run build deploy: needs: test runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' steps: - name: Deploy to Vercel run: npx vercel --prod --token ${{ secrets.VERCEL_TOKEN }}
🔄 Simulation Pipeline CI/CD

7. Base de données MongoDB/PostgreSQL

ODM/ORM, requêtes, relations.

// MongoDB avec Mongoose const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, unique: true }, age: Number, createdAt: { type: Date, default: Date.now } }); const User = mongoose.model('User', userSchema); await User.create({ name: 'Alice', email: 'alice@test.com' }); // PostgreSQL avec Prisma const { PrismaClient } = require('@prisma/client'); const prisma = new PrismaClient(); const user = await prisma.user.create({ data: { name: 'Alice', email: 'alice@test.com', posts: { create: [{ title: 'Hello World' }] } }, include: { posts: true } });
🗄️ Simulations Base de données

8. State Management Redux/Zustand

Gestion d'état avancée.

// Zustand (moderne et simple) import { create } from 'zustand'; const useStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), reset: () => set({ count: 0 }) })); // Redux Toolkit import { createSlice, configureStore } from '@reduxjs/toolkit'; const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: (state) => { state.value += 1; }, decrement: (state) => { state.value -= 1; } } }); const store = configureStore({ reducer: counterSlice.reducer });
📦 State Management (Zustand simulé)
Compteur: 0

9. Next.js & Frameworks Fullstack Next.js

SSR, SSG, API Routes.

// pages/index.tsx - Next.js App Router export default async function HomePage() { const data = await fetch('https://api.example.com/data'); const posts = await data.json(); return (
{posts.map(post => (

{post.title}

{post.content}

))}
); } // API Route (app/api/users/route.ts) export async function GET(request: Request) { const users = await db.user.findMany(); return Response.json(users); } // Static Site Generation export async function generateStaticParams() { const posts = await getPosts(); return posts.map(post => ({ id: post.id.toString() })); }
🌐 Simulation Next.js

10. Mini-projet : TaskMaster API Fullstack

Application complète avec toutes les technologies vues.

✅ TaskMaster - Gestionnaire de tâches Fullstack

🏁 Récapitulatif - Spécialisations

🎯 Compétences acquises dans cette partie :

📘

TypeScript

Types avancés, Generics, Decorators

Union Types Utility Types
🖥️

Node.js

API REST, Streams, Event Emitter

Express Streams
⚛️

React

Hooks, Context, Performance

Custom Hooks Memo
🧪

Tests

Unitaires, E2E, Mocks

Jest Cypress
🔮

GraphQL

Queries, Mutations, tRPC

GraphQL tRPC
🔄

CI/CD

GitHub Actions, Déploiement

GitHub Actions Docker
🚀 Prochaines étapes possibles :
• Créer un projet fullstack complet avec Next.js + Prisma + PostgreSQL
• Contribuer à des projets Open Source
• Passer les certifications (AWS, Azure, MongoDB)
• Spécialisation mobile avec React Native
• Architecture Microservices avec Node.js