From a6f5a147fcfeddcda0afa0777e6c3072d94e6f05 Mon Sep 17 00:00:00 2001 From: Dionei Bianchati Date: Wed, 3 Jun 2026 08:21:33 -0300 Subject: [PATCH 01/11] refactor: rename Difficulty type to seniority levels (junior/pleno/senior/especialista) --- src/lib/__tests__/content.test.ts | 2 +- src/lib/content.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/lib/__tests__/content.test.ts b/src/lib/__tests__/content.test.ts index d87d851..5ad8e24 100644 --- a/src/lib/__tests__/content.test.ts +++ b/src/lib/__tests__/content.test.ts @@ -21,7 +21,7 @@ describe('buildQuestionMeta', () => { category: 'frontend', subcategory: 'javascript', tags: ['es6'], - difficulty: 'beginner', + difficulty: 'junior', lang: 'en', } const meta = buildQuestionMeta('let-const-var', fm) diff --git a/src/lib/content.ts b/src/lib/content.ts index f5235ec..0a5afaf 100644 --- a/src/lib/content.ts +++ b/src/lib/content.ts @@ -7,7 +7,7 @@ import remarkRehype from 'remark-rehype' import rehypeShiki from '@shikijs/rehype' import rehypeStringify from 'rehype-stringify' -export type Difficulty = 'beginner' | 'intermediate' | 'advanced' +export type Difficulty = 'junior' | 'pleno' | 'senior' | 'especialista' export type QuestionMeta = { slug: string @@ -69,7 +69,7 @@ export function buildQuestionMeta( category: fm.category as string, subcategory: fm.subcategory as string, tags: (fm.tags as string[]) ?? [], - difficulty: (fm.difficulty as Difficulty) ?? 'intermediate', + difficulty: (fm.difficulty as Difficulty) ?? 'pleno', lang: fm.lang as string, path: `${fm.category}/${fm.subcategory}/${slug}`, quickAnswer: stripMarkdown(extractSection(rawContent, 'Quick Answer')), From 4138f4f9a54a80489c9a64d241cb338fcf3478c4 Mon Sep 17 00:00:00 2001 From: Dionei Bianchati Date: Wed, 3 Jun 2026 08:22:37 -0300 Subject: [PATCH 02/11] refactor: update validate-content script with new seniority difficulty levels --- scripts/validate-content.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/validate-content.mjs b/scripts/validate-content.mjs index eb35d2a..f8281a8 100644 --- a/scripts/validate-content.mjs +++ b/scripts/validate-content.mjs @@ -5,7 +5,7 @@ import { fileURLToPath } from 'url' const __dirname = path.dirname(fileURLToPath(import.meta.url)) const CONTENT_DIR = path.join(__dirname, '..', 'src', 'content') const REQUIRED_FIELDS = ['title', 'category', 'subcategory', 'tags', 'difficulty', 'lang'] -const VALID_DIFFICULTIES = ['beginner', 'intermediate', 'advanced'] +const VALID_DIFFICULTIES = ['junior', 'pleno', 'senior', 'especialista'] const VALID_LANGS = ['en', 'pt'] const REQUIRED_SECTIONS = ['## Full Answer', '## Quick Answer', '## Flashcard'] From e71920676dbb594cc1cc90410a85558c7982ee62 Mon Sep 17 00:00:00 2001 From: Dionei Bianchati Date: Wed, 3 Jun 2026 08:23:08 -0300 Subject: [PATCH 03/11] feat: add updates i18n keys and rename difficulty translations to seniority levels --- src/messages/en.json | 13 ++++++++----- src/messages/pt.json | 13 ++++++++----- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/messages/en.json b/src/messages/en.json index 93f2332..d552e2c 100644 --- a/src/messages/en.json +++ b/src/messages/en.json @@ -5,7 +5,8 @@ "resume": "Resume", "contribute": "Contribute", "support": "Support Us", - "about": "About" + "about": "About", + "updates": "Updates" }, "home": { "title": "CodeQuestions", @@ -64,9 +65,10 @@ "gotIt": "Got it!", "needReview": "Need more study", "difficulty": { - "beginner": "Beginner", - "intermediate": "Intermediate", - "advanced": "Advanced" + "junior": "Junior", + "pleno": "Mid-level", + "senior": "Senior", + "especialista": "Specialist" } }, "progress": { @@ -80,7 +82,8 @@ "contribute": "How to Contribute", "contact": "Contact", "support": "Support the Project", - "storytelling": "StoryTelling Guide" + "storytelling": "StoryTelling Guide", + "updates": "Updates" }, "footer": { "openSource": "Open source on GitHub", diff --git a/src/messages/pt.json b/src/messages/pt.json index db56fe9..b75c6d1 100644 --- a/src/messages/pt.json +++ b/src/messages/pt.json @@ -5,7 +5,8 @@ "resume": "Currículo", "contribute": "Contribuir", "support": "Apoie", - "about": "Sobre" + "about": "Sobre", + "updates": "Atualizações" }, "home": { "title": "CodeQuestions", @@ -64,9 +65,10 @@ "gotIt": "Sei!", "needReview": "Preciso estudar", "difficulty": { - "beginner": "Iniciante", - "intermediate": "Intermediário", - "advanced": "Avançado" + "junior": "Júnior", + "pleno": "Pleno", + "senior": "Sênior", + "especialista": "Especialista" } }, "progress": { @@ -80,7 +82,8 @@ "contribute": "Como Contribuir", "contact": "Contato", "support": "Apoie o Projeto", - "storytelling": "Guia de StoryTelling" + "storytelling": "Guia de StoryTelling", + "updates": "Atualizações" }, "footer": { "openSource": "Open source no GitHub", From be8542f03ef87f2891459d6fb83093fc658f358e Mon Sep 17 00:00:00 2001 From: Dionei Bianchati Date: Wed, 3 Jun 2026 08:39:06 -0300 Subject: [PATCH 04/11] feat: update all question difficulty frontmatter to seniority levels --- .../en/architecture/solid/solid-principles.md | 144 +++++------ .../en/backend/general/sql-vs-nosql.md | 120 +++++----- src/content/en/backend/node/event-loop.md | 66 ++--- src/content/en/devops/docker/docker-basics.md | 110 ++++----- src/content/en/frontend/css/box-model.md | 104 ++++---- .../frontend/javascript/event-delegation.md | 62 ++--- .../en/frontend/javascript/let-const-var.md | 78 +++--- .../react/controlled-vs-uncontrolled.md | 136 +++++------ src/content/en/frontend/react/hooks.md | 72 +++--- .../en/frontend/react/what-is-a-component.md | 102 ++++---- src/content/en/security/web/xss.md | 108 ++++----- .../soft-skills/hr/tell-me-about-yourself.md | 90 +++---- .../arquitetura-escalavel.md | 78 +++--- .../pt/architecture/solid/solid-principles.md | 140 +++++------ src/content/pt/backend/general/graphql.md | 198 +++++++-------- src/content/pt/backend/general/o-que-e-api.md | 146 +++++------ src/content/pt/backend/general/rest.md | 112 ++++----- src/content/pt/backend/node/middlewares.md | 226 +++++++++--------- .../devops/containers/diferenca-docker-k8s.md | 64 ++--- .../pt/devops/containers/o-que-e-docker.md | 56 ++--- .../pt/devops/containers/o-que-e-k8s.md | 60 ++--- .../quando-usar-containers-em-vez-de-vm.md | 70 +++--- .../frontend/accessibility/acessibilidade.md | 206 ++++++++-------- src/content/pt/frontend/css/box-model.md | 104 ++++---- .../pt/frontend/javascript/let-const-var.md | 78 +++--- .../performance/otimizacao-carregamento.md | 180 +++++++------- .../pt/frontend/react/ciclo-de-vida.md | 148 ++++++------ .../pt/frontend/react/context-api-vs-redux.md | 204 ++++++++-------- .../pt/frontend/react/o-que-e-estado.md | 112 ++++----- .../frontend/react/o-que-e-um-componente.md | 102 ++++---- .../frontend/react/o-que-sao-propriedades.md | 118 ++++----- .../pt/frontend/react/react-vs-next.md | 104 ++++---- .../pt/frontend/react/ssr-ssg-isr-nextjs.md | 222 ++++++++--------- .../pt/frontend/react/usememo-usecallback.md | 208 ++++++++-------- .../pt/soft-skills/hr/fale-sobre-voce.md | 90 +++---- 35 files changed, 2109 insertions(+), 2109 deletions(-) diff --git a/src/content/en/architecture/solid/solid-principles.md b/src/content/en/architecture/solid/solid-principles.md index 343d763..c8f7930 100644 --- a/src/content/en/architecture/solid/solid-principles.md +++ b/src/content/en/architecture/solid/solid-principles.md @@ -1,72 +1,72 @@ ---- -title: "What are the SOLID principles?" -category: architecture -subcategory: solid -tags: [solid, oop, design-principles, clean-code] -difficulty: intermediate -lang: en ---- - -## Full Answer - -SOLID is an acronym for five object-oriented design principles that make software easier to understand, change, and extend. - -**S — Single Responsibility Principle** -A class should have one, and only one, reason to change. In practice: if you can describe a class with "and" it probably has too many responsibilities. - -```typescript -// Bad: one class does parsing AND persistence -class UserService { - parseCSV(data: string) { ... } - saveToDatabase(user: User) { ... } -} - -// Good: split responsibilities -class UserParser { parseCSV(data: string) { ... } } -class UserRepository { save(user: User) { ... } } -``` - -**O — Open/Closed Principle** -Software entities should be open for extension but closed for modification. Add new behavior by adding new code, not changing existing code. - -**L — Liskov Substitution Principle** -Subtypes must be substitutable for their base types without breaking behavior. If `Square extends Rectangle` but overriding `setWidth` also changes height, it violates LSP — code expecting a `Rectangle` will break. - -**I — Interface Segregation Principle** -No client should be forced to depend on methods it does not use. Prefer small, focused interfaces over large fat ones. - -```typescript -// Bad: one large interface -interface Worker { work(): void; eat(): void; sleep(): void } - -// Good: split by role -interface Workable { work(): void } -interface Restable { eat(): void; sleep(): void } -``` - -**D — Dependency Inversion Principle** -High-level modules should not depend on low-level modules. Both should depend on abstractions. Concretely: depend on interfaces, inject implementations. - -```typescript -// Bad: high-level depends directly on low-level -class OrderService { - private db = new PostgresDatabase() -} - -// Good: depends on abstraction, implementation injected -class OrderService { - constructor(private db: Database) {} -} -``` - -These principles work together: SRP keeps classes focused, OCP enables extension, LSP ensures safe inheritance, ISP prevents bloated interfaces, DIP enables flexibility through abstractions. - -## Quick Answer - -SOLID: **S**ingle Responsibility (one reason to change), **O**pen/Closed (extend without modifying), **L**iskov Substitution (subtypes must be replaceable), **I**nterface Segregation (small focused interfaces), **D**ependency Inversion (depend on abstractions, inject implementations). - -## Flashcard - -**Q:** What does each letter in SOLID stand for? - -**A:** S — Single Responsibility (one reason to change). O — Open/Closed (open for extension, closed for modification). L — Liskov Substitution (subtypes replaceable for base types). I — Interface Segregation (small focused interfaces). D — Dependency Inversion (depend on abstractions, not concretions). +--- +title: "What are the SOLID principles?" +category: architecture +subcategory: solid +tags: [solid, oop, design-principles, clean-code] +difficulty: pleno +lang: en +--- + +## Full Answer + +SOLID is an acronym for five object-oriented design principles that make software easier to understand, change, and extend. + +**S — Single Responsibility Principle** +A class should have one, and only one, reason to change. In practice: if you can describe a class with "and" it probably has too many responsibilities. + +```typescript +// Bad: one class does parsing AND persistence +class UserService { + parseCSV(data: string) { ... } + saveToDatabase(user: User) { ... } +} + +// Good: split responsibilities +class UserParser { parseCSV(data: string) { ... } } +class UserRepository { save(user: User) { ... } } +``` + +**O — Open/Closed Principle** +Software entities should be open for extension but closed for modification. Add new behavior by adding new code, not changing existing code. + +**L — Liskov Substitution Principle** +Subtypes must be substitutable for their base types without breaking behavior. If `Square extends Rectangle` but overriding `setWidth` also changes height, it violates LSP — code expecting a `Rectangle` will break. + +**I — Interface Segregation Principle** +No client should be forced to depend on methods it does not use. Prefer small, focused interfaces over large fat ones. + +```typescript +// Bad: one large interface +interface Worker { work(): void; eat(): void; sleep(): void } + +// Good: split by role +interface Workable { work(): void } +interface Restable { eat(): void; sleep(): void } +``` + +**D — Dependency Inversion Principle** +High-level modules should not depend on low-level modules. Both should depend on abstractions. Concretely: depend on interfaces, inject implementations. + +```typescript +// Bad: high-level depends directly on low-level +class OrderService { + private db = new PostgresDatabase() +} + +// Good: depends on abstraction, implementation injected +class OrderService { + constructor(private db: Database) {} +} +``` + +These principles work together: SRP keeps classes focused, OCP enables extension, LSP ensures safe inheritance, ISP prevents bloated interfaces, DIP enables flexibility through abstractions. + +## Quick Answer + +SOLID: **S**ingle Responsibility (one reason to change), **O**pen/Closed (extend without modifying), **L**iskov Substitution (subtypes must be replaceable), **I**nterface Segregation (small focused interfaces), **D**ependency Inversion (depend on abstractions, inject implementations). + +## Flashcard + +**Q:** What does each letter in SOLID stand for? + +**A:** S — Single Responsibility (one reason to change). O — Open/Closed (open for extension, closed for modification). L — Liskov Substitution (subtypes replaceable for base types). I — Interface Segregation (small focused interfaces). D — Dependency Inversion (depend on abstractions, not concretions). diff --git a/src/content/en/backend/general/sql-vs-nosql.md b/src/content/en/backend/general/sql-vs-nosql.md index ed1b162..0050dd5 100644 --- a/src/content/en/backend/general/sql-vs-nosql.md +++ b/src/content/en/backend/general/sql-vs-nosql.md @@ -1,60 +1,60 @@ ---- -title: "What is the difference between SQL and NoSQL databases?" -category: backend -subcategory: general -tags: [database, sql, nosql, relational, mongodb, postgres] -difficulty: intermediate -lang: en ---- - -## Full Answer - -SQL and NoSQL databases take fundamentally different approaches to storing and querying data. - -**SQL (Relational databases)** - -Data is stored in tables with rows and columns. The schema is defined upfront and enforced — every row must conform to the table structure. Relationships between tables are expressed with foreign keys and joined at query time. - -Examples: PostgreSQL, MySQL, SQLite, SQL Server. - -Strengths: -- ACID transactions — atomicity, consistency, isolation, durability -- Powerful joins and aggregations with a standardized query language -- Well-suited when data has a clear, stable structure and relationships matter - -**NoSQL (Non-relational databases)** - -"NoSQL" covers several different storage models: -- **Document stores** (MongoDB, Firestore) — store JSON-like documents, flexible schema -- **Key-value stores** (Redis, DynamoDB) — fast lookup by key, great for caching and sessions -- **Wide-column stores** (Cassandra) — optimized for high write throughput and time-series data -- **Graph databases** (Neo4j) — nodes and edges, optimized for relationship queries - -Strengths: -- Flexible or schema-less — easy to evolve data shape over time -- Horizontal scaling is simpler for most NoSQL types -- High write throughput in specialized engines - -**Choosing between them:** - -Use SQL when: -- Data is structured and relational (orders → customers → products) -- You need strong consistency and complex transactions -- You have reporting or analytics requirements - -Use NoSQL when: -- Schema changes frequently or is unknown upfront -- You need high write throughput at scale -- Your data model maps naturally to documents, key-value pairs, or graphs - -Most modern applications use both — a relational DB for core entities and a NoSQL store for caching, logs, or search. - -## Quick Answer - -SQL stores data in tables with a fixed schema and supports ACID transactions and joins. NoSQL covers document, key-value, wide-column, and graph databases — flexible schema, designed for horizontal scale. Use SQL for relational structured data with complex queries; NoSQL for flexible schemas and high throughput. - -## Flashcard - -**Q:** What are the main trade-offs between SQL and NoSQL databases? - -**A:** SQL: structured schema, ACID transactions, powerful joins — great for relational data. NoSQL: flexible schema, horizontal scale, high throughput — great for documents, key-value, or graph data. Most systems use both. +--- +title: "What is the difference between SQL and NoSQL databases?" +category: backend +subcategory: general +tags: [database, sql, nosql, relational, mongodb, postgres] +difficulty: pleno +lang: en +--- + +## Full Answer + +SQL and NoSQL databases take fundamentally different approaches to storing and querying data. + +**SQL (Relational databases)** + +Data is stored in tables with rows and columns. The schema is defined upfront and enforced — every row must conform to the table structure. Relationships between tables are expressed with foreign keys and joined at query time. + +Examples: PostgreSQL, MySQL, SQLite, SQL Server. + +Strengths: +- ACID transactions — atomicity, consistency, isolation, durability +- Powerful joins and aggregations with a standardized query language +- Well-suited when data has a clear, stable structure and relationships matter + +**NoSQL (Non-relational databases)** + +"NoSQL" covers several different storage models: +- **Document stores** (MongoDB, Firestore) — store JSON-like documents, flexible schema +- **Key-value stores** (Redis, DynamoDB) — fast lookup by key, great for caching and sessions +- **Wide-column stores** (Cassandra) — optimized for high write throughput and time-series data +- **Graph databases** (Neo4j) — nodes and edges, optimized for relationship queries + +Strengths: +- Flexible or schema-less — easy to evolve data shape over time +- Horizontal scaling is simpler for most NoSQL types +- High write throughput in specialized engines + +**Choosing between them:** + +Use SQL when: +- Data is structured and relational (orders → customers → products) +- You need strong consistency and complex transactions +- You have reporting or analytics requirements + +Use NoSQL when: +- Schema changes frequently or is unknown upfront +- You need high write throughput at scale +- Your data model maps naturally to documents, key-value pairs, or graphs + +Most modern applications use both — a relational DB for core entities and a NoSQL store for caching, logs, or search. + +## Quick Answer + +SQL stores data in tables with a fixed schema and supports ACID transactions and joins. NoSQL covers document, key-value, wide-column, and graph databases — flexible schema, designed for horizontal scale. Use SQL for relational structured data with complex queries; NoSQL for flexible schemas and high throughput. + +## Flashcard + +**Q:** What are the main trade-offs between SQL and NoSQL databases? + +**A:** SQL: structured schema, ACID transactions, powerful joins — great for relational data. NoSQL: flexible schema, horizontal scale, high throughput — great for documents, key-value, or graph data. Most systems use both. diff --git a/src/content/en/backend/node/event-loop.md b/src/content/en/backend/node/event-loop.md index 9c00f57..eae5bd6 100644 --- a/src/content/en/backend/node/event-loop.md +++ b/src/content/en/backend/node/event-loop.md @@ -1,33 +1,33 @@ ---- -title: "How does the Node.js event loop work?" -category: backend -subcategory: node -tags: [event-loop, async, non-blocking, libuv] -difficulty: intermediate -lang: en ---- - -## Full Answer - -The Node.js event loop allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded. It offloads operations to the system kernel or libuv thread pool and resumes execution when they complete. - -**Phases of the event loop (in order):** - -1. **timers** — executes `setTimeout` and `setInterval` callbacks -2. **pending callbacks** — I/O callbacks deferred from the previous iteration -3. **idle, prepare** — internal use only -4. **poll** — retrieves new I/O events; blocks here if queue is empty -5. **check** — executes `setImmediate` callbacks -6. **close callbacks** — handles `close` events - -Between each phase, Node.js drains `process.nextTick` and Promise microtask queues completely. - -## Quick Answer - -The event loop processes callbacks across 6 phases, draining microtasks (`nextTick`, Promises) between each. It allows Node.js to handle concurrent I/O without threads by deferring work to the OS/libuv. - -## Flashcard - -**Q:** What is the execution order of `process.nextTick`, `Promise.then`, `setImmediate`, and `setTimeout(fn, 0)`? - -**A:** `process.nextTick` → `Promise.then` (microtasks, before next phase) → `setTimeout(fn, 0)` (timers phase) → `setImmediate` (check phase, after I/O poll). +--- +title: "How does the Node.js event loop work?" +category: backend +subcategory: node +tags: [event-loop, async, non-blocking, libuv] +difficulty: pleno +lang: en +--- + +## Full Answer + +The Node.js event loop allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded. It offloads operations to the system kernel or libuv thread pool and resumes execution when they complete. + +**Phases of the event loop (in order):** + +1. **timers** — executes `setTimeout` and `setInterval` callbacks +2. **pending callbacks** — I/O callbacks deferred from the previous iteration +3. **idle, prepare** — internal use only +4. **poll** — retrieves new I/O events; blocks here if queue is empty +5. **check** — executes `setImmediate` callbacks +6. **close callbacks** — handles `close` events + +Between each phase, Node.js drains `process.nextTick` and Promise microtask queues completely. + +## Quick Answer + +The event loop processes callbacks across 6 phases, draining microtasks (`nextTick`, Promises) between each. It allows Node.js to handle concurrent I/O without threads by deferring work to the OS/libuv. + +## Flashcard + +**Q:** What is the execution order of `process.nextTick`, `Promise.then`, `setImmediate`, and `setTimeout(fn, 0)`? + +**A:** `process.nextTick` → `Promise.then` (microtasks, before next phase) → `setTimeout(fn, 0)` (timers phase) → `setImmediate` (check phase, after I/O poll). diff --git a/src/content/en/devops/docker/docker-basics.md b/src/content/en/devops/docker/docker-basics.md index d37c30e..4e27aae 100644 --- a/src/content/en/devops/docker/docker-basics.md +++ b/src/content/en/devops/docker/docker-basics.md @@ -1,55 +1,55 @@ ---- -title: "What is Docker and why is it used?" -category: devops -subcategory: docker -tags: [docker, containers, devops, deployment, images] -difficulty: beginner -lang: en ---- - -## Full Answer - -**Docker** is a platform for building, running, and shipping applications in **containers** — lightweight, isolated environments that package the application code together with all its dependencies (runtime, libraries, config). - -**The core problem Docker solves** - -"It works on my machine" — Docker eliminates environment inconsistencies by making the environment part of the artifact. The same container image runs identically on a developer's laptop, a CI server, and production. - -**Key concepts** - -- **Image** — a read-only template (snapshot) of a file system with your app and dependencies. Built from a `Dockerfile`. -- **Container** — a running instance of an image. Isolated from the host and other containers via Linux namespaces and cgroups. -- **Dockerfile** — a text file with instructions for building an image: - -```dockerfile -FROM node:20-alpine -WORKDIR /app -COPY package*.json ./ -RUN npm ci -COPY . . -RUN npm run build -CMD ["node", "dist/index.js"] -``` - -- **Registry** — a repository for storing and sharing images. Docker Hub is the public default; AWS ECR, Google Artifact Registry, and GitHub Container Registry are common private options. -- **Docker Compose** — a tool to define and run multi-container applications (e.g., app + database + cache) with a single `docker-compose.yml`. - -**Containers vs. VMs** - -Virtual machines virtualize hardware and run a full OS per VM — heavy (GBs). Containers share the host OS kernel — lightweight (MBs), start in seconds, and run thousands per host. - -**Common use cases:** -- Consistent dev environments across the team -- CI/CD pipelines that build and test in isolation -- Microservices deployment -- Running services locally without installing them (postgres, redis, etc.) - -## Quick Answer - -Docker packages applications in containers — isolated environments with all dependencies baked in. This guarantees the same behavior everywhere (dev, CI, prod). Key objects: Image (template), Container (running instance), Dockerfile (build recipe), Docker Compose (multi-container orchestration). - -## Flashcard - -**Q:** What is the difference between a Docker image and a Docker container? - -**A:** An image is a read-only snapshot of the app and its dependencies, built from a Dockerfile. A container is a running instance of an image — isolated, lightweight, and disposable. +--- +title: "What is Docker and why is it used?" +category: devops +subcategory: docker +tags: [docker, containers, devops, deployment, images] +difficulty: junior +lang: en +--- + +## Full Answer + +**Docker** is a platform for building, running, and shipping applications in **containers** — lightweight, isolated environments that package the application code together with all its dependencies (runtime, libraries, config). + +**The core problem Docker solves** + +"It works on my machine" — Docker eliminates environment inconsistencies by making the environment part of the artifact. The same container image runs identically on a developer's laptop, a CI server, and production. + +**Key concepts** + +- **Image** — a read-only template (snapshot) of a file system with your app and dependencies. Built from a `Dockerfile`. +- **Container** — a running instance of an image. Isolated from the host and other containers via Linux namespaces and cgroups. +- **Dockerfile** — a text file with instructions for building an image: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci +COPY . . +RUN npm run build +CMD ["node", "dist/index.js"] +``` + +- **Registry** — a repository for storing and sharing images. Docker Hub is the public default; AWS ECR, Google Artifact Registry, and GitHub Container Registry are common private options. +- **Docker Compose** — a tool to define and run multi-container applications (e.g., app + database + cache) with a single `docker-compose.yml`. + +**Containers vs. VMs** + +Virtual machines virtualize hardware and run a full OS per VM — heavy (GBs). Containers share the host OS kernel — lightweight (MBs), start in seconds, and run thousands per host. + +**Common use cases:** +- Consistent dev environments across the team +- CI/CD pipelines that build and test in isolation +- Microservices deployment +- Running services locally without installing them (postgres, redis, etc.) + +## Quick Answer + +Docker packages applications in containers — isolated environments with all dependencies baked in. This guarantees the same behavior everywhere (dev, CI, prod). Key objects: Image (template), Container (running instance), Dockerfile (build recipe), Docker Compose (multi-container orchestration). + +## Flashcard + +**Q:** What is the difference between a Docker image and a Docker container? + +**A:** An image is a read-only snapshot of the app and its dependencies, built from a Dockerfile. A container is a running instance of an image — isolated, lightweight, and disposable. diff --git a/src/content/en/frontend/css/box-model.md b/src/content/en/frontend/css/box-model.md index 1e1d26d..b869a2a 100644 --- a/src/content/en/frontend/css/box-model.md +++ b/src/content/en/frontend/css/box-model.md @@ -1,52 +1,52 @@ ---- -title: "What is the CSS Box Model?" -category: frontend -subcategory: css -tags: [css, box-model, layout, margin, padding] -difficulty: beginner -lang: en ---- - -## Full Answer - -The CSS Box Model describes how every HTML element is rendered as a rectangular box composed of four layers, from inside out: - -1. **Content** — the actual text, image, or other content. Width and height apply here by default. -2. **Padding** — transparent space between the content and the border. Padding is inside the element, so it inherits the element's background color. -3. **Border** — a line wrapping the padding and content. Can have width, style, and color. -4. **Margin** — transparent space outside the border. Margins of adjacent elements can collapse into each other (margin collapsing). - -**Box Sizing** - -By default (`box-sizing: content-box`), `width` and `height` only apply to the content box — padding and border are added on top, making the actual rendered size larger than you specified. - -With `box-sizing: border-box`, `width` and `height` include padding and border. This is almost always more intuitive and is used by default in most CSS resets: - -```css -*, *::before, *::after { - box-sizing: border-box; -} -``` - -**Example:** - -```css -.box { - width: 200px; - padding: 20px; - border: 2px solid black; - margin: 10px; -} -/* content-box: rendered width = 200 + 40 + 4 = 244px */ -/* border-box: rendered width = 200px (padding and border fit inside) */ -``` - -## Quick Answer - -The Box Model is the four layers around every element: content, padding, border, margin. By default `width` only sets the content area; with `box-sizing: border-box` it includes padding and border, which is almost always preferred. - -## Flashcard - -**Q:** What are the four layers of the CSS Box Model, from inside out? - -**A:** Content → Padding → Border → Margin. With `box-sizing: border-box`, `width`/`height` include padding and border; with `content-box` (default) they only cover content. +--- +title: "What is the CSS Box Model?" +category: frontend +subcategory: css +tags: [css, box-model, layout, margin, padding] +difficulty: junior +lang: en +--- + +## Full Answer + +The CSS Box Model describes how every HTML element is rendered as a rectangular box composed of four layers, from inside out: + +1. **Content** — the actual text, image, or other content. Width and height apply here by default. +2. **Padding** — transparent space between the content and the border. Padding is inside the element, so it inherits the element's background color. +3. **Border** — a line wrapping the padding and content. Can have width, style, and color. +4. **Margin** — transparent space outside the border. Margins of adjacent elements can collapse into each other (margin collapsing). + +**Box Sizing** + +By default (`box-sizing: content-box`), `width` and `height` only apply to the content box — padding and border are added on top, making the actual rendered size larger than you specified. + +With `box-sizing: border-box`, `width` and `height` include padding and border. This is almost always more intuitive and is used by default in most CSS resets: + +```css +*, *::before, *::after { + box-sizing: border-box; +} +``` + +**Example:** + +```css +.box { + width: 200px; + padding: 20px; + border: 2px solid black; + margin: 10px; +} +/* content-box: rendered width = 200 + 40 + 4 = 244px */ +/* border-box: rendered width = 200px (padding and border fit inside) */ +``` + +## Quick Answer + +The Box Model is the four layers around every element: content, padding, border, margin. By default `width` only sets the content area; with `box-sizing: border-box` it includes padding and border, which is almost always preferred. + +## Flashcard + +**Q:** What are the four layers of the CSS Box Model, from inside out? + +**A:** Content → Padding → Border → Margin. With `box-sizing: border-box`, `width`/`height` include padding and border; with `content-box` (default) they only cover content. diff --git a/src/content/en/frontend/javascript/event-delegation.md b/src/content/en/frontend/javascript/event-delegation.md index c1474b9..b98c05d 100644 --- a/src/content/en/frontend/javascript/event-delegation.md +++ b/src/content/en/frontend/javascript/event-delegation.md @@ -1,31 +1,31 @@ ---- -title: "What is event delegation?" -category: frontend -subcategory: javascript -tags: [dom, events, performance, bubbling] -difficulty: intermediate -lang: en ---- - -## Full Answer - -Event delegation is a pattern where a single event listener is placed on a **parent element** to handle events triggered by its **child elements**, instead of attaching individual listeners to each child. - -It works because of **event bubbling**: when an event fires on a child, it bubbles up through the DOM to parent elements. The parent listener can inspect `event.target` to determine which child triggered the event. - -**Benefits:** -- Fewer event listeners → less memory usage -- Works for dynamically added children (no need to reattach listeners) -- Simpler cleanup (remove one listener instead of many) - -**When not to use it:** events that don't bubble (e.g., `focus`, `blur`) require `focusin`/`focusout` instead, or `addEventListener` with `useCapture: true`. - -## Quick Answer - -Event delegation attaches one listener to a parent element that handles events from its children via bubbling, checking `event.target` to identify the source. It reduces memory usage and works for dynamically added elements. - -## Flashcard - -**Q:** What is event delegation and why is it useful? - -**A:** Placing a single event listener on a parent to handle events from children via bubbling. Useful because it reduces listener count, saves memory, and automatically handles dynamically added children. +--- +title: "What is event delegation?" +category: frontend +subcategory: javascript +tags: [dom, events, performance, bubbling] +difficulty: pleno +lang: en +--- + +## Full Answer + +Event delegation is a pattern where a single event listener is placed on a **parent element** to handle events triggered by its **child elements**, instead of attaching individual listeners to each child. + +It works because of **event bubbling**: when an event fires on a child, it bubbles up through the DOM to parent elements. The parent listener can inspect `event.target` to determine which child triggered the event. + +**Benefits:** +- Fewer event listeners → less memory usage +- Works for dynamically added children (no need to reattach listeners) +- Simpler cleanup (remove one listener instead of many) + +**When not to use it:** events that don't bubble (e.g., `focus`, `blur`) require `focusin`/`focusout` instead, or `addEventListener` with `useCapture: true`. + +## Quick Answer + +Event delegation attaches one listener to a parent element that handles events from its children via bubbling, checking `event.target` to identify the source. It reduces memory usage and works for dynamically added elements. + +## Flashcard + +**Q:** What is event delegation and why is it useful? + +**A:** Placing a single event listener on a parent to handle events from children via bubbling. Useful because it reduces listener count, saves memory, and automatically handles dynamically added children. diff --git a/src/content/en/frontend/javascript/let-const-var.md b/src/content/en/frontend/javascript/let-const-var.md index b0f504a..906f037 100644 --- a/src/content/en/frontend/javascript/let-const-var.md +++ b/src/content/en/frontend/javascript/let-const-var.md @@ -1,39 +1,39 @@ ---- -title: "What is the difference between let, const, and var?" -category: frontend -subcategory: javascript -tags: [es6, scope, hoisting, variables] -difficulty: beginner -lang: en ---- - -## Full Answer - -JavaScript has three ways to declare variables: `var`, `let`, and `const`. They differ in scope, hoisting behavior, and mutability. - -**var** -- Function-scoped (or globally scoped if declared outside a function) -- Hoisted to the top of its scope and initialized as `undefined` -- Can be redeclared and reassigned - -**let** -- Block-scoped (limited to the `{}` block it is declared in) -- Hoisted but NOT initialized — accessing it before declaration throws a `ReferenceError` (Temporal Dead Zone) -- Cannot be redeclared in the same scope, but can be reassigned - -**const** -- Block-scoped, same as `let` -- Cannot be redeclared or reassigned — the binding is constant -- Objects and arrays declared with `const` are still mutable (their contents can change) - -**Rule of thumb:** prefer `const` by default, use `let` when you need to reassign, avoid `var`. - -## Quick Answer - -`var` is function-scoped and hoisted as `undefined`; `let` and `const` are block-scoped with a Temporal Dead Zone. `const` prevents reassignment; `let` allows it. Prefer `const` by default. - -## Flashcard - -**Q:** What are the three key differences between `var`, `let`, and `const`? - -**A:** 1) Scope — `var` is function-scoped, `let`/`const` are block-scoped. 2) Hoisting — `var` initializes as `undefined`, `let`/`const` enter the Temporal Dead Zone. 3) Reassignment — `const` forbids it, `let` and `var` allow it. +--- +title: "What is the difference between let, const, and var?" +category: frontend +subcategory: javascript +tags: [es6, scope, hoisting, variables] +difficulty: junior +lang: en +--- + +## Full Answer + +JavaScript has three ways to declare variables: `var`, `let`, and `const`. They differ in scope, hoisting behavior, and mutability. + +**var** +- Function-scoped (or globally scoped if declared outside a function) +- Hoisted to the top of its scope and initialized as `undefined` +- Can be redeclared and reassigned + +**let** +- Block-scoped (limited to the `{}` block it is declared in) +- Hoisted but NOT initialized — accessing it before declaration throws a `ReferenceError` (Temporal Dead Zone) +- Cannot be redeclared in the same scope, but can be reassigned + +**const** +- Block-scoped, same as `let` +- Cannot be redeclared or reassigned — the binding is constant +- Objects and arrays declared with `const` are still mutable (their contents can change) + +**Rule of thumb:** prefer `const` by default, use `let` when you need to reassign, avoid `var`. + +## Quick Answer + +`var` is function-scoped and hoisted as `undefined`; `let` and `const` are block-scoped with a Temporal Dead Zone. `const` prevents reassignment; `let` allows it. Prefer `const` by default. + +## Flashcard + +**Q:** What are the three key differences between `var`, `let`, and `const`? + +**A:** 1) Scope — `var` is function-scoped, `let`/`const` are block-scoped. 2) Hoisting — `var` initializes as `undefined`, `let`/`const` enter the Temporal Dead Zone. 3) Reassignment — `const` forbids it, `let` and `var` allow it. diff --git a/src/content/en/frontend/react/controlled-vs-uncontrolled.md b/src/content/en/frontend/react/controlled-vs-uncontrolled.md index ecd0112..460445e 100644 --- a/src/content/en/frontend/react/controlled-vs-uncontrolled.md +++ b/src/content/en/frontend/react/controlled-vs-uncontrolled.md @@ -1,68 +1,68 @@ ---- -title: "What is the difference between controlled and uncontrolled components in React?" -category: frontend -subcategory: react -tags: [react, forms, controlled, uncontrolled, state] -difficulty: intermediate -lang: en ---- - -## Full Answer - -In React, **controlled** and **uncontrolled** components differ in where the source of truth for form data lives. - -**Controlled components** - -The component's value is driven by React state. Every keystroke triggers an event handler that calls `setState`, and the input's `value` prop is set from state. React owns the data. - -```jsx -function ControlledInput() { - const [name, setName] = useState('') - return ( - setName(e.target.value)} - /> - ) -} -``` - -Advantages: -- Instant access to the current value -- Easy to validate, transform, or disable inputs on every change -- Single source of truth — predictable behavior - -**Uncontrolled components** - -The DOM owns the value. React does not track changes. You read the value only when needed, using a `ref`. - -```jsx -function UncontrolledInput() { - const inputRef = useRef(null) - - function handleSubmit() { - console.log(inputRef.current.value) - } - - return -} -``` - -Advantages: -- Less boilerplate for simple cases -- Better for integrating with non-React code or file inputs -- Slightly better performance for very large forms (no re-render on every keystroke) - -**When to use which:** -- Default to controlled for most forms — they are predictable and easy to test. -- Use uncontrolled when integrating third-party DOM libraries or handling file inputs (`` cannot be controlled). - -## Quick Answer - -Controlled components store form data in React state and update it on every change via `onChange`. Uncontrolled components let the DOM manage the value and you read it via a `ref` when needed. Prefer controlled for most cases. - -## Flashcard - -**Q:** What is the key difference between a controlled and uncontrolled component in React? - -**A:** Controlled: React state is the source of truth, value is set via props, changes go through `onChange`. Uncontrolled: the DOM manages the value, accessed via `ref` only when needed. +--- +title: "What is the difference between controlled and uncontrolled components in React?" +category: frontend +subcategory: react +tags: [react, forms, controlled, uncontrolled, state] +difficulty: pleno +lang: en +--- + +## Full Answer + +In React, **controlled** and **uncontrolled** components differ in where the source of truth for form data lives. + +**Controlled components** + +The component's value is driven by React state. Every keystroke triggers an event handler that calls `setState`, and the input's `value` prop is set from state. React owns the data. + +```jsx +function ControlledInput() { + const [name, setName] = useState('') + return ( + setName(e.target.value)} + /> + ) +} +``` + +Advantages: +- Instant access to the current value +- Easy to validate, transform, or disable inputs on every change +- Single source of truth — predictable behavior + +**Uncontrolled components** + +The DOM owns the value. React does not track changes. You read the value only when needed, using a `ref`. + +```jsx +function UncontrolledInput() { + const inputRef = useRef(null) + + function handleSubmit() { + console.log(inputRef.current.value) + } + + return +} +``` + +Advantages: +- Less boilerplate for simple cases +- Better for integrating with non-React code or file inputs +- Slightly better performance for very large forms (no re-render on every keystroke) + +**When to use which:** +- Default to controlled for most forms — they are predictable and easy to test. +- Use uncontrolled when integrating third-party DOM libraries or handling file inputs (`` cannot be controlled). + +## Quick Answer + +Controlled components store form data in React state and update it on every change via `onChange`. Uncontrolled components let the DOM manage the value and you read it via a `ref` when needed. Prefer controlled for most cases. + +## Flashcard + +**Q:** What is the key difference between a controlled and uncontrolled component in React? + +**A:** Controlled: React state is the source of truth, value is set via props, changes go through `onChange`. Uncontrolled: the DOM manages the value, accessed via `ref` only when needed. diff --git a/src/content/en/frontend/react/hooks.md b/src/content/en/frontend/react/hooks.md index 2f801d5..5dfc70b 100644 --- a/src/content/en/frontend/react/hooks.md +++ b/src/content/en/frontend/react/hooks.md @@ -1,36 +1,36 @@ ---- -title: "What are React Hooks and why were they introduced?" -category: frontend -subcategory: react -tags: [hooks, useState, useEffect, functional-components] -difficulty: beginner -lang: en ---- - -## Full Answer - -React Hooks are functions that let you use React state and lifecycle features inside **functional components**, without writing a class component. - -Introduced in React 16.8, they solve three main problems with class components: - -1. **Reusing stateful logic** — before Hooks, sharing stateful logic required patterns like render props or HOCs. Hooks let you extract stateful logic into a custom Hook and reuse it directly. - -2. **Complex components** — lifecycle methods like `componentDidMount` forced unrelated logic to live together. `useEffect` lets you co-locate related side effects. - -3. **Classes are confusing** — `this` binding and event handler binding created a learning curve. Hooks eliminate all of that. - -**Core Hooks:** `useState`, `useEffect`, `useContext`, `useRef`, `useMemo`, `useCallback` - -**Rules of Hooks:** -1. Only call Hooks at the top level -2. Only call Hooks from React functions - -## Quick Answer - -Hooks let functional components use state and lifecycle features previously only available in class components. Introduced in React 16.8 to simplify code reuse, co-locate related logic, and eliminate class complexity. - -## Flashcard - -**Q:** What problem did React Hooks solve? - -**A:** They let functional components use state and lifecycle features without classes, solving three issues: (1) difficulty reusing stateful logic, (2) unrelated code mixed in lifecycle methods, (3) `this` binding confusion in classes. +--- +title: "What are React Hooks and why were they introduced?" +category: frontend +subcategory: react +tags: [hooks, useState, useEffect, functional-components] +difficulty: junior +lang: en +--- + +## Full Answer + +React Hooks are functions that let you use React state and lifecycle features inside **functional components**, without writing a class component. + +Introduced in React 16.8, they solve three main problems with class components: + +1. **Reusing stateful logic** — before Hooks, sharing stateful logic required patterns like render props or HOCs. Hooks let you extract stateful logic into a custom Hook and reuse it directly. + +2. **Complex components** — lifecycle methods like `componentDidMount` forced unrelated logic to live together. `useEffect` lets you co-locate related side effects. + +3. **Classes are confusing** — `this` binding and event handler binding created a learning curve. Hooks eliminate all of that. + +**Core Hooks:** `useState`, `useEffect`, `useContext`, `useRef`, `useMemo`, `useCallback` + +**Rules of Hooks:** +1. Only call Hooks at the top level +2. Only call Hooks from React functions + +## Quick Answer + +Hooks let functional components use state and lifecycle features previously only available in class components. Introduced in React 16.8 to simplify code reuse, co-locate related logic, and eliminate class complexity. + +## Flashcard + +**Q:** What problem did React Hooks solve? + +**A:** They let functional components use state and lifecycle features without classes, solving three issues: (1) difficulty reusing stateful logic, (2) unrelated code mixed in lifecycle methods, (3) `this` binding confusion in classes. diff --git a/src/content/en/frontend/react/what-is-a-component.md b/src/content/en/frontend/react/what-is-a-component.md index 1d9cce1..5ca7282 100644 --- a/src/content/en/frontend/react/what-is-a-component.md +++ b/src/content/en/frontend/react/what-is-a-component.md @@ -1,51 +1,51 @@ ---- -title: "What is a component in React?" -category: frontend -subcategory: react -tags: [component, props, JSX, functional-components] -difficulty: beginner -lang: en ---- - -## Full Answer - -A component is essentially a **JavaScript function** (or class, though functions are the current standard) that returns UI elements. It encapsulates three main pillars: - -1. **Logic:** Data and state management (Hooks). -2. **Structure:** What will be rendered (JSX). -3. **Style:** How it should look (CSS, Styled Components, etc). - -**Key characteristics:** - -- **Composition:** You build small components (button, input) and combine them to form complex components (form, dashboard). -- **Reusability:** The same component can be used in different parts of the application with different behaviors or data. -- **Isolation:** Each component manages its own lifecycle and state, making debugging and maintenance easier. - -```tsx -interface WelcomeProps { - name: string; -} - -const Welcome: React.FC = ({ name }) => { - return ( -
-

Hello, {name}!

-

Welcome to the system.

-
- ); -}; - -export default Welcome; -``` - -The `Welcome` component is pure: it receives an input (`props`) and returns a visual representation. If `name` changes, React updates only that part of the DOM efficiently. - -## Quick Answer - -A React component is a JavaScript function that returns JSX. It encapsulates logic, structure, and style in a reusable, modular, and isolated unit — enabling you to compose complex interfaces from smaller parts. - -## Flashcard - -**Q:** What is a component in React and what is its main purpose? - -**A:** An independent logical and visual unit (usually a JS function) that returns JSX. Its main purpose is to enable building modular, reusable, and maintainable interfaces by dividing the UI into smaller, isolated parts. +--- +title: "What is a component in React?" +category: frontend +subcategory: react +tags: [component, props, JSX, functional-components] +difficulty: junior +lang: en +--- + +## Full Answer + +A component is essentially a **JavaScript function** (or class, though functions are the current standard) that returns UI elements. It encapsulates three main pillars: + +1. **Logic:** Data and state management (Hooks). +2. **Structure:** What will be rendered (JSX). +3. **Style:** How it should look (CSS, Styled Components, etc). + +**Key characteristics:** + +- **Composition:** You build small components (button, input) and combine them to form complex components (form, dashboard). +- **Reusability:** The same component can be used in different parts of the application with different behaviors or data. +- **Isolation:** Each component manages its own lifecycle and state, making debugging and maintenance easier. + +```tsx +interface WelcomeProps { + name: string; +} + +const Welcome: React.FC = ({ name }) => { + return ( +
+

Hello, {name}!

+

Welcome to the system.

+
+ ); +}; + +export default Welcome; +``` + +The `Welcome` component is pure: it receives an input (`props`) and returns a visual representation. If `name` changes, React updates only that part of the DOM efficiently. + +## Quick Answer + +A React component is a JavaScript function that returns JSX. It encapsulates logic, structure, and style in a reusable, modular, and isolated unit — enabling you to compose complex interfaces from smaller parts. + +## Flashcard + +**Q:** What is a component in React and what is its main purpose? + +**A:** An independent logical and visual unit (usually a JS function) that returns JSX. Its main purpose is to enable building modular, reusable, and maintainable interfaces by dividing the UI into smaller, isolated parts. diff --git a/src/content/en/security/web/xss.md b/src/content/en/security/web/xss.md index c4614b7..585e07d 100644 --- a/src/content/en/security/web/xss.md +++ b/src/content/en/security/web/xss.md @@ -1,54 +1,54 @@ ---- -title: "What is Cross-Site Scripting (XSS) and how do you prevent it?" -category: security -subcategory: web -tags: [xss, security, injection, csrf, sanitization] -difficulty: intermediate -lang: en ---- - -## Full Answer - -**Cross-Site Scripting (XSS)** is a vulnerability where an attacker injects malicious scripts into web pages viewed by other users. The injected script runs in the victim's browser with the same privileges as the legitimate site — it can steal cookies, tokens, or perform actions on behalf of the user. - -**Types of XSS** - -1. **Stored XSS** — malicious script is saved in the database (e.g., in a comment) and served to every user who views that content. Most dangerous. - -2. **Reflected XSS** — script is embedded in a URL parameter. The server reflects it back in the response without sanitizing. Requires tricking the user into clicking a crafted link. - -3. **DOM-based XSS** — script is injected and executed entirely in the browser via client-side JavaScript (e.g., `document.innerHTML = location.hash`). Server is not involved. - -**Example (Stored XSS):** -```html - - - - -
-``` - -**Prevention** - -1. **Escape output** — HTML-encode user-supplied data before inserting it into HTML. `<` → `<`, `>` → `>`, `"` → `"`. Modern frameworks (React, Vue, Angular) do this automatically when using template syntax. - -2. **Never use raw HTML injection** — avoid `innerHTML`, `dangerouslySetInnerHTML` (React), `v-html` (Vue) with untrusted input. - -3. **Content Security Policy (CSP)** — HTTP header that restricts which scripts can run. A strict CSP blocks inline scripts and limits sources: - ``` - Content-Security-Policy: default-src 'self'; script-src 'self' - ``` - -4. **Sanitize rich text** — if you must allow HTML (e.g., WYSIWYG editors), use a trusted library like DOMPurify to strip dangerous tags before rendering. - -5. **HttpOnly cookies** — mark session cookies as `HttpOnly` so they cannot be accessed by JavaScript, limiting the damage if XSS occurs. - -## Quick Answer - -XSS is injecting malicious scripts into pages seen by other users. Prevention: escape all user output (frameworks do this by default), avoid `innerHTML` with untrusted data, use Content Security Policy headers, and mark session cookies as `HttpOnly`. - -## Flashcard - -**Q:** What is XSS and what is the primary prevention technique? - -**A:** XSS (Cross-Site Scripting) — attacker injects scripts into pages viewed by others, running with site privileges. Primary prevention: escape all user-supplied output before rendering as HTML. Also use CSP headers and `HttpOnly` cookies. +--- +title: "What is Cross-Site Scripting (XSS) and how do you prevent it?" +category: security +subcategory: web +tags: [xss, security, injection, csrf, sanitization] +difficulty: pleno +lang: en +--- + +## Full Answer + +**Cross-Site Scripting (XSS)** is a vulnerability where an attacker injects malicious scripts into web pages viewed by other users. The injected script runs in the victim's browser with the same privileges as the legitimate site — it can steal cookies, tokens, or perform actions on behalf of the user. + +**Types of XSS** + +1. **Stored XSS** — malicious script is saved in the database (e.g., in a comment) and served to every user who views that content. Most dangerous. + +2. **Reflected XSS** — script is embedded in a URL parameter. The server reflects it back in the response without sanitizing. Requires tricking the user into clicking a crafted link. + +3. **DOM-based XSS** — script is injected and executed entirely in the browser via client-side JavaScript (e.g., `document.innerHTML = location.hash`). Server is not involved. + +**Example (Stored XSS):** +```html + + + + +
+``` + +**Prevention** + +1. **Escape output** — HTML-encode user-supplied data before inserting it into HTML. `<` → `<`, `>` → `>`, `"` → `"`. Modern frameworks (React, Vue, Angular) do this automatically when using template syntax. + +2. **Never use raw HTML injection** — avoid `innerHTML`, `dangerouslySetInnerHTML` (React), `v-html` (Vue) with untrusted input. + +3. **Content Security Policy (CSP)** — HTTP header that restricts which scripts can run. A strict CSP blocks inline scripts and limits sources: + ``` + Content-Security-Policy: default-src 'self'; script-src 'self' + ``` + +4. **Sanitize rich text** — if you must allow HTML (e.g., WYSIWYG editors), use a trusted library like DOMPurify to strip dangerous tags before rendering. + +5. **HttpOnly cookies** — mark session cookies as `HttpOnly` so they cannot be accessed by JavaScript, limiting the damage if XSS occurs. + +## Quick Answer + +XSS is injecting malicious scripts into pages seen by other users. Prevention: escape all user output (frameworks do this by default), avoid `innerHTML` with untrusted data, use Content Security Policy headers, and mark session cookies as `HttpOnly`. + +## Flashcard + +**Q:** What is XSS and what is the primary prevention technique? + +**A:** XSS (Cross-Site Scripting) — attacker injects scripts into pages viewed by others, running with site privileges. Primary prevention: escape all user-supplied output before rendering as HTML. Also use CSP headers and `HttpOnly` cookies. diff --git a/src/content/en/soft-skills/hr/tell-me-about-yourself.md b/src/content/en/soft-skills/hr/tell-me-about-yourself.md index 901a4e1..6f369f7 100644 --- a/src/content/en/soft-skills/hr/tell-me-about-yourself.md +++ b/src/content/en/soft-skills/hr/tell-me-about-yourself.md @@ -1,45 +1,45 @@ ---- -title: "How do you answer \"Tell me about yourself\"?" -category: soft-skills -subcategory: hr -tags: [hr, storytelling, intro, pitch, behavioral] -difficulty: beginner -lang: en ---- - -## Full Answer - -"Tell me about yourself" is almost always the first question in any interview — technical or HR. Most candidates treat it as an invitation to recite their resume. It isn't. It is your opportunity to deliver a focused, compelling professional pitch. - -**What the interviewer actually wants to know:** -- Can this person communicate clearly? -- Does their background match what we need? -- Are they genuinely interested in this role? - -**The structure: Present → Past → Future** - -1. **Present** — your current role and what you do (1-2 sentences). This anchors the conversation. -2. **Past** — 1-2 relevant experiences that explain how you got here and demonstrate value. -3. **Future** — why this role and this company specifically. Connect your trajectory to their opportunity. - -**Example (software engineer):** - -> "I'm currently a full-stack engineer at a fintech startup where I lead the payments infrastructure team — we process around 2 million transactions a month. Before that I spent 3 years at a consulting firm where I built data pipelines for enterprise clients, which gave me a strong foundation in backend systems and cross-functional collaboration. I'm looking to move into a product-focused environment at this stage, and what drew me to your company is the scale of the data problems you're working on — particularly the work your team has published around real-time fraud detection." - -**What to avoid:** -- Starting with childhood or education unless you are a new graduate -- Reciting your entire LinkedIn profile chronologically -- Being vague: "I'm a passionate developer who loves solving problems" -- Going over 2 minutes - -**For new graduates:** Lead with your most relevant project or internship, then mention your degree, then express what you're looking for. - -## Quick Answer - -Use the Present → Past → Future structure: what you do now (1-2 sentences), 1-2 relevant past experiences, and why this specific role at this specific company. Keep it under 2 minutes. Make it a pitch, not a biography. - -## Flashcard - -**Q:** What structure should you use to answer "Tell me about yourself"? - -**A:** Present → Past → Future. Current role (what you do now) → 1-2 relevant past experiences → why this role and company specifically. Keep it under 2 minutes. +--- +title: "How do you answer \"Tell me about yourself\"?" +category: soft-skills +subcategory: hr +tags: [hr, storytelling, intro, pitch, behavioral] +difficulty: junior +lang: en +--- + +## Full Answer + +"Tell me about yourself" is almost always the first question in any interview — technical or HR. Most candidates treat it as an invitation to recite their resume. It isn't. It is your opportunity to deliver a focused, compelling professional pitch. + +**What the interviewer actually wants to know:** +- Can this person communicate clearly? +- Does their background match what we need? +- Are they genuinely interested in this role? + +**The structure: Present → Past → Future** + +1. **Present** — your current role and what you do (1-2 sentences). This anchors the conversation. +2. **Past** — 1-2 relevant experiences that explain how you got here and demonstrate value. +3. **Future** — why this role and this company specifically. Connect your trajectory to their opportunity. + +**Example (software engineer):** + +> "I'm currently a full-stack engineer at a fintech startup where I lead the payments infrastructure team — we process around 2 million transactions a month. Before that I spent 3 years at a consulting firm where I built data pipelines for enterprise clients, which gave me a strong foundation in backend systems and cross-functional collaboration. I'm looking to move into a product-focused environment at this stage, and what drew me to your company is the scale of the data problems you're working on — particularly the work your team has published around real-time fraud detection." + +**What to avoid:** +- Starting with childhood or education unless you are a new graduate +- Reciting your entire LinkedIn profile chronologically +- Being vague: "I'm a passionate developer who loves solving problems" +- Going over 2 minutes + +**For new graduates:** Lead with your most relevant project or internship, then mention your degree, then express what you're looking for. + +## Quick Answer + +Use the Present → Past → Future structure: what you do now (1-2 sentences), 1-2 relevant past experiences, and why this specific role at this specific company. Keep it under 2 minutes. Make it a pitch, not a biography. + +## Flashcard + +**Q:** What structure should you use to answer "Tell me about yourself"? + +**A:** Present → Past → Future. Current role (what you do now) → 1-2 relevant past experiences → why this role and company specifically. Keep it under 2 minutes. diff --git a/src/content/pt/architecture/software-engineering/arquitetura-escalavel.md b/src/content/pt/architecture/software-engineering/arquitetura-escalavel.md index 86d6b9d..3a1b0c0 100644 --- a/src/content/pt/architecture/software-engineering/arquitetura-escalavel.md +++ b/src/content/pt/architecture/software-engineering/arquitetura-escalavel.md @@ -1,39 +1,39 @@ ---- -title: "O que é uma arquitetura escalável?" -category: architecture -subcategory: software-engineering -tags: [escalabilidade, arquitetura, sistemas-distribuidos] -difficulty: intermediate -lang: pt ---- - -## Full Answer - -Uma arquitetura escalável é uma arquitetura de software capaz de suportar o aumento de usuários, requisições e volume de dados sem perda significativa de desempenho. - -Ela permite que o sistema cresça de forma eficiente, adicionando recursos conforme a demanda aumenta. - -A escalabilidade pode ocorrer de duas formas: -- Escalabilidade vertical → aumentar recursos da máquina, como CPU e memória -- Escalabilidade horizontal → adicionar novas instâncias da aplicação - -Arquiteturas escaláveis normalmente utilizam: -- Load balancers -- Containers -- Kubernetes -- Cache -- Filas de mensageria -- Bancos distribuídos -- Microserviços - -O objetivo é garantir alta disponibilidade, desempenho e capacidade de crescimento da aplicação. - -## Quick Answer - -Uma arquitetura escalável é capaz de crescer e suportar mais carga sem comprometer o desempenho do sistema. - -## Flashcard - -**P:** O que é uma arquitetura escalável? - -**R:** É uma arquitetura capaz de suportar aumento de carga e usuários mantendo bom desempenho e disponibilidade. \ No newline at end of file +--- +title: "O que é uma arquitetura escalável?" +category: architecture +subcategory: software-engineering +tags: [escalabilidade, arquitetura, sistemas-distribuidos] +difficulty: pleno +lang: pt +--- + +## Full Answer + +Uma arquitetura escalável é uma arquitetura de software capaz de suportar o aumento de usuários, requisições e volume de dados sem perda significativa de desempenho. + +Ela permite que o sistema cresça de forma eficiente, adicionando recursos conforme a demanda aumenta. + +A escalabilidade pode ocorrer de duas formas: +- Escalabilidade vertical → aumentar recursos da máquina, como CPU e memória +- Escalabilidade horizontal → adicionar novas instâncias da aplicação + +Arquiteturas escaláveis normalmente utilizam: +- Load balancers +- Containers +- Kubernetes +- Cache +- Filas de mensageria +- Bancos distribuídos +- Microserviços + +O objetivo é garantir alta disponibilidade, desempenho e capacidade de crescimento da aplicação. + +## Quick Answer + +Uma arquitetura escalável é capaz de crescer e suportar mais carga sem comprometer o desempenho do sistema. + +## Flashcard + +**P:** O que é uma arquitetura escalável? + +**R:** É uma arquitetura capaz de suportar aumento de carga e usuários mantendo bom desempenho e disponibilidade. diff --git a/src/content/pt/architecture/solid/solid-principles.md b/src/content/pt/architecture/solid/solid-principles.md index e0b3462..893ec55 100644 --- a/src/content/pt/architecture/solid/solid-principles.md +++ b/src/content/pt/architecture/solid/solid-principles.md @@ -1,70 +1,70 @@ ---- -title: "O que são os princípios SOLID?" -category: architecture -subcategory: solid -tags: [solid, oop, design-principles, clean-code] -difficulty: intermediate -lang: pt ---- - -## Full Answer - -SOLID é um acrônimo para cinco princípios de design orientado a objetos que tornam o software mais fácil de entender, modificar e estender. - -**S — Single Responsibility Principle (Princípio da Responsabilidade Única)** -Uma classe deve ter um, e apenas um, motivo para mudar. Na prática: se você descreve uma classe com "e", ela provavelmente tem responsabilidades demais. - -```typescript -// Ruim: uma classe faz parsing E persistência -class UserService { - parseCSV(data: string) { ... } - saveToDatabase(user: User) { ... } -} - -// Bom: responsabilidades separadas -class UserParser { parseCSV(data: string) { ... } } -class UserRepository { save(user: User) { ... } } -``` - -**O — Open/Closed Principle (Princípio Aberto/Fechado)** -Entidades de software devem ser abertas para extensão, mas fechadas para modificação. Adicione comportamento novo criando código novo, não alterando o existente. - -**L — Liskov Substitution Principle (Princípio da Substituição de Liskov)** -Subtipos devem ser substituíveis pelos seus tipos base sem quebrar o comportamento. Se `Quadrado extends Retangulo` mas sobrescrever `setWidth` também muda a altura, viola o LSP — código que espera um `Retangulo` vai quebrar. - -**I — Interface Segregation Principle (Princípio da Segregação de Interface)** -Nenhum cliente deve ser forçado a depender de métodos que não usa. Prefira interfaces pequenas e focadas a interfaces grandes e genéricas. - -```typescript -// Ruim: uma interface grande -interface Trabalhador { trabalhar(): void; comer(): void; dormir(): void } - -// Bom: dividida por papel -interface Trabalhavel { trabalhar(): void } -interface Descansavel { comer(): void; dormir(): void } -``` - -**D — Dependency Inversion Principle (Princípio da Inversão de Dependência)** -Módulos de alto nível não devem depender de módulos de baixo nível. Ambos devem depender de abstrações. Na prática: dependa de interfaces, injete implementações. - -```typescript -// Ruim: alto nível depende diretamente do baixo nível -class OrderService { - private db = new PostgresDatabase() -} - -// Bom: depende de abstração, implementação injetada -class OrderService { - constructor(private db: Database) {} -} -``` - -## Quick Answer - -SOLID: **S**ingle Responsibility (um motivo para mudar), **O**pen/Closed (estender sem modificar), **L**iskov Substitution (subtipos substituem o tipo base), **I**nterface Segregation (interfaces pequenas e focadas), **D**ependency Inversion (dependa de abstrações, injete implementações). - -## Flashcard - -**P:** O que significa cada letra do SOLID? - -**R:** S — Responsabilidade Única (um motivo para mudar). O — Aberto/Fechado (aberto para extensão, fechado para modificação). L — Substituição de Liskov (subtipos substituem o tipo base). I — Segregação de Interface (interfaces pequenas). D — Inversão de Dependência (dependa de abstrações, não de implementações). +--- +title: "O que são os princípios SOLID?" +category: architecture +subcategory: solid +tags: [solid, oop, design-principles, clean-code] +difficulty: pleno +lang: pt +--- + +## Full Answer + +SOLID é um acrônimo para cinco princípios de design orientado a objetos que tornam o software mais fácil de entender, modificar e estender. + +**S — Single Responsibility Principle (Princípio da Responsabilidade Única)** +Uma classe deve ter um, e apenas um, motivo para mudar. Na prática: se você descreve uma classe com "e", ela provavelmente tem responsabilidades demais. + +```typescript +// Ruim: uma classe faz parsing E persistência +class UserService { + parseCSV(data: string) { ... } + saveToDatabase(user: User) { ... } +} + +// Bom: responsabilidades separadas +class UserParser { parseCSV(data: string) { ... } } +class UserRepository { save(user: User) { ... } } +``` + +**O — Open/Closed Principle (Princípio Aberto/Fechado)** +Entidades de software devem ser abertas para extensão, mas fechadas para modificação. Adicione comportamento novo criando código novo, não alterando o existente. + +**L — Liskov Substitution Principle (Princípio da Substituição de Liskov)** +Subtipos devem ser substituíveis pelos seus tipos base sem quebrar o comportamento. Se `Quadrado extends Retangulo` mas sobrescrever `setWidth` também muda a altura, viola o LSP — código que espera um `Retangulo` vai quebrar. + +**I — Interface Segregation Principle (Princípio da Segregação de Interface)** +Nenhum cliente deve ser forçado a depender de métodos que não usa. Prefira interfaces pequenas e focadas a interfaces grandes e genéricas. + +```typescript +// Ruim: uma interface grande +interface Trabalhador { trabalhar(): void; comer(): void; dormir(): void } + +// Bom: dividida por papel +interface Trabalhavel { trabalhar(): void } +interface Descansavel { comer(): void; dormir(): void } +``` + +**D — Dependency Inversion Principle (Princípio da Inversão de Dependência)** +Módulos de alto nível não devem depender de módulos de baixo nível. Ambos devem depender de abstrações. Na prática: dependa de interfaces, injete implementações. + +```typescript +// Ruim: alto nível depende diretamente do baixo nível +class OrderService { + private db = new PostgresDatabase() +} + +// Bom: depende de abstração, implementação injetada +class OrderService { + constructor(private db: Database) {} +} +``` + +## Quick Answer + +SOLID: **S**ingle Responsibility (um motivo para mudar), **O**pen/Closed (estender sem modificar), **L**iskov Substitution (subtipos substituem o tipo base), **I**nterface Segregation (interfaces pequenas e focadas), **D**ependency Inversion (dependa de abstrações, injete implementações). + +## Flashcard + +**P:** O que significa cada letra do SOLID? + +**R:** S — Responsabilidade Única (um motivo para mudar). O — Aberto/Fechado (aberto para extensão, fechado para modificação). L — Substituição de Liskov (subtipos substituem o tipo base). I — Segregação de Interface (interfaces pequenas). D — Inversão de Dependência (dependa de abstrações, não de implementações). diff --git a/src/content/pt/backend/general/graphql.md b/src/content/pt/backend/general/graphql.md index a456eaf..dad822e 100644 --- a/src/content/pt/backend/general/graphql.md +++ b/src/content/pt/backend/general/graphql.md @@ -1,99 +1,99 @@ ---- -title: "Explique o que é GraphQL" -category: backend -subcategory: general -tags: [graphql, api, query, schema, rest, tipos] -difficulty: intermediate -lang: pt ---- - -## Full Answer - -GraphQL é uma **linguagem de consulta para APIs** e um runtime para executar essas consultas, criado pelo Facebook em 2012 e aberto ao público em 2015. É uma alternativa ao REST que dá ao cliente controle total sobre quais dados receber. - -**O problema que o GraphQL resolve** - -Em REST, os endpoints definem o formato da resposta. Isso gera dois problemas comuns: - -- **Over-fetching** — o endpoint retorna campos que o cliente não precisa -- **Under-fetching** — o cliente precisa chamar múltiplos endpoints para montar uma tela - -Com GraphQL, o cliente descreve exatamente o que quer em uma única requisição. - -**Como funciona** - -Tudo passa por um único endpoint (`POST /graphql`). O cliente envia uma query descrevendo a estrutura de dados desejada: - -```graphql -query { - user(id: "42") { - name - email - posts { - title - publishedAt - } - } -} -``` - -O servidor retorna exatamente isso — nem mais, nem menos. - -**Os três tipos de operação** - -| Operação | Equivalente REST | Uso | -|----------|-----------------|-----| -| `query` | `GET` | Leitura de dados | -| `mutation` | `POST` / `PUT` / `DELETE` | Escrita de dados | -| `subscription` | WebSocket | Dados em tempo real | - -**Schema e tipos** - -O contrato da API é definido em um schema fortemente tipado: - -```graphql -type User { - id: ID! - name: String! - email: String! - posts: [Post!]! -} - -type Post { - title: String! - publishedAt: String -} -``` - -O `!` indica campo obrigatório (não-nulo). O schema é a documentação viva da API. - -**GraphQL vs REST** - -| | REST | GraphQL | -|---|---|---| -| Endpoints | Múltiplos | Um único | -| Formato da resposta | Definido pelo servidor | Definido pelo cliente | -| Over/under-fetching | Comum | Eliminado | -| Tipagem | Opcional (OpenAPI) | Nativa e obrigatória | -| Tempo real | Não nativo | Subscriptions | -| Curva de aprendizado | Baixa | Média | - -**Quando usar GraphQL:** -- Múltiplos clientes com necessidades de dados diferentes (web, mobile, TV) -- APIs públicas com consumidores externos variados -- Telas complexas que agregam dados de múltiplas entidades - -**Quando REST ainda é melhor:** -- APIs simples com poucos endpoints -- Time sem experiência em GraphQL -- Operações de upload de arquivo ou streaming - -## Quick Answer - -GraphQL é uma linguagem de consulta para APIs onde o cliente define exatamente quais dados quer receber. Tudo passa por um único endpoint; o schema tipado define o contrato. Resolve over-fetching e under-fetching comuns em REST. Suporta queries (leitura), mutations (escrita) e subscriptions (tempo real). - -## Flashcard - -**P:** O que é GraphQL e qual problema ele resolve? - -**R:** GraphQL é uma linguagem de consulta para APIs onde o cliente descreve exatamente os dados que quer. Resolve over-fetching (receber dados demais) e under-fetching (precisar de múltiplas chamadas). Usa um único endpoint, schema fortemente tipado, e suporta queries, mutations e subscriptions. +--- +title: "Explique o que é GraphQL" +category: backend +subcategory: general +tags: [graphql, api, query, schema, rest, tipos] +difficulty: pleno +lang: pt +--- + +## Full Answer + +GraphQL é uma **linguagem de consulta para APIs** e um runtime para executar essas consultas, criado pelo Facebook em 2012 e aberto ao público em 2015. É uma alternativa ao REST que dá ao cliente controle total sobre quais dados receber. + +**O problema que o GraphQL resolve** + +Em REST, os endpoints definem o formato da resposta. Isso gera dois problemas comuns: + +- **Over-fetching** — o endpoint retorna campos que o cliente não precisa +- **Under-fetching** — o cliente precisa chamar múltiplos endpoints para montar uma tela + +Com GraphQL, o cliente descreve exatamente o que quer em uma única requisição. + +**Como funciona** + +Tudo passa por um único endpoint (`POST /graphql`). O cliente envia uma query descrevendo a estrutura de dados desejada: + +```graphql +query { + user(id: "42") { + name + email + posts { + title + publishedAt + } + } +} +``` + +O servidor retorna exatamente isso — nem mais, nem menos. + +**Os três tipos de operação** + +| Operação | Equivalente REST | Uso | +|----------|-----------------|-----| +| `query` | `GET` | Leitura de dados | +| `mutation` | `POST` / `PUT` / `DELETE` | Escrita de dados | +| `subscription` | WebSocket | Dados em tempo real | + +**Schema e tipos** + +O contrato da API é definido em um schema fortemente tipado: + +```graphql +type User { + id: ID! + name: String! + email: String! + posts: [Post!]! +} + +type Post { + title: String! + publishedAt: String +} +``` + +O `!` indica campo obrigatório (não-nulo). O schema é a documentação viva da API. + +**GraphQL vs REST** + +| | REST | GraphQL | +|---|---|---| +| Endpoints | Múltiplos | Um único | +| Formato da resposta | Definido pelo servidor | Definido pelo cliente | +| Over/under-fetching | Comum | Eliminado | +| Tipagem | Opcional (OpenAPI) | Nativa e obrigatória | +| Tempo real | Não nativo | Subscriptions | +| Curva de aprendizado | Baixa | Média | + +**Quando usar GraphQL:** +- Múltiplos clientes com necessidades de dados diferentes (web, mobile, TV) +- APIs públicas com consumidores externos variados +- Telas complexas que agregam dados de múltiplas entidades + +**Quando REST ainda é melhor:** +- APIs simples com poucos endpoints +- Time sem experiência em GraphQL +- Operações de upload de arquivo ou streaming + +## Quick Answer + +GraphQL é uma linguagem de consulta para APIs onde o cliente define exatamente quais dados quer receber. Tudo passa por um único endpoint; o schema tipado define o contrato. Resolve over-fetching e under-fetching comuns em REST. Suporta queries (leitura), mutations (escrita) e subscriptions (tempo real). + +## Flashcard + +**P:** O que é GraphQL e qual problema ele resolve? + +**R:** GraphQL é uma linguagem de consulta para APIs onde o cliente descreve exatamente os dados que quer. Resolve over-fetching (receber dados demais) e under-fetching (precisar de múltiplas chamadas). Usa um único endpoint, schema fortemente tipado, e suporta queries, mutations e subscriptions. diff --git a/src/content/pt/backend/general/o-que-e-api.md b/src/content/pt/backend/general/o-que-e-api.md index ef3b84b..7ebb22a 100644 --- a/src/content/pt/backend/general/o-que-e-api.md +++ b/src/content/pt/backend/general/o-que-e-api.md @@ -1,73 +1,73 @@ ---- -title: "O que é uma API?" -category: backend -subcategory: general -tags: [api, http, rest, contrato, integração, web] -difficulty: beginner -lang: pt ---- - -## Full Answer - -API (Application Programming Interface) é um **contrato que define como dois sistemas se comunicam**. Ela expõe funcionalidades de um sistema para que outro possa utilizá-las sem precisar conhecer os detalhes internos de implementação. - -**A analogia do restaurante** - -Pense em um restaurante: você (cliente) não vai à cozinha preparar a comida. Você faz um pedido ao garçom (API), que leva sua solicitação à cozinha (servidor) e traz o resultado de volta. Você não precisa saber como a comida é feita — só precisa conhecer o cardápio (contrato da API). - -**O que uma API define** - -- **Endpoint** — onde fazer a requisição (`https://api.exemplo.com/users`) -- **Método** — o que fazer (`GET`, `POST`, `PUT`, `DELETE`) -- **Parâmetros** — o que enviar (headers, query params, body) -- **Resposta** — o formato dos dados retornados (geralmente JSON) - -**Exemplo prático** - -Um app de clima no seu celular não coleta dados meteorológicos. Ele chama a API de um serviço como OpenWeather: - -``` -GET https://api.openweathermap.org/data/2.5/weather?q=São Paulo -``` - -O serviço responde com JSON: - -```json -{ - "city": "São Paulo", - "temp": 24, - "condition": "Parcialmente nublado" -} -``` - -O app exibe esses dados sem saber nada sobre como eles foram coletados. - -**Tipos de API** - -| Tipo | Descrição | Exemplo | -|------|-----------|---------| -| **REST** | Usa HTTP + JSON, arquitetura stateless | GitHub API, Twitter API | -| **GraphQL** | Cliente define os dados que quer | Shopify, GitHub v4 | -| **SOAP** | Protocolo baseado em XML, mais formal | Sistemas bancários legados | -| **WebSocket** | Conexão persistente bidirecional | Chat, notificações em tempo real | -| **gRPC** | Binário, alta performance, tipado | Comunicação entre microsserviços | - -**API pública vs privada** - -- **Pública** — qualquer desenvolvedor pode usar (Stripe, Google Maps, OpenAI) -- **Privada** — uso interno entre sistemas da mesma empresa -- **Partner** — compartilhada com parceiros específicos mediante autenticação - -**Por que APIs importam** - -APIs são o que permitem que sistemas diferentes se integrem: seu app usa a API do Stripe para pagamentos, a do SendGrid para e-mails, a do Google Maps para localização — sem precisar construir nada disso do zero. - -## Quick Answer - -API é um contrato que define como dois sistemas se comunicam. Ela expõe funcionalidades de um serviço (endpoints, métodos, formato de resposta) para que outro sistema possa consumi-las sem conhecer a implementação interna. Na web, APIs geralmente usam HTTP e retornam JSON. - -## Flashcard - -**P:** O que é uma API? - -**R:** API (Application Programming Interface) é um contrato que define como dois sistemas se comunicam. Ela expõe endpoints que aceitam requisições e retornam respostas em formato padronizado (geralmente JSON), permitindo que sistemas se integrem sem conhecer a implementação um do outro. +--- +title: "O que é uma API?" +category: backend +subcategory: general +tags: [api, http, rest, contrato, integração, web] +difficulty: junior +lang: pt +--- + +## Full Answer + +API (Application Programming Interface) é um **contrato que define como dois sistemas se comunicam**. Ela expõe funcionalidades de um sistema para que outro possa utilizá-las sem precisar conhecer os detalhes internos de implementação. + +**A analogia do restaurante** + +Pense em um restaurante: você (cliente) não vai à cozinha preparar a comida. Você faz um pedido ao garçom (API), que leva sua solicitação à cozinha (servidor) e traz o resultado de volta. Você não precisa saber como a comida é feita — só precisa conhecer o cardápio (contrato da API). + +**O que uma API define** + +- **Endpoint** — onde fazer a requisição (`https://api.exemplo.com/users`) +- **Método** — o que fazer (`GET`, `POST`, `PUT`, `DELETE`) +- **Parâmetros** — o que enviar (headers, query params, body) +- **Resposta** — o formato dos dados retornados (geralmente JSON) + +**Exemplo prático** + +Um app de clima no seu celular não coleta dados meteorológicos. Ele chama a API de um serviço como OpenWeather: + +``` +GET https://api.openweathermap.org/data/2.5/weather?q=São Paulo +``` + +O serviço responde com JSON: + +```json +{ + "city": "São Paulo", + "temp": 24, + "condition": "Parcialmente nublado" +} +``` + +O app exibe esses dados sem saber nada sobre como eles foram coletados. + +**Tipos de API** + +| Tipo | Descrição | Exemplo | +|------|-----------|---------| +| **REST** | Usa HTTP + JSON, arquitetura stateless | GitHub API, Twitter API | +| **GraphQL** | Cliente define os dados que quer | Shopify, GitHub v4 | +| **SOAP** | Protocolo baseado em XML, mais formal | Sistemas bancários legados | +| **WebSocket** | Conexão persistente bidirecional | Chat, notificações em tempo real | +| **gRPC** | Binário, alta performance, tipado | Comunicação entre microsserviços | + +**API pública vs privada** + +- **Pública** — qualquer desenvolvedor pode usar (Stripe, Google Maps, OpenAI) +- **Privada** — uso interno entre sistemas da mesma empresa +- **Partner** — compartilhada com parceiros específicos mediante autenticação + +**Por que APIs importam** + +APIs são o que permitem que sistemas diferentes se integrem: seu app usa a API do Stripe para pagamentos, a do SendGrid para e-mails, a do Google Maps para localização — sem precisar construir nada disso do zero. + +## Quick Answer + +API é um contrato que define como dois sistemas se comunicam. Ela expõe funcionalidades de um serviço (endpoints, métodos, formato de resposta) para que outro sistema possa consumi-las sem conhecer a implementação interna. Na web, APIs geralmente usam HTTP e retornam JSON. + +## Flashcard + +**P:** O que é uma API? + +**R:** API (Application Programming Interface) é um contrato que define como dois sistemas se comunicam. Ela expõe endpoints que aceitam requisições e retornam respostas em formato padronizado (geralmente JSON), permitindo que sistemas se integrem sem conhecer a implementação um do outro. diff --git a/src/content/pt/backend/general/rest.md b/src/content/pt/backend/general/rest.md index 3efb7b5..e32f130 100644 --- a/src/content/pt/backend/general/rest.md +++ b/src/content/pt/backend/general/rest.md @@ -1,56 +1,56 @@ ---- -title: "Explique o que é REST" -category: backend -subcategory: general -tags: [rest, api, http, stateless, web, arquitetura] -difficulty: beginner -lang: pt ---- - -## Full Answer - -REST (Representational State Transfer) é um **estilo arquitetural** para projetar APIs web. Não é um protocolo nem um padrão formal — é um conjunto de restrições que, quando seguidas, produzem APIs previsíveis, escaláveis e fáceis de consumir. - -**As restrições principais do REST** - -1. **Cliente-Servidor** — a interface do usuário e o armazenamento de dados são separados. Cada lado evolui independentemente. - -2. **Stateless (sem estado)** — cada requisição deve conter todas as informações necessárias para ser processada. O servidor não guarda sessão entre requisições. Estado de autenticação vai no header (ex: `Authorization: Bearer `). - -3. **Interface uniforme** — recursos são identificados por URIs e manipulados via métodos HTTP padronizados: - - | Método | Ação | - |--------|------| - | `GET` | Lê um recurso | - | `POST` | Cria um novo recurso | - | `PUT` / `PATCH` | Atualiza um recurso | - | `DELETE` | Remove um recurso | - -4. **Recursos como substantivos** — a URI identifica *o quê*, o método HTTP diz *o que fazer*: - - `GET /users` — lista usuários - - `POST /users` — cria um usuário - - `GET /users/42` — busca o usuário 42 - - `DELETE /users/42` — remove o usuário 42 - -5. **Representações** — o servidor retorna uma representação do recurso (geralmente JSON), não o recurso em si. - -6. **Cacheável** — respostas devem indicar se podem ser cacheadas, permitindo que clientes e intermediários (proxies, CDNs) reutilizem respostas. - -**REST vs REST "de fato"** - -Na prática, a maioria das APIs chamadas "REST" são na verdade **RESTful** no sentido informal — usam HTTP + JSON com URIs razoáveis, mas não seguem todas as restrições (ex: HATEOAS). Isso é aceitável na maioria dos contextos. - -**O que REST não é:** -- Não é um protocolo (o protocolo é HTTP) -- Não é só "usar JSON" -- Não é SOAP (que é um protocolo com contrato XML formal) - -## Quick Answer - -REST é um estilo arquitetural para APIs web que usa HTTP de forma padronizada: recursos identificados por URIs (substantivos), manipulados por métodos HTTP (`GET`, `POST`, `PUT`, `DELETE`). É stateless — cada requisição carrega tudo que o servidor precisa. O formato de resposta mais comum é JSON. - -## Flashcard - -**P:** O que é REST e quais são suas características principais? - -**R:** REST é um estilo arquitetural para APIs web. Características: stateless (sem sessão no servidor), interface uniforme (URI + métodos HTTP), cliente-servidor separados, respostas cacheáveis. Recursos são substantivos na URI (`/users/42`), métodos HTTP definem a ação (`GET`, `POST`, `PUT`, `DELETE`). +--- +title: "Explique o que é REST" +category: backend +subcategory: general +tags: [rest, api, http, stateless, web, arquitetura] +difficulty: junior +lang: pt +--- + +## Full Answer + +REST (Representational State Transfer) é um **estilo arquitetural** para projetar APIs web. Não é um protocolo nem um padrão formal — é um conjunto de restrições que, quando seguidas, produzem APIs previsíveis, escaláveis e fáceis de consumir. + +**As restrições principais do REST** + +1. **Cliente-Servidor** — a interface do usuário e o armazenamento de dados são separados. Cada lado evolui independentemente. + +2. **Stateless (sem estado)** — cada requisição deve conter todas as informações necessárias para ser processada. O servidor não guarda sessão entre requisições. Estado de autenticação vai no header (ex: `Authorization: Bearer `). + +3. **Interface uniforme** — recursos são identificados por URIs e manipulados via métodos HTTP padronizados: + + | Método | Ação | + |--------|------| + | `GET` | Lê um recurso | + | `POST` | Cria um novo recurso | + | `PUT` / `PATCH` | Atualiza um recurso | + | `DELETE` | Remove um recurso | + +4. **Recursos como substantivos** — a URI identifica *o quê*, o método HTTP diz *o que fazer*: + - `GET /users` — lista usuários + - `POST /users` — cria um usuário + - `GET /users/42` — busca o usuário 42 + - `DELETE /users/42` — remove o usuário 42 + +5. **Representações** — o servidor retorna uma representação do recurso (geralmente JSON), não o recurso em si. + +6. **Cacheável** — respostas devem indicar se podem ser cacheadas, permitindo que clientes e intermediários (proxies, CDNs) reutilizem respostas. + +**REST vs REST "de fato"** + +Na prática, a maioria das APIs chamadas "REST" são na verdade **RESTful** no sentido informal — usam HTTP + JSON com URIs razoáveis, mas não seguem todas as restrições (ex: HATEOAS). Isso é aceitável na maioria dos contextos. + +**O que REST não é:** +- Não é um protocolo (o protocolo é HTTP) +- Não é só "usar JSON" +- Não é SOAP (que é um protocolo com contrato XML formal) + +## Quick Answer + +REST é um estilo arquitetural para APIs web que usa HTTP de forma padronizada: recursos identificados por URIs (substantivos), manipulados por métodos HTTP (`GET`, `POST`, `PUT`, `DELETE`). É stateless — cada requisição carrega tudo que o servidor precisa. O formato de resposta mais comum é JSON. + +## Flashcard + +**P:** O que é REST e quais são suas características principais? + +**R:** REST é um estilo arquitetural para APIs web. Características: stateless (sem sessão no servidor), interface uniforme (URI + métodos HTTP), cliente-servidor separados, respostas cacheáveis. Recursos são substantivos na URI (`/users/42`), métodos HTTP definem a ação (`GET`, `POST`, `PUT`, `DELETE`). diff --git a/src/content/pt/backend/node/middlewares.md b/src/content/pt/backend/node/middlewares.md index 233e3f7..7a33ea0 100644 --- a/src/content/pt/backend/node/middlewares.md +++ b/src/content/pt/backend/node/middlewares.md @@ -1,113 +1,113 @@ ---- -title: "O que são e como funcionam middlewares no Node.js?" -category: backend -subcategory: node -tags: [middleware, express, nodejs, request, response] -difficulty: intermediate -lang: pt ---- - -## Full Answer - -Middleware é uma função que fica no meio do ciclo de requisição-resposta. Ela recebe o objeto `req`, o objeto `res` e a função `next`, podendo executar código, modificar a requisição ou resposta, encerrar o ciclo ou passar o controle para o próximo middleware. - -``` -Requisição → middleware 1 → middleware 2 → rota → resposta -``` - -### Assinatura básica - -```js -function meuMiddleware(req, res, next) { - // faz alguma coisa - next() // passa para o próximo -} -``` - -Se `next()` não for chamado e a resposta também não for enviada, a requisição fica travada. - -### Tipos comuns - -**1. Middleware de aplicação** — executado em todas as rotas ou em rotas específicas: - -```js -// todas as rotas -app.use((req, res, next) => { - console.log(`${req.method} ${req.url}`) - next() -}) - -// apenas /admin -app.use('/admin', autenticar) -``` - -**2. Middleware de rota** — aplicado a uma rota específica: - -```js -app.get('/perfil', autenticar, (req, res) => { - res.json(req.usuario) -}) -``` - -**3. Middleware de erro** — possui quatro parâmetros; o Express identifica pelo `err` como primeiro argumento: - -```js -app.use((err, req, res, next) => { - console.error(err.stack) - res.status(500).json({ erro: 'Algo deu errado' }) -}) -``` - -**4. Middleware de terceiros** — bibliotecas que se encaixam no pipeline: - -```js -import express from 'express' -import cors from 'cors' -import helmet from 'helmet' - -const app = express() - -app.use(helmet()) // cabeçalhos de segurança -app.use(cors()) // controle de origem -app.use(express.json()) // parse do body JSON -``` - -### Ordem importa - -O Express executa middlewares na ordem em que são registrados com `app.use()`. Um middleware de autenticação precisa vir antes das rotas protegidas; o middleware de erro precisa vir por último. - -```js -app.use(logger) // 1º — loga todas as requisições -app.use(autenticar) // 2º — bloqueia se não autenticado -app.get('/dados', handler) -app.use(tratarErros) // último — captura erros de toda a aplicação -``` - -### Exemplo completo: autenticação com JWT - -```js -function autenticar(req, res, next) { - const token = req.headers.authorization?.split(' ')[1] - - if (!token) { - return res.status(401).json({ erro: 'Token ausente' }) - } - - try { - req.usuario = jwt.verify(token, process.env.JWT_SECRET) - next() - } catch { - res.status(401).json({ erro: 'Token inválido' }) - } -} -``` - -## Quick Answer - -Middleware no Node.js (especialmente no Express) é uma função com acesso a `req`, `res` e `next` que intercepta o ciclo de requisição-resposta. Você os encadeia para separar responsabilidades como logging, autenticação e tratamento de erros — cada um faz sua parte e chama `next()` para passar o controle ao próximo. - -## Flashcard - -**P:** O que é um middleware no Express/Node.js e qual a assinatura da função? - -**R:** É uma função que intercepta o pipeline de requisição-resposta. Assinatura: `(req, res, next) => {}`. Deve chamar `next()` para continuar o fluxo ou enviar uma resposta para encerrá-lo. Middlewares de erro recebem `(err, req, res, next)`. +--- +title: "O que são e como funcionam middlewares no Node.js?" +category: backend +subcategory: node +tags: [middleware, express, nodejs, request, response] +difficulty: pleno +lang: pt +--- + +## Full Answer + +Middleware é uma função que fica no meio do ciclo de requisição-resposta. Ela recebe o objeto `req`, o objeto `res` e a função `next`, podendo executar código, modificar a requisição ou resposta, encerrar o ciclo ou passar o controle para o próximo middleware. + +``` +Requisição → middleware 1 → middleware 2 → rota → resposta +``` + +### Assinatura básica + +```js +function meuMiddleware(req, res, next) { + // faz alguma coisa + next() // passa para o próximo +} +``` + +Se `next()` não for chamado e a resposta também não for enviada, a requisição fica travada. + +### Tipos comuns + +**1. Middleware de aplicação** — executado em todas as rotas ou em rotas específicas: + +```js +// todas as rotas +app.use((req, res, next) => { + console.log(`${req.method} ${req.url}`) + next() +}) + +// apenas /admin +app.use('/admin', autenticar) +``` + +**2. Middleware de rota** — aplicado a uma rota específica: + +```js +app.get('/perfil', autenticar, (req, res) => { + res.json(req.usuario) +}) +``` + +**3. Middleware de erro** — possui quatro parâmetros; o Express identifica pelo `err` como primeiro argumento: + +```js +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).json({ erro: 'Algo deu errado' }) +}) +``` + +**4. Middleware de terceiros** — bibliotecas que se encaixam no pipeline: + +```js +import express from 'express' +import cors from 'cors' +import helmet from 'helmet' + +const app = express() + +app.use(helmet()) // cabeçalhos de segurança +app.use(cors()) // controle de origem +app.use(express.json()) // parse do body JSON +``` + +### Ordem importa + +O Express executa middlewares na ordem em que são registrados com `app.use()`. Um middleware de autenticação precisa vir antes das rotas protegidas; o middleware de erro precisa vir por último. + +```js +app.use(logger) // 1º — loga todas as requisições +app.use(autenticar) // 2º — bloqueia se não autenticado +app.get('/dados', handler) +app.use(tratarErros) // último — captura erros de toda a aplicação +``` + +### Exemplo completo: autenticação com JWT + +```js +function autenticar(req, res, next) { + const token = req.headers.authorization?.split(' ')[1] + + if (!token) { + return res.status(401).json({ erro: 'Token ausente' }) + } + + try { + req.usuario = jwt.verify(token, process.env.JWT_SECRET) + next() + } catch { + res.status(401).json({ erro: 'Token inválido' }) + } +} +``` + +## Quick Answer + +Middleware no Node.js (especialmente no Express) é uma função com acesso a `req`, `res` e `next` que intercepta o ciclo de requisição-resposta. Você os encadeia para separar responsabilidades como logging, autenticação e tratamento de erros — cada um faz sua parte e chama `next()` para passar o controle ao próximo. + +## Flashcard + +**P:** O que é um middleware no Express/Node.js e qual a assinatura da função? + +**R:** É uma função que intercepta o pipeline de requisição-resposta. Assinatura: `(req, res, next) => {}`. Deve chamar `next()` para continuar o fluxo ou enviar uma resposta para encerrá-lo. Middlewares de erro recebem `(err, req, res, next)`. diff --git a/src/content/pt/devops/containers/diferenca-docker-k8s.md b/src/content/pt/devops/containers/diferenca-docker-k8s.md index d3bc66f..10d5919 100644 --- a/src/content/pt/devops/containers/diferenca-docker-k8s.md +++ b/src/content/pt/devops/containers/diferenca-docker-k8s.md @@ -1,32 +1,32 @@ ---- -title: "Qual a diferença entre Docker e Kubernetes?" -category: devops -subcategory: containers -tags: [docker, kubernetes, k8s, containers, orquestração] -difficulty: intermediate -lang: pt ---- - -## Full Answer - -Docker e Kubernetes resolvem problemas diferentes, mas complementares. - -O Docker é uma plataforma para criar, empacotar e executar containers. Ele permite que aplicações rodem de forma isolada e consistente em diferentes ambientes. - -Já o Kubernetes (K8s) é uma plataforma de orquestração de containers. Ele gerencia múltiplos containers em escala, automatizando deploy, balanceamento de carga, escalabilidade, recuperação de falhas e gerenciamento de infraestrutura. - -Em resumo: -- Docker → cria e executa containers -- Kubernetes → gerencia containers em produção - -Normalmente, aplicações containerizadas com Docker são orquestradas pelo Kubernetes em ambientes distribuídos. - -## Quick Answer - -Docker é usado para criar e executar containers, enquanto Kubernetes é usado para orquestrar e gerenciar containers em escala. - -## Flashcard - -**P:** Qual a diferença entre Docker e Kubernetes? - -**R:** Docker cria e executa containers; Kubernetes gerencia e orquestra containers em ambientes distribuídos. \ No newline at end of file +--- +title: "Qual a diferença entre Docker e Kubernetes?" +category: devops +subcategory: containers +tags: [docker, kubernetes, k8s, containers, orquestração] +difficulty: pleno +lang: pt +--- + +## Full Answer + +Docker e Kubernetes resolvem problemas diferentes, mas complementares. + +O Docker é uma plataforma para criar, empacotar e executar containers. Ele permite que aplicações rodem de forma isolada e consistente em diferentes ambientes. + +Já o Kubernetes (K8s) é uma plataforma de orquestração de containers. Ele gerencia múltiplos containers em escala, automatizando deploy, balanceamento de carga, escalabilidade, recuperação de falhas e gerenciamento de infraestrutura. + +Em resumo: +- Docker → cria e executa containers +- Kubernetes → gerencia containers em produção + +Normalmente, aplicações containerizadas com Docker são orquestradas pelo Kubernetes em ambientes distribuídos. + +## Quick Answer + +Docker é usado para criar e executar containers, enquanto Kubernetes é usado para orquestrar e gerenciar containers em escala. + +## Flashcard + +**P:** Qual a diferença entre Docker e Kubernetes? + +**R:** Docker cria e executa containers; Kubernetes gerencia e orquestra containers em ambientes distribuídos. diff --git a/src/content/pt/devops/containers/o-que-e-docker.md b/src/content/pt/devops/containers/o-que-e-docker.md index b756177..8fa14d3 100644 --- a/src/content/pt/devops/containers/o-que-e-docker.md +++ b/src/content/pt/devops/containers/o-que-e-docker.md @@ -1,28 +1,28 @@ ---- -title: "O que é Docker?" -category: devops -subcategory: containers -tags: [docker, containers, virtualização] -difficulty: beginner -lang: pt ---- - -## Full Answer - -Docker é uma plataforma que permite criar, empacotar e executar aplicações em containers. - -Containers são ambientes leves e isolados que incluem tudo o que a aplicação precisa para funcionar, como código, bibliotecas e dependências. Isso garante que a aplicação rode da mesma forma em qualquer ambiente, seja localmente, em servidores ou na nuvem. - -O Docker facilita o desenvolvimento, testes e deploy de aplicações, reduzindo problemas de compatibilidade entre ambientes. - -Diferente de máquinas virtuais, containers compartilham o kernel do sistema operacional, tornando sua execução mais leve e rápida. - -## Quick Answer - -Docker é uma plataforma para criar e executar aplicações em containers, garantindo consistência entre ambientes. - -## Flashcard - -**P:** O que é Docker? - -**R:** Docker é uma plataforma que empacota aplicações em containers para execução isolada e consistente. \ No newline at end of file +--- +title: "O que é Docker?" +category: devops +subcategory: containers +tags: [docker, containers, virtualização] +difficulty: junior +lang: pt +--- + +## Full Answer + +Docker é uma plataforma que permite criar, empacotar e executar aplicações em containers. + +Containers são ambientes leves e isolados que incluem tudo o que a aplicação precisa para funcionar, como código, bibliotecas e dependências. Isso garante que a aplicação rode da mesma forma em qualquer ambiente, seja localmente, em servidores ou na nuvem. + +O Docker facilita o desenvolvimento, testes e deploy de aplicações, reduzindo problemas de compatibilidade entre ambientes. + +Diferente de máquinas virtuais, containers compartilham o kernel do sistema operacional, tornando sua execução mais leve e rápida. + +## Quick Answer + +Docker é uma plataforma para criar e executar aplicações em containers, garantindo consistência entre ambientes. + +## Flashcard + +**P:** O que é Docker? + +**R:** Docker é uma plataforma que empacota aplicações em containers para execução isolada e consistente. diff --git a/src/content/pt/devops/containers/o-que-e-k8s.md b/src/content/pt/devops/containers/o-que-e-k8s.md index 9606f9f..9f28d79 100644 --- a/src/content/pt/devops/containers/o-que-e-k8s.md +++ b/src/content/pt/devops/containers/o-que-e-k8s.md @@ -1,30 +1,30 @@ ---- -title: "O que é Kubernetes?" -category: devops -subcategory: orchestration -tags: [kubernetes, k8s, containers, orquestração] -difficulty: intermediate -lang: pt ---- - -## Full Answer - -Kubernetes, também conhecido como K8s, é uma plataforma de orquestração de containers. - -Ele automatiza o gerenciamento de aplicações containerizadas, permitindo realizar deploy, escalabilidade, balanceamento de carga, monitoramento e recuperação automática de falhas. - -O Kubernetes é muito utilizado em ambientes de produção porque facilita a execução de aplicações distribuídas em múltiplos servidores. - -Com ele, é possível garantir alta disponibilidade, escalar aplicações automaticamente e atualizar sistemas sem downtime significativo. - -Normalmente, o Kubernetes trabalha junto com tecnologias de containers, como Docker. - -## Quick Answer - -Kubernetes é uma plataforma que automatiza o gerenciamento e a orquestração de containers em ambientes distribuídos. - -## Flashcard - -**P:** O que é Kubernetes? - -**R:** Kubernetes é uma plataforma de orquestração de containers usada para automatizar deploy, escalabilidade e gerenciamento de aplicações. \ No newline at end of file +--- +title: "O que é Kubernetes?" +category: devops +subcategory: orchestration +tags: [kubernetes, k8s, containers, orquestração] +difficulty: pleno +lang: pt +--- + +## Full Answer + +Kubernetes, também conhecido como K8s, é uma plataforma de orquestração de containers. + +Ele automatiza o gerenciamento de aplicações containerizadas, permitindo realizar deploy, escalabilidade, balanceamento de carga, monitoramento e recuperação automática de falhas. + +O Kubernetes é muito utilizado em ambientes de produção porque facilita a execução de aplicações distribuídas em múltiplos servidores. + +Com ele, é possível garantir alta disponibilidade, escalar aplicações automaticamente e atualizar sistemas sem downtime significativo. + +Normalmente, o Kubernetes trabalha junto com tecnologias de containers, como Docker. + +## Quick Answer + +Kubernetes é uma plataforma que automatiza o gerenciamento e a orquestração de containers em ambientes distribuídos. + +## Flashcard + +**P:** O que é Kubernetes? + +**R:** Kubernetes é uma plataforma de orquestração de containers usada para automatizar deploy, escalabilidade e gerenciamento de aplicações. diff --git a/src/content/pt/devops/containers/quando-usar-containers-em-vez-de-vm.md b/src/content/pt/devops/containers/quando-usar-containers-em-vez-de-vm.md index d283c24..e7a4240 100644 --- a/src/content/pt/devops/containers/quando-usar-containers-em-vez-de-vm.md +++ b/src/content/pt/devops/containers/quando-usar-containers-em-vez-de-vm.md @@ -1,35 +1,35 @@ ---- -title: "Quando usar containers em vez de máquinas virtuais?" -category: devops -subcategory: containers -tags: [docker, containers, virtual-machines, infraestrutura] -difficulty: intermediate -lang: pt ---- - -## Full Answer - -Containers são mais indicados quando precisamos executar aplicações de forma leve, rápida e escalável. - -Um exemplo comum é uma aplicação web composta por frontend, backend e banco de dados. Em vez de criar uma máquina virtual completa para cada serviço, podemos executar cada parte em um container separado. - -Containers possuem menos overhead porque compartilham o kernel do sistema operacional, consumindo menos memória e iniciando mais rapidamente que máquinas virtuais. - -Eles também facilitam: -- Deploys rápidos -- Escalabilidade -- Integração com CI/CD -- Padronização entre ambientes -- Arquiteturas de microserviços - -Máquinas virtuais ainda são úteis quando é necessário isolamento mais forte ou executar sistemas operacionais diferentes no mesmo host. - -## Quick Answer - -Containers são preferíveis a máquinas virtuais quando precisamos de aplicações mais leves, rápidas e fáceis de escalar. - -## Flashcard - -**P:** Quando usar containers em vez de máquinas virtuais? - -**R:** Containers são ideais para aplicações leves e escaláveis, enquanto máquinas virtuais oferecem isolamento mais forte e suporte a múltiplos sistemas operacionais. \ No newline at end of file +--- +title: "Quando usar containers em vez de máquinas virtuais?" +category: devops +subcategory: containers +tags: [docker, containers, virtual-machines, infraestrutura] +difficulty: pleno +lang: pt +--- + +## Full Answer + +Containers são mais indicados quando precisamos executar aplicações de forma leve, rápida e escalável. + +Um exemplo comum é uma aplicação web composta por frontend, backend e banco de dados. Em vez de criar uma máquina virtual completa para cada serviço, podemos executar cada parte em um container separado. + +Containers possuem menos overhead porque compartilham o kernel do sistema operacional, consumindo menos memória e iniciando mais rapidamente que máquinas virtuais. + +Eles também facilitam: +- Deploys rápidos +- Escalabilidade +- Integração com CI/CD +- Padronização entre ambientes +- Arquiteturas de microserviços + +Máquinas virtuais ainda são úteis quando é necessário isolamento mais forte ou executar sistemas operacionais diferentes no mesmo host. + +## Quick Answer + +Containers são preferíveis a máquinas virtuais quando precisamos de aplicações mais leves, rápidas e fáceis de escalar. + +## Flashcard + +**P:** Quando usar containers em vez de máquinas virtuais? + +**R:** Containers são ideais para aplicações leves e escaláveis, enquanto máquinas virtuais oferecem isolamento mais forte e suporte a múltiplos sistemas operacionais. diff --git a/src/content/pt/frontend/accessibility/acessibilidade.md b/src/content/pt/frontend/accessibility/acessibilidade.md index 592a0b4..b0f61f3 100644 --- a/src/content/pt/frontend/accessibility/acessibilidade.md +++ b/src/content/pt/frontend/accessibility/acessibilidade.md @@ -1,103 +1,103 @@ ---- -title: "Como você abordaria a acessibilidade ao construir uma aplicação?" -category: frontend -subcategory: accessibility -tags: [acessibilidade, a11y, aria, wcag, html-semantico] -difficulty: intermediate -lang: pt ---- - -## Full Answer - -Acessibilidade (a11y) é a prática de construir interfaces utilizáveis por qualquer pessoa, incluindo quem usa leitores de tela, navega apenas pelo teclado ou tem baixa visão. A abordagem começa na base e avança em camadas: - -### 1. HTML Semântico - -Use as tags corretas para cada propósito. O browser e os leitores de tela entendem a semântica nativamente — sem nenhum atributo extra necessário. - -```html - -
Salvar
- - - -``` - -Tags como `