@hexlet/frontend-blog-server 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -2
- package/contract/main.tsp +286 -0
- package/contract/openapi.yaml +781 -0
- package/dist/bin/cli.d.ts +2 -0
- package/dist/bin/cli.js +63 -0
- package/dist/src/app.d.ts +6 -0
- package/dist/src/app.js +256 -0
- package/dist/src/generated/api.d.ts +911 -0
- package/dist/src/generated/api.js +5 -0
- package/dist/src/seed.d.ts +9 -0
- package/dist/src/seed.js +189 -0
- package/dist/src/state.d.ts +58 -0
- package/dist/src/state.js +81 -0
- package/package.json +50 -4
package/dist/bin/cli.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { cpSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { cac } from "cac";
|
|
8
|
+
const require = createRequire(import.meta.url);
|
|
9
|
+
const here = dirname(fileURLToPath(import.meta.url)); // dist/bin
|
|
10
|
+
const pkgRoot = resolve(here, "..", ".."); // корень пакета (dist/bin → ..)
|
|
11
|
+
const cli = cac("frontend-blog-server");
|
|
12
|
+
// --- start: поднять API-сервер (+ опционально раздавать собранный SPA) ---
|
|
13
|
+
cli
|
|
14
|
+
.command("start", "запустить API-сервер (опционально раздавать SPA из каталога)")
|
|
15
|
+
.option("-a, --address <address>", "host to listen on", { default: "0.0.0.0" })
|
|
16
|
+
.option("-p, --port <port>", "port to listen on", { default: process.env.PORT ?? "8080" })
|
|
17
|
+
.option("-s, --static <dir>", "serve a built SPA from <dir> with SPA fallback")
|
|
18
|
+
.action((options) => {
|
|
19
|
+
// Запуск через Fastify CLI (программно): резолвим бинарь fastify-cli и стартуем плагин.
|
|
20
|
+
const pkgPath = require.resolve("fastify-cli/package.json");
|
|
21
|
+
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
|
|
22
|
+
const binRel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin.fastify;
|
|
23
|
+
const fastifyCli = join(dirname(pkgPath), binRel);
|
|
24
|
+
const appPath = join(here, "..", "src", "app.js"); // dist/bin → dist/src/app.js
|
|
25
|
+
const env = { ...process.env };
|
|
26
|
+
if (options.static)
|
|
27
|
+
env.SPA_DIR = resolve(process.cwd(), options.static);
|
|
28
|
+
const child = spawn(process.execPath, [
|
|
29
|
+
fastifyCli,
|
|
30
|
+
"start",
|
|
31
|
+
"-l",
|
|
32
|
+
"info",
|
|
33
|
+
"-a",
|
|
34
|
+
options.address,
|
|
35
|
+
"-p",
|
|
36
|
+
String(options.port),
|
|
37
|
+
appPath,
|
|
38
|
+
], { stdio: "inherit", env });
|
|
39
|
+
child.on("exit", (code) => process.exit(code ?? 0));
|
|
40
|
+
});
|
|
41
|
+
// --- contract: извлечь контракт API (TypeSpec + OpenAPI), запечённый в пакет ---
|
|
42
|
+
cli
|
|
43
|
+
.command("contract [dir]", "извлечь контракт API (openapi.yaml + main.tsp) в каталог (по умолчанию ./contract)")
|
|
44
|
+
.action((dir) => {
|
|
45
|
+
const srcDir = join(pkgRoot, "contract");
|
|
46
|
+
const outDir = resolve(process.cwd(), dir ?? "contract");
|
|
47
|
+
if (!existsSync(srcDir)) {
|
|
48
|
+
console.error("Контракт не найден в пакете @hexlet/frontend-blog-server. Обновите пакет до свежей версии.");
|
|
49
|
+
process.exit(1);
|
|
50
|
+
}
|
|
51
|
+
mkdirSync(outDir, { recursive: true });
|
|
52
|
+
const files = ["openapi.yaml", "main.tsp"];
|
|
53
|
+
for (const file of files) {
|
|
54
|
+
const from = join(srcDir, file);
|
|
55
|
+
if (existsSync(from)) {
|
|
56
|
+
cpSync(from, join(outDir, file));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
console.log(`Контракт скопирован в ${outDir}: ${files.join(", ")}.`);
|
|
60
|
+
console.log("openapi.yaml — OpenAPI 3 (генерируется из TypeSpec main.tsp). Это источник правды по API.");
|
|
61
|
+
});
|
|
62
|
+
cli.help();
|
|
63
|
+
cli.parse();
|
package/dist/src/app.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import fastifyStatic from "@fastify/static";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { createState, verifyPassword, } from "./state.js";
|
|
6
|
+
const credentialsSchema = z.object({
|
|
7
|
+
username: z
|
|
8
|
+
.string()
|
|
9
|
+
.regex(/^[A-Za-z0-9_-]{3,20}$/, "username must be 3-20 chars of A-Z, a-z, 0-9, _ or -"),
|
|
10
|
+
password: z.string().min(6, "password must be at least 6 chars"),
|
|
11
|
+
});
|
|
12
|
+
const articleSchema = z.object({
|
|
13
|
+
title: z
|
|
14
|
+
.string()
|
|
15
|
+
.trim()
|
|
16
|
+
.min(1, "title must not be empty")
|
|
17
|
+
.max(120, "title must be at most 120 chars"),
|
|
18
|
+
body: z.string().trim().min(1, "body must not be empty"),
|
|
19
|
+
categoryId: z.number().int(),
|
|
20
|
+
});
|
|
21
|
+
const listQuerySchema = z.object({
|
|
22
|
+
page: z.coerce.number().int().min(1).default(1),
|
|
23
|
+
perPage: z.coerce.number().int().min(1).max(50).default(10),
|
|
24
|
+
category: z.string().optional(),
|
|
25
|
+
author: z.string().optional(),
|
|
26
|
+
});
|
|
27
|
+
const commentSchema = z.object({
|
|
28
|
+
body: z.string().trim().min(1, "body must not be empty"),
|
|
29
|
+
parentId: z.number().int().nullish(),
|
|
30
|
+
});
|
|
31
|
+
const fail = (reply, status, code, message) => {
|
|
32
|
+
reply.status(status);
|
|
33
|
+
return { code, message };
|
|
34
|
+
};
|
|
35
|
+
const issuesText = (error) => error.issues.map((issue) => issue.message).join("; ");
|
|
36
|
+
const app = async (fastify, options) => {
|
|
37
|
+
const state = createState();
|
|
38
|
+
// Собранный SPA из опции плагина (тесты) или из SPA_DIR (CLI `start -s`). Фронтенд и API
|
|
39
|
+
// живут на одном origin, поэтому CORS не нужен: в разработке запросы проксирует дев-сервер.
|
|
40
|
+
const staticDir = options.staticDir ?? process.env.SPA_DIR;
|
|
41
|
+
const root = staticDir ? resolve(process.cwd(), staticDir) : undefined;
|
|
42
|
+
if (root && !existsSync(root))
|
|
43
|
+
fastify.log.warn(`SPA directory ${root} not found, serving API only`);
|
|
44
|
+
const serveSpa = root !== undefined && existsSync(root);
|
|
45
|
+
if (serveSpa)
|
|
46
|
+
await fastify.register(fastifyStatic, { root, prefix: "/" });
|
|
47
|
+
fastify.setNotFoundHandler((request, reply) => {
|
|
48
|
+
if (serveSpa && !request.raw.url?.startsWith("/api")) {
|
|
49
|
+
reply.sendFile("index.html");
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
reply.status(404).send({ code: "not_found", message: "Resource not found" });
|
|
53
|
+
});
|
|
54
|
+
const currentUser = (request) => {
|
|
55
|
+
const [scheme, token] = (request.headers.authorization ?? "").split(" ");
|
|
56
|
+
if (scheme !== "Bearer" || !token)
|
|
57
|
+
return undefined;
|
|
58
|
+
const id = state.tokens.get(token);
|
|
59
|
+
return state.users.find((user) => user.id === id);
|
|
60
|
+
};
|
|
61
|
+
const publicUser = (id) => {
|
|
62
|
+
const { username } = state.users.find((user) => user.id === id);
|
|
63
|
+
return { id, username };
|
|
64
|
+
};
|
|
65
|
+
const likesCount = (articleId) => [...state.likes].filter((key) => key.startsWith(`${articleId}:`)).length;
|
|
66
|
+
const summary = (article) => ({
|
|
67
|
+
id: article.id,
|
|
68
|
+
title: article.title,
|
|
69
|
+
excerpt: article.body
|
|
70
|
+
.replace(/```[\s\S]*?```/g, "")
|
|
71
|
+
.replace(/[#*_`>[\]()-]/g, "")
|
|
72
|
+
.replace(/\s+/g, " ")
|
|
73
|
+
.trim()
|
|
74
|
+
.slice(0, 200),
|
|
75
|
+
category: state.categories.find((c) => c.id === article.categoryId),
|
|
76
|
+
author: publicUser(article.authorId),
|
|
77
|
+
createdAt: article.createdAt.toISOString(),
|
|
78
|
+
likesCount: likesCount(article.id),
|
|
79
|
+
commentsCount: state.comments.filter((c) => c.articleId === article.id).length,
|
|
80
|
+
});
|
|
81
|
+
const full = (article, viewer) => ({
|
|
82
|
+
...summary(article),
|
|
83
|
+
body: article.body,
|
|
84
|
+
updatedAt: article.updatedAt.toISOString(),
|
|
85
|
+
liked: viewer ? state.likes.has(`${article.id}:${viewer.id}`) : false,
|
|
86
|
+
});
|
|
87
|
+
const commentView = ({ id, body, parentId, authorId, createdAt, }) => ({
|
|
88
|
+
id,
|
|
89
|
+
body,
|
|
90
|
+
parentId,
|
|
91
|
+
author: publicUser(authorId),
|
|
92
|
+
createdAt: createdAt.toISOString(),
|
|
93
|
+
});
|
|
94
|
+
const findArticle = (id) => state.articles.find((article) => article.id === Number(id));
|
|
95
|
+
fastify.get("/api/health", async () => ({ status: "ok" }));
|
|
96
|
+
fastify.post("/api/users", async (request, reply) => {
|
|
97
|
+
const parsed = credentialsSchema.safeParse(request.body);
|
|
98
|
+
if (!parsed.success)
|
|
99
|
+
return fail(reply, 400, "validation_error", issuesText(parsed.error));
|
|
100
|
+
const { username, password } = parsed.data;
|
|
101
|
+
if (state.users.some((user) => user.username.toLowerCase() === username.toLowerCase())) {
|
|
102
|
+
return fail(reply, 409, "username_taken", `${username} is taken`);
|
|
103
|
+
}
|
|
104
|
+
const user = state.addUser(username, password);
|
|
105
|
+
reply.status(201);
|
|
106
|
+
return { token: state.issueToken(user), user: publicUser(user.id) };
|
|
107
|
+
});
|
|
108
|
+
fastify.get("/api/users/:username", async (request, reply) => {
|
|
109
|
+
const user = state.users.find((item) => item.username === request.params.username);
|
|
110
|
+
if (!user)
|
|
111
|
+
return fail(reply, 404, "not_found", "User not found");
|
|
112
|
+
return {
|
|
113
|
+
...publicUser(user.id),
|
|
114
|
+
articlesCount: state.articles.filter((article) => article.authorId === user.id).length,
|
|
115
|
+
};
|
|
116
|
+
});
|
|
117
|
+
fastify.post("/api/session", async (request, reply) => {
|
|
118
|
+
const parsed = z.object({ username: z.string(), password: z.string() }).safeParse(request.body);
|
|
119
|
+
if (!parsed.success)
|
|
120
|
+
return fail(reply, 400, "validation_error", issuesText(parsed.error));
|
|
121
|
+
const user = state.users.find((item) => item.username === parsed.data.username);
|
|
122
|
+
if (!user || !verifyPassword(parsed.data.password, user.passwordHash)) {
|
|
123
|
+
return fail(reply, 401, "invalid_credentials", "Wrong username or password");
|
|
124
|
+
}
|
|
125
|
+
return { token: state.issueToken(user), user: publicUser(user.id) };
|
|
126
|
+
});
|
|
127
|
+
fastify.get("/api/me", async (request, reply) => {
|
|
128
|
+
const user = currentUser(request);
|
|
129
|
+
if (!user)
|
|
130
|
+
return fail(reply, 401, "unauthorized", "Sign in required");
|
|
131
|
+
return publicUser(user.id);
|
|
132
|
+
});
|
|
133
|
+
fastify.get("/api/categories", async () => state.categories);
|
|
134
|
+
fastify.get("/api/articles", async (request, reply) => {
|
|
135
|
+
const parsed = listQuerySchema.safeParse(request.query);
|
|
136
|
+
if (!parsed.success)
|
|
137
|
+
return fail(reply, 400, "validation_error", issuesText(parsed.error));
|
|
138
|
+
const { page, perPage, category, author } = parsed.data;
|
|
139
|
+
const categoryId = state.categories.find((c) => c.slug === category)?.id;
|
|
140
|
+
const authorId = state.users.find((u) => u.username === author)?.id;
|
|
141
|
+
const matched = state.articles
|
|
142
|
+
.filter((a) => category === undefined || a.categoryId === categoryId)
|
|
143
|
+
.filter((a) => author === undefined || a.authorId === authorId)
|
|
144
|
+
.toSorted((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.id - a.id);
|
|
145
|
+
return {
|
|
146
|
+
items: matched.slice((page - 1) * perPage, page * perPage).map(summary),
|
|
147
|
+
page,
|
|
148
|
+
perPage,
|
|
149
|
+
total: matched.length,
|
|
150
|
+
};
|
|
151
|
+
});
|
|
152
|
+
fastify.get("/api/articles/:id", async (request, reply) => {
|
|
153
|
+
const article = findArticle(request.params.id);
|
|
154
|
+
if (!article)
|
|
155
|
+
return fail(reply, 404, "not_found", "Article not found");
|
|
156
|
+
return full(article, currentUser(request));
|
|
157
|
+
});
|
|
158
|
+
fastify.post("/api/articles", async (request, reply) => {
|
|
159
|
+
const user = currentUser(request);
|
|
160
|
+
if (!user)
|
|
161
|
+
return fail(reply, 401, "unauthorized", "Sign in required");
|
|
162
|
+
const parsed = articleSchema.safeParse(request.body);
|
|
163
|
+
if (!parsed.success)
|
|
164
|
+
return fail(reply, 400, "validation_error", issuesText(parsed.error));
|
|
165
|
+
const { title, body, categoryId } = parsed.data;
|
|
166
|
+
if (!state.categories.some((c) => c.id === categoryId)) {
|
|
167
|
+
return fail(reply, 400, "validation_error", "unknown categoryId");
|
|
168
|
+
}
|
|
169
|
+
reply.status(201);
|
|
170
|
+
return full(state.addArticle(user.id, categoryId, title, body), user);
|
|
171
|
+
});
|
|
172
|
+
// Общая проверка для правки и удаления: статья есть, пользователь вошёл и он автор.
|
|
173
|
+
const ownArticle = (request, reply) => {
|
|
174
|
+
const user = currentUser(request);
|
|
175
|
+
if (!user)
|
|
176
|
+
return { error: fail(reply, 401, "unauthorized", "Sign in required") };
|
|
177
|
+
const article = findArticle(request.params.id);
|
|
178
|
+
if (!article)
|
|
179
|
+
return { error: fail(reply, 404, "not_found", "Article not found") };
|
|
180
|
+
if (article.authorId !== user.id)
|
|
181
|
+
return { error: fail(reply, 403, "forbidden", "Only the author can do this") };
|
|
182
|
+
return { user, article };
|
|
183
|
+
};
|
|
184
|
+
fastify.patch("/api/articles/:id", async (request, reply) => {
|
|
185
|
+
const own = ownArticle(request, reply);
|
|
186
|
+
if (own.error)
|
|
187
|
+
return own.error;
|
|
188
|
+
const parsed = articleSchema.partial().safeParse(request.body);
|
|
189
|
+
if (!parsed.success)
|
|
190
|
+
return fail(reply, 400, "validation_error", issuesText(parsed.error));
|
|
191
|
+
const { categoryId } = parsed.data;
|
|
192
|
+
if (categoryId !== undefined && !state.categories.some((c) => c.id === categoryId)) {
|
|
193
|
+
return fail(reply, 400, "validation_error", "unknown categoryId");
|
|
194
|
+
}
|
|
195
|
+
Object.assign(own.article, parsed.data, { updatedAt: new Date() });
|
|
196
|
+
return full(own.article, own.user);
|
|
197
|
+
});
|
|
198
|
+
fastify.delete("/api/articles/:id", async (request, reply) => {
|
|
199
|
+
const own = ownArticle(request, reply);
|
|
200
|
+
if (own.error)
|
|
201
|
+
return own.error;
|
|
202
|
+
const { id } = own.article;
|
|
203
|
+
state.articles.splice(state.articles.indexOf(own.article), 1);
|
|
204
|
+
for (let i = state.comments.length - 1; i >= 0; i -= 1) {
|
|
205
|
+
if (state.comments[i].articleId === id)
|
|
206
|
+
state.comments.splice(i, 1);
|
|
207
|
+
}
|
|
208
|
+
for (const key of state.likes)
|
|
209
|
+
if (key.startsWith(`${id}:`))
|
|
210
|
+
state.likes.delete(key);
|
|
211
|
+
reply.status(204);
|
|
212
|
+
return null;
|
|
213
|
+
});
|
|
214
|
+
fastify.get("/api/articles/:id/comments", async (request, reply) => {
|
|
215
|
+
const article = findArticle(request.params.id);
|
|
216
|
+
if (!article)
|
|
217
|
+
return fail(reply, 404, "not_found", "Article not found");
|
|
218
|
+
return state.comments.filter((comment) => comment.articleId === article.id).map(commentView);
|
|
219
|
+
});
|
|
220
|
+
fastify.post("/api/articles/:id/comments", async (request, reply) => {
|
|
221
|
+
const user = currentUser(request);
|
|
222
|
+
if (!user)
|
|
223
|
+
return fail(reply, 401, "unauthorized", "Sign in required");
|
|
224
|
+
const article = findArticle(request.params.id);
|
|
225
|
+
if (!article)
|
|
226
|
+
return fail(reply, 404, "not_found", "Article not found");
|
|
227
|
+
const parsed = commentSchema.safeParse(request.body);
|
|
228
|
+
if (!parsed.success)
|
|
229
|
+
return fail(reply, 400, "validation_error", issuesText(parsed.error));
|
|
230
|
+
const parentId = parsed.data.parentId ?? null;
|
|
231
|
+
if (parentId !== null &&
|
|
232
|
+
!state.comments.some((c) => c.id === parentId && c.articleId === article.id)) {
|
|
233
|
+
return fail(reply, 400, "validation_error", "parentId must be a comment of the same article");
|
|
234
|
+
}
|
|
235
|
+
const comment = state.addComment(article.id, user.id, parsed.data.body, parentId);
|
|
236
|
+
reply.status(201);
|
|
237
|
+
return commentView(comment);
|
|
238
|
+
});
|
|
239
|
+
const setLike = (liked) => async (request, reply) => {
|
|
240
|
+
const user = currentUser(request);
|
|
241
|
+
if (!user)
|
|
242
|
+
return fail(reply, 401, "unauthorized", "Sign in required");
|
|
243
|
+
const article = findArticle(request.params.id);
|
|
244
|
+
if (!article)
|
|
245
|
+
return fail(reply, 404, "not_found", "Article not found");
|
|
246
|
+
const key = `${article.id}:${user.id}`;
|
|
247
|
+
if (liked)
|
|
248
|
+
state.likes.add(key);
|
|
249
|
+
else
|
|
250
|
+
state.likes.delete(key);
|
|
251
|
+
return { liked, likesCount: likesCount(article.id) };
|
|
252
|
+
};
|
|
253
|
+
fastify.put("/api/articles/:id/like", setLike(true));
|
|
254
|
+
fastify.delete("/api/articles/:id/like", setLike(false));
|
|
255
|
+
};
|
|
256
|
+
export default app;
|