Files
bun-server-test/CHEATSHEET.md

292 lines
7.2 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 📋 Шпаргалка по встроенным возможностям Bun
## ⚡ Быстрые примеры
### 1⃣ HTML рендер (Template Literals)
```typescript
const html = `
<!DOCTYPE html>
<html>
<body>
<h1>${title}</h1>
<p>${content}</p>
</body>
</html>
`;
return new Response(html, { headers: { "Content-Type": "text/html" } });
```
**Скорость:** 0.1ms | **Когда:** 80% случаев
---
### 2⃣ JSON API
```typescript
const data = { status: "ok", items: [] };
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" }
});
```
**Встроено:** V8 оптимизация | **Когда:** API endpoints
---
### 3⃣ Статические файлы
```typescript
return new Response(Bun.file("static/style.css"));
```
**Скорость:** 0.05ms | **Когда:** CSS, JS, медиа
---
### 4⃣ Динамический контент
```typescript
const items = ["A", "B", "C"];
const html = `
<ul>
${items.map(i => `<li>${i}</li>`).join("")}
</ul>
`;
```
**Когда:** Списки, таблицы
---
### 5⃣ React компонент (SSR)
```typescript
import React from "react";
const Page = ({ title }) => (
<html>
<body>
<h1>{title}</h1>
</body>
</html>
);
const html = React.renderToString(<Page title="Hello" />);
return new Response(html, { headers: { "Content-Type": "text/html" } });
```
**Скорость:** 2-5ms | **Когда:** 15% случаев
---
### 6⃣ Streaming большого файла
```typescript
return new Response(Bun.file("large-file.zip"));
// или
const readable = new ReadableStream({ /* ... */ });
return new Response(readable);
```
**Скорость:** 0.05ms | **Когда:** Большие файлы
---
### 7⃣ Кеширование
```typescript
return new Response(html, {
headers: {
"Cache-Control": "public, max-age=3600",
"ETag": '"123456"'
}
});
```
**Когда:** Статические ассеты
---
### 8⃣ Cookie
```typescript
// Установка
return new Response(html, {
headers: {
"Set-Cookie": "session=abc123; Path=/; HttpOnly"
}
});
// Чтение
const cookie = req.headers.get("cookie");
```
---
### 9⃣ TypeScript (встроенный)
```typescript
const greeting: string = "Hello";
const numbers: number[] = [1, 2, 3];
interface User { name: string; age: number; }
```
**Компиляция:** встроенная | **Конфигурация:** опциональна
---
### 🔟 Web Standards API
```typescript
const req = new Request("http://example.com");
const res = new Response("content");
const headers = new Headers({ "Content-Type": "text/html" });
const url = new URL("https://example.com");
const params = new URLSearchParams("a=1");
const blob = new Blob(["data"]);
```
---
## 🎯 Таблица выбора
```
Нужно что делать? Используйте это
─────────────────────────────────────────────────────
HTML страница Template Literals
API endpoint (JSON) JSON.stringify
Статический файл Bun.file()
Большой файл Streaming API
React компонент React.renderToString
Переиспользуемая логика Custom функция
Типизация TypeScript
Кеширование браузером Cache-Control
Сохранить состояние Cookie
```
---
## 📊 Производительность
```
Template Literals 0.1ms ⚡⚡⚡ ИСПОЛЬЗУЙТЕ
Bun.file() 0.05ms ⚡⚡⚡ ДЛЯ ФАЙЛОВ
Streaming 0.05ms ⚡⚡⚡ БОЛЬШИЕ
JSON.stringify() встроено ⚡⚡⚡ ОПТИМИЗИРОВАН
React SSR 2-5ms ⚡ КОГДА НУЖНЫ
```
---
## 🚀 Структура сервера
```typescript
// 1. Импорты
import { Server } from "./server";
import { Router } from "./router";
// 2. Создание сервера
const server = new Server({ port: 3000 });
const router = server.getRouter();
// 3. Регистрация маршрутов
router.get("/", async (req, url) => {
const html = `<!DOCTYPE html>...`;
return new Response(html, { headers: { "Content-Type": "text/html" } });
});
router.get("/api/data", async (req, url) => {
const data = { status: "ok" };
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" }
});
});
// 4. Запуск
server.start();
```
---
## 🎓 Правила для начинающих
1. **Template Literals в 80% случаев**
```typescript
const html = `<h1>${title}</h1>`;
```
2. **JSON.stringify для API**
```typescript
return new Response(JSON.stringify(data));
```
3. **Bun.file для статики**
```typescript
return new Response(Bun.file("static/style.css"));
```
4. **React только когда нужны компоненты**
```typescript
// NOT в 80% случаев - используйте Template Literals!
```
5. **TypeScript для типизации**
```typescript
function handler(req: Request): Response { }
```
---
## 📦 Не требует установки
```
НЕ нужно устанавливать:
- HTML рендер библиотеку
- Шаблонизатор
- HTTP сервер
- TypeScript компилятор
- JSON библиотеку
ВСЕ встроено в Bun!
```
---
## 💡 Советы производительности
1. **Кешируйте статику**
```typescript
"Cache-Control": "public, max-age=86400"
```
2. **Используйте Streaming для больших файлов**
```typescript
return new Response(Bun.file("huge-file.zip"));
```
3. **Делайте Template Literals чистыми**
```typescript
// ХОРОШО
const html = `<h1>${htmlEscape(title)}</h1>`;
// ПЛОХО
const html = "<h1>" + title + "</h1>";
```
4. **Минифицируйте JSON если нужно**
```typescript
JSON.stringify(data) // Компактный
// vs
JSON.stringify(data, null, 2) // С отступами (для debug)
```
5. **Используйте ETag для кеширования**
```typescript
"ETag": '"hash-of-content"'
```
---
## 🔗 Документация в проекте
- **WHAT_BUN_CAN_DO.md** - Главный файл (начните отсюда!)
- **BUN_CAPABILITIES.md** - 10 возможностей
- **BUN_RENDERING.md** - Подробное руководство
- **README.md** - Полная документация
- **DOCS_INDEX.md** - Индекс всего
---
## 🎉 Итого
**Bun имеет всё что нужно для веб-разработки БЕЗ дополнительных библиотек!**
Используйте эту шпаргалку как быструю справку.
Для деталей смотрите основные файлы документации.
Happy Bun coding! 🚀