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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 39x 39x 6x 6x 6x 6x 39x 3x 3x 1x 1x 2x 3x 39x 2x 2x 2x 2x 2x 1x 39x 39x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 39x 39x 39x 39x 39x 1x 1x 1x 1x 39x 39x 1x 1x 1x 1x 1x 1x 39x 39x 39x 39x 39x 1x 1x 1x 1x 1x 1x 1x 1x 39x 39x 39x 39x | import { randomUUID } from "node:crypto";
import { AppError } from "@ontrack/backend-common";
import type { FastifyPluginAsync, FastifyRequest } from "fastify";
import type { AppConfig } from "../config.js";
import { MAX_AVATAR_BYTES, avatarExtension } from "../lib/avatar-media.js";
import { assertServiceToken } from "../lib/service-token.js";
import { readUserUid } from "../lib/user-uid.js";
import { prisma } from "../lib/prisma.js";
import type { ObjectStore } from "../storage/object-store.js";
const bikeIdParamSchema = {
type: "object",
required: ["bikeId"],
additionalProperties: false,
properties: {
bikeId: { type: "string", pattern: "^[1-9][0-9]*$" },
},
} as const;
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;
type BikeRow = {
id: number;
brand: string;
model: string;
name: string;
description: string | null;
photoKey: string | null;
};
function mapBike(row: BikeRow) {
return {
id: row.id,
brand: row.brand,
model: row.model,
name: row.name,
description: row.description ?? null,
hasPhoto: Boolean(row.photoKey),
};
}
function normalize(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
export const bikesRoutes: FastifyPluginAsync<{
config: AppConfig;
photoStore: ObjectStore | null;
}> = async (app, opts) => {
const { config, photoStore } = opts;
function authorize(request: FastifyRequest): string {
const token = request.headers["x-service-token"];
assertServiceToken(Array.isArray(token) ? token[0] : token, config.serviceToken);
return readUserUid(request);
}
/** Найти велик владельца или 404 (не раскрываем чужие). */
async function ownedBikeOrThrow(id: number, uid: string) {
const bike = await prisma.bike.findUnique({ where: { id } });
if (!bike || bike.ownerUid !== uid) {
throw new AppError(404, "BIKE_NOT_FOUND", "Велик не найден");
}
return bike;
}
app.get("/bikes", async (request, reply) => {
const uid = authorize(request);
const rows = await prisma.bike.findMany({
where: { ownerUid: uid },
orderBy: { createdAt: "asc" },
});
return reply.send({ bikes: rows.map(mapBike) });
});
app.post("/bikes", { schema: { body: bikeBodySchema } }, async (request, reply) => {
const uid = authorize(request);
const body = request.body as {
brand: string;
model: string;
name: string;
description?: string | null;
};
const bike = await prisma.bike.create({
data: {
ownerUid: uid,
brand: body.brand.trim(),
model: body.model.trim(),
name: body.name.trim(),
description: normalize(body.description),
},
});
return reply.status(201).send({ bike: mapBike(bike) });
});
app.put(
"/bikes/:bikeId",
{ schema: { params: bikeIdParamSchema, body: bikeBodySchema } },
async (request, reply) => {
const uid = authorize(request);
const id = Number.parseInt((request.params as { bikeId: string }).bikeId, 10);
await ownedBikeOrThrow(id, uid);
const body = request.body as {
brand: string;
model: string;
name: string;
description?: string | null;
};
const bike = await prisma.bike.update({
where: { id },
data: {
brand: body.brand.trim(),
model: body.model.trim(),
name: body.name.trim(),
description: normalize(body.description),
},
});
return reply.send({ bike: mapBike(bike) });
},
);
app.delete("/bikes/:bikeId", { schema: { params: bikeIdParamSchema } }, async (request, reply) => {
const uid = authorize(request);
const id = Number.parseInt((request.params as { bikeId: string }).bikeId, 10);
const bike = await ownedBikeOrThrow(id, uid);
await prisma.bike.delete({ where: { id } });
if (bike.photoKey && photoStore) {
await photoStore.delete(bike.photoKey).catch(() => undefined);
}
return reply.send({ ok: true });
});
app.post(
"/bikes/:bikeId/photo",
{ schema: { params: bikeIdParamSchema } },
async (request, reply) => {
const uid = authorize(request);
const id = Number.parseInt((request.params as { bikeId: string }).bikeId, 10);
const existing = await ownedBikeOrThrow(id, uid);
if (!photoStore) {
throw new AppError(503, "PHOTO_STORAGE_UNAVAILABLE", "Хранилище фото не настроено");
}
const file = await request.file();
if (!file) {
throw new AppError(400, "FILE_REQUIRED", "Файл не передан");
}
const ext = avatarExtension(file.mimetype);
const buffer = await file.toBuffer();
if (buffer.length === 0) {
throw new AppError(400, "FILE_REQUIRED", "Пустой файл");
}
if (buffer.length > MAX_AVATAR_BYTES) {
throw new AppError(413, "FILE_TOO_LARGE", "Файл больше 5 МБ");
}
const key = `bikes/${uid}/${id}/${randomUUID()}.${ext}`;
await photoStore.put(key, buffer, file.mimetype);
const bike = await prisma.bike.update({ where: { id }, data: { photoKey: key } });
if (existing.photoKey && existing.photoKey !== key) {
await photoStore.delete(existing.photoKey).catch(() => undefined);
}
return reply.send({ bike: mapBike(bike) });
},
);
app.get("/bikes/:bikeId/photo", { schema: { params: bikeIdParamSchema } }, async (request, reply) => {
const uid = authorize(request);
const id = Number.parseInt((request.params as { bikeId: string }).bikeId, 10);
const bike = await ownedBikeOrThrow(id, uid);
if (!photoStore || !bike.photoKey) {
throw new AppError(404, "PHOTO_NOT_FOUND", "Фото не найдено");
}
const object = await photoStore.get(bike.photoKey);
return reply
.header("Content-Type", object.contentType)
.header("Cache-Control", "private, max-age=300")
.send(object.body);
});
};
|