(body: unknown)
| 395 | } |
| 396 | |
| 397 | function parseSaveRequest(body: unknown): { name: string; note: string; hops: SaveTrailRequest['hops'] } { |
| 398 | if (typeof body !== 'object' || body === null || Array.isArray(body)) { |
| 399 | throw badRequest('A trail is saved from a JSON object: { name, hops }.'); |
| 400 | } |
| 401 | const value = body as Record<string, unknown>; |
| 402 | |
| 403 | const name = typeof value.name === 'string' ? value.name.trim().replace(/\s+/g, ' ') : ''; |
| 404 | if (name === '') throw badRequest('A saved trail needs a name.'); |
| 405 | if (name.length > MAX_TRAIL_NAME) { |
| 406 | throw badRequest(`That name is too long (max ${MAX_TRAIL_NAME} characters).`); |
| 407 | } |
| 408 | |
| 409 | const note = typeof value.note === 'string' ? value.note.trim() : ''; |
| 410 | if (note.length > MAX_TRAIL_NOTE) { |
| 411 | throw badRequest(`That note is too long (max ${MAX_TRAIL_NOTE} characters).`); |
| 412 | } |
| 413 | |
| 414 | if (!Array.isArray(value.hops) || value.hops.length === 0) { |
| 415 | throw badRequest('A saved trail needs at least one hop.'); |
| 416 | } |
| 417 | if (value.hops.length > MAX_TRAIL_HOPS) { |
| 418 | throw badRequest(`A saved trail can hold at most ${MAX_TRAIL_HOPS} hops.`); |
| 419 | } |
| 420 | |
| 421 | const hops: SaveTrailRequest['hops'] = []; |
| 422 | for (const entry of value.hops) { |
| 423 | if (typeof entry !== 'object' || entry === null) throw badRequest('Each hop is { dir, id }.'); |
| 424 | const hop = entry as Record<string, unknown>; |
| 425 | if (typeof hop.id !== 'string' || hop.id === '') throw badRequest('Each hop needs an id.'); |
| 426 | hops.push({ id: hop.id, ...(typeof hop.dir === 'string' ? { dir: hop.dir } : {}) }); |
| 427 | } |
| 428 | |
| 429 | return { name, note, hops }; |
| 430 | } |
| 431 | |
| 432 | /* ---------------------------------------------------------------- author -- */ |
| 433 |
no test coverage detected