Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@

Устройство короткое: четыре спецификации на TypeSpec (`typespec/<app>/`, по одной на курс) компилируются в OpenAPI, а маршруты, валидацию и авторизацию строит из них `fastify-openapi-glue`. Руками написаны только данные и то, что в OpenAPI не выражается. Значит документация и поведение разъехаться не могут: студент читает ту же спецификацию, по которой работает сервер.

## Примеры форматов тела

Урок `body-formats` курса HTTP для автоматизации использует следующие адреса. Обработчики показывают полученные данные без сохранения задач.

| Метод и путь | Результат |
| --- | --- |
| `GET /http-protocol/form` | HTML-форма с полями `title` и `description` |
| `POST /http-protocol/form` | Полученные значения обоих полей обычным текстом |
| `POST /http-protocol/body` | JSON с заголовками запроса и данными в `json`, `form` или `files` |
| `GET /http-protocol/image.png` | Файл PNG размером 8090 байтов |

Обработчик `body` принимает JSON, `application/x-www-form-urlencoded` и multipart. Для примера с файлом он возвращает его содержимое как строку UTF-8. Лимиты multipart допускают один файл до 64 КиБ и до десяти текстовых полей по 4 КиБ. Исходное тестовое изображение взято из [httpbin](https://httpbin.org/image/png), который распространяется под [лицензией MIT](https://github.com/postmanlabs/httpbin/blob/master/LICENSE).

## Prerequisites

- Make
Expand Down
73 changes: 73 additions & 0 deletions bin/body-smoke-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
export default async function checkBodyExamples({ APP, check, getJson }) {
console.log("\nФорматы тела учебных запросов");
const fields = { title: "Check the automation task", description: "Review the test request" };
const formPage = await fetch(`${APP}/http-protocol/form`);
const formHtml = await formPage.text();
check(
"форма доступна и задаёт имена обоих полей",
formPage.status === 200 &&
formHtml.includes('name="title"') &&
formHtml.includes('name="description"'),
);
const formReply = await fetch(`${APP}/http-protocol/form`, {
method: "POST",
body: new URLSearchParams(fields),
});
check(
"браузерная форма возвращает прочитанные значения",
formReply.status === 200 &&
(await formReply.text()) === `title=${fields.title}\ndescription=${fields.description}\n`,
);
const jsonReply = await getJson(`${APP}/http-protocol/body`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ ...fields, priority: 2, urgent: false }),
});
check(
"JSON сохраняет типы и отражает заголовки",
jsonReply.status === 200 &&
jsonReply.body.json.priority === 2 &&
jsonReply.body.json.urgent === false &&
jsonReply.body.headers.Accept === "application/json",
);
const encodedReply = await getJson(`${APP}/http-protocol/body`, {
method: "POST",
body: new URLSearchParams(fields),
});
check(
"кодированные поля декодируются с пробелами",
encodedReply.status === 200 &&
encodedReply.body.form.title === fields.title &&
encodedReply.body.json === null,
);
const multipartBody = new FormData();
multipartBody.set("title", fields.title);
multipartBody.set(
"attachment",
new Blob(["Please check the automation task\n"], {
type: "text/plain",
}),
"http-body-note.txt",
);
const multipartReply = await getJson(`${APP}/http-protocol/body`, {
method: "POST",
body: multipartBody,
});
check(
"multipart передаёт содержимое файла и текстовое поле",
multipartReply.status === 200 &&
multipartReply.body.form.title === fields.title &&
multipartReply.body.files.attachment === "Please check the automation task\n" &&
multipartReply.body.headers["Content-Type"].includes("boundary="),
);
const imageReply = await fetch(`${APP}/http-protocol/image.png`);
const imageData = new Uint8Array(await imageReply.arrayBuffer());
check(
"PNG имеет заявленный размер и сигнатуру",
imageReply.status === 200 &&
imageReply.headers.get("Content-Type").startsWith("image/png") &&
Number(imageReply.headers.get("Content-Length")) === imageData.length &&
imageData.length === 8090 &&
imageData.slice(0, 8).join(",") === "137,80,78,71,13,10,26,10",
);
}
3 changes: 3 additions & 0 deletions bin/smoke-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { readFileSync } from 'node:fs';
import checkBodyExamples from './body-smoke-test.js';

import expectedComments from '../custom-server/src/data/comments.js';
import expectedCourses from '../custom-server/src/data/courses.js';
Expand Down Expand Up @@ -157,6 +158,8 @@ const run = async () => {

await waitFor(`${APP}/`, 'приложение');

await checkBodyExamples({ APP, check, getJson });

console.log('\nREST и RPC отдают одни и те же задачи');
const restList = await getJson(TASKS);
const rpcList = await rpc('tasks.list', {});
Expand Down
32 changes: 32 additions & 0 deletions custom-server/assets/http-protocol/form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTTP Form</title>
<style>
body { font: 18px/1.5 system-ui, sans-serif; margin: 40px auto; padding: 0 24px; max-width: 620px; color: #18212d; }
h1 { font-size: 30px; }
label { display: block; margin: 24px 0; }
input, textarea { display: block; box-sizing: border-box; width: 100%; margin-top: 8px; padding: 12px; font: inherit; border: 1px solid #9ca6b4; border-radius: 6px; }
textarea { min-height: 100px; resize: vertical; }
button { padding: 10px 24px; font: inherit; color: white; background: #315acc; border: 0; border-radius: 6px; cursor: pointer; }
a { color: #315acc; }
</style>
</head>
<body>
<a href="/http-protocol">HTTP examples</a>
<h1>Send task details</h1>
<form action="/http-protocol/form" method="post">
<label>
Title
<input name="title" value="Check the automation task" />
</label>
<label>
Description
<textarea name="description">Review the test request</textarea>
</label>
<button type="submit">Send</button>
</form>
</body>
</html>
Binary file added custom-server/assets/http-protocol/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions custom-server/assets/http-protocol/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ <h1>It works!</h1>
<li><a href="/http-protocol/example">Example</a></li>
<li><a href="/http-protocol/removed">Redirect</a></li>
<li><a href="/http-protocol/stream">Stream</a></li>
<li><a href="/http-protocol/form">HTML form</a></li>
<li><a href="/http-protocol/image.png">PNG image</a></li>
</ul>
</body>
</html>
1 change: 1 addition & 0 deletions custom-server/assets/main/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ <h1>It works!</h1>
<ul>
<li><a href="/http-api-openapi">HTTP API</a></li>
<li><a href="/http-protocol-openapi">HTTP Protocol</a></li>
<li><a href="/http-protocol/form">HTTP Form</a></li>
<li><a href="/js-playwright-openapi">JS Playwright</a></li>
<li><a href="/postman-openapi">Postman</a></li>
</ul>
Expand Down
39 changes: 39 additions & 0 deletions custom-server/src/body-examples.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import multipart from "@fastify/multipart";

// Изолированный учебный обработчик отражает данные без изменения коллекций.
export default async function setUpBodyExamples(app) {
await app.register(multipart, {
limits: { files: 1, fields: 10, parts: 11, fileSize: 65536, fieldSize: 4096 },
});

app.get("/http-protocol/form", (_req, res) => res.sendFile("http-protocol/form.html"));
app.post("/http-protocol/form", (req, res) => {
const { title = "", description = "" } = req.body ?? {};
return res
.type("text/plain; charset=utf-8")
.send(`title=${title}\ndescription=${description}\n`);
});

app.get("/http-protocol/image.png", (_req, res) => res.sendFile("http-protocol/image.png"));

app.post("/http-protocol/body", async (req) => {
const headers = { "Content-Type": req.headers["content-type"] };
if (req.headers.accept) headers.Accept = req.headers.accept;
const result = { headers, json: null, form: Object.create(null), files: Object.create(null) };
if (req.isMultipart()) {
for await (const part of req.parts()) {
if (part.type === "file") {
const data = await part.toBuffer();
result.files[part.fieldname] = data.toString("utf8");
} else {
result.form[part.fieldname] = part.value;
}
}
} else if (req.headers["content-type"]?.startsWith("application/json")) {
result.json = req.body;
} else {
result.form = req.body ?? {};
}
return result;
});
}
3 changes: 3 additions & 0 deletions custom-server/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import fastifyCookie from '@fastify/cookie';

import appConfig from '../../app.config.json' with {type: 'json'}
import setUpRpc from './rpc.js';
import setUpBodyExamples from './body-examples.js';
import setUpSpec from './openapi-spec.ts';

const { dirname } = import.meta;
Expand Down Expand Up @@ -95,6 +96,8 @@ export default async (app, _options) => {
});
setUpStaticAssets(app);

await app.register(setUpBodyExamples);

await setupDocs(app);

app.get('/http-protocol/example', (req, res) => {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"dependencies": {
"@fastify/cookie": "^11.1.2",
"@fastify/formbody": "^9.0.0",
"@fastify/multipart": "^10.1.3",
"@fastify/static": "^10.1.5",
"@fastify/swagger": "^9.9.0",
"@fastify/swagger-ui": "^6.1.1",
Expand Down
19 changes: 19 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading