Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x | import { AppError } from "@ontrack/backend-common";
import type { FastifyPluginAsync } from "fastify";
import type { AppConfig } from "../config.js";
import { requireVerifiedUser, type IdTokenVerifier } from "../lib/firebase-auth.js";
import { proxyJsonRequest, proxyUpstreamGetRaw, throwIfUpstreamFailed } from "../lib/http-client.js";
const bikeBodySchema = {
type: "object",
required: ["brand", "model", "name"],
additionalProperties: false,
properties: {
brand: { type: "string", minLength: 1, maxLength: 80 },
model: { type: "string", minLength: 1, maxLength: 80 },
name: { type: "string", minLength: 1, maxLength: 80 },
description: { type: ["string", "null"], maxLength: 1000 },
},
} as const;
const bikeIdParamSchema = {
type: "object",
required: ["bikeId"],
additionalProperties: false,
properties: {
bikeId: { type: "string", pattern: "^[1-9][0-9]*$" },
},
} as const;
/** Велосипеды текущего пользователя. uid берётся из ID-токена. */
export const bikesRoutes: FastifyPluginAsync<{
config: AppConfig;
verifyIdToken: IdTokenVerifier;
}> = async (app, opts) => {
const { config, verifyIdToken } = opts;
function userHeaders(uid: string): Record<string, string> {
return { "x-service-token": config.serviceToken, "x-user-uid": uid };
}
app.get("/bikes", async (request) => {
const user = await requireVerifiedUser(request, verifyIdToken);
return proxyJsonRequest<unknown>({
method: "GET",
url: `${config.catalogServiceUrl}/bikes`,
headers: userHeaders(user.uid),
timeoutMs: config.upstreamTimeoutMs,
});
});
app.post("/bikes", { schema: { body: bikeBodySchema } }, async (request) => {
const user = await requireVerifiedUser(request, verifyIdToken);
return proxyJsonRequest<unknown>({
method: "POST",
url: `${config.catalogServiceUrl}/bikes`,
headers: userHeaders(user.uid),
body: request.body,
timeoutMs: config.upstreamTimeoutMs,
});
});
app.put("/bikes/:bikeId", { schema: { params: bikeIdParamSchema, body: bikeBodySchema } }, async (request) => {
const user = await requireVerifiedUser(request, verifyIdToken);
const encoded = encodeURIComponent((request.params as { bikeId: string }).bikeId);
return proxyJsonRequest<unknown>({
method: "PUT",
url: `${config.catalogServiceUrl}/bikes/${encoded}`,
headers: userHeaders(user.uid),
body: request.body,
timeoutMs: config.upstreamTimeoutMs,
});
});
app.delete("/bikes/:bikeId", { schema: { params: bikeIdParamSchema } }, async (request) => {
const user = await requireVerifiedUser(request, verifyIdToken);
const encoded = encodeURIComponent((request.params as { bikeId: string }).bikeId);
return proxyJsonRequest<unknown>({
method: "DELETE",
url: `${config.catalogServiceUrl}/bikes/${encoded}`,
headers: userHeaders(user.uid),
// валидное тело, иначе каталог 500 на пустом application/json body
body: {},
timeoutMs: config.upstreamTimeoutMs,
});
});
/** Загрузка фото велика (multipart) — проксируется в каталог. */
app.post("/bikes/:bikeId/photo", { schema: { params: bikeIdParamSchema } }, async (request, reply) => {
const user = await requireVerifiedUser(request, verifyIdToken);
const encoded = encodeURIComponent((request.params as { bikeId: string }).bikeId);
const outgoing = new FormData();
const parts = request.parts();
for await (const part of parts) {
if (part.type === "file") {
const buf = await part.toBuffer();
const blob = new Blob([new Uint8Array(buf)], part.mimetype ? { type: part.mimetype } : {});
outgoing.append(part.fieldname, blob, part.filename ?? "photo");
} else {
outgoing.append(part.fieldname, String(part.value ?? ""));
}
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), config.upstreamTimeoutMs);
try {
const response = await fetch(`${config.catalogServiceUrl}/bikes/${encoded}/photo`, {
method: "POST",
headers: userHeaders(user.uid),
body: outgoing,
signal: controller.signal,
});
const body = Buffer.from(await response.arrayBuffer());
throwIfUpstreamFailed(response.status, body);
const ct = response.headers.get("content-type");
if (ct) {
reply.header("Content-Type", ct);
}
return reply.code(response.status).send(body);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
if (error instanceof Error && error.name === "AbortError") {
throw new AppError(504, "UPSTREAM_TIMEOUT", "Upstream request timed out");
}
throw new AppError(502, "UPSTREAM_UNAVAILABLE", "Upstream service unavailable");
} finally {
clearTimeout(timeout);
}
});
/** Фото велика (байты из R2 через каталог). */
app.get("/bikes/:bikeId/photo", { schema: { params: bikeIdParamSchema } }, async (request, reply) => {
const user = await requireVerifiedUser(request, verifyIdToken);
const encoded = encodeURIComponent((request.params as { bikeId: string }).bikeId);
const result = await proxyUpstreamGetRaw({
url: `${config.catalogServiceUrl}/bikes/${encoded}/photo`,
headers: userHeaders(user.uid),
timeoutMs: config.upstreamTimeoutMs,
});
if (result.contentType) {
reply.header("Content-Type", result.contentType);
}
reply.header("Cache-Control", "private, max-age=300");
return reply.code(result.status).send(result.body);
});
};
|