Menu
CoddyTech

Sortowanie tekstu

Część sekcji API REST ścieżki Node.js w Coddy. Lekcja 15 z 25.

Twój moduł śledzący może filtrować zadania. Teraz pozwól klientowi zażądać tytułów w kolejności alfabetycznej bez zmieniania zapisanej kolejności. Porównanie sortujące zwraca liczbę ujemną, gdy pierwszy element powinien znaleźć się przed drugim, dodatnią, gdy powinien znaleźć się po nim, a zero, gdy są równe.

const sorted = cities.toSorted((a, b) => a.name.localeCompare(b.name));

Odejmowanie ciągów znaków nie daje użytecznej kolejności. localeCompare porównuje tekst. toSorted zwraca nową tablicę, pozostawiając oryginalną tablicę bez zmian. Posortuj przefiltrowaną listę, aby filtrowanie i sortowanie działały razem. Kolejna lekcja Sortowanie dodaje inne pola, kolejność malejącą i obsługę nieprawidłowych zapytań.

challenge icon

Wyzwanie

Łatwy

Kontynuuj pracę nad menedżerem zadań w pliku routes/tasks.js. W trasie listy, po istniejących filtrach, spraw, aby ?sort=title zwracało zadania posortowane alfabetycznie według tytułu. Bez tej wartości zachowaj obecne działanie. Nie zmieniaj kolejności zadań w pamięci.

Wypróbuj GET /api/tasks?sort=title, a następnie GET /api/tasks. Druga lista musi nadal być w pierwotnej kolejności. Filtrowanie za pomocą ?done=false&sort=title musi nadal zwracać tylko niewykonane zadania.

Spróbuj swoich sił

import { Router } from 'express';
import { z } from 'zod';
import { sendError, sendInvalid } from '../errors.js';
import { nextId, tasks } from '../store.js';

const router = Router();

// Pełne zadanie, w postaci przesyłanej przez PUT. .strict() odrzuca pola, których nie wymienia.
const Task = z
    .object({
        title: z.string().trim().min(1).max(100),
        done: z.boolean(),
    })
    .strict();
const NewTask = Task.partial({ done: true });
const TaskChanges = Task.partial();

// True, gdy inne zadanie ma już taki tytuł, niezależnie od wielkości liter.
const titleTaken = (title, exceptId) =>
    tasks.some((t) => t.id !== exceptId && t.title.toLowerCase() === title.toLowerCase());

router.get('/', (req, res) => {
    const { done, q } = req.query;
    let list = tasks;
    if (done !== undefined) {
        if (done !== 'true' && done !== 'false') {
            return sendError(res, 400, 'invalid_query', 'done must be true or false');
        }
        list = list.filter((t) => t.done === (done === 'true'));
    }
    if (q !== undefined) {
        const words = String(q).toLowerCase();
        list = list.filter((t) => t.title.toLowerCase().includes(words));
    }
    res.json(list);
});

router.get('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return sendError(res, 404, 'not_found', 'Task not found');
    }
    res.json(task);
});

router.post('/', (req, res) => {
    const result = NewTask.safeParse(req.body);
    if (!result.success) {
        return sendInvalid(res, result.error);
    }
    const { title, done = false } = result.data;
    if (titleTaken(title)) {
        return sendError(res, 409, 'conflict', 'A task with this title already exists');
    }
    const task = { id: nextId(), title, done, createdAt: new Date().toISOString() };
    tasks.push(task);
    res.status(201).location(`/api/tasks/${task.id}`).json(task);
});

router.patch('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return sendError(res, 404, 'not_found', 'Task not found');
    }
    const result = TaskChanges.safeParse(req.body);
    if (!result.success) {
        return sendInvalid(res, result.error);
    }
    if (result.data.title !== undefined && titleTaken(result.data.title, task.id)) {
        return sendError(res, 409, 'conflict', 'A task with this title already exists');
    }
    Object.assign(task, result.data);
    res.json(task);
});

router.put('/:id', (req, res) => {
    const index = tasks.findIndex((t) => t.id === Number(req.params.id));
    if (index === -1) {
        return sendError(res, 404, 'not_found', 'Task not found');
    }
    const result = Task.safeParse(req.body);
    if (!result.success) {
        return sendInvalid(res, result.error);
    }
    const { id, createdAt } = tasks[index];
    if (titleTaken(result.data.title, id)) {
        return sendError(res, 409, 'conflict', 'A task with this title already exists');
    }
    tasks[index] = { id, ...result.data, createdAt };
    res.json(tasks[index]);
});

router.delete('/:id', (req, res) => {
    const index = tasks.findIndex((t) => t.id === Number(req.params.id));
    if (index === -1) {
        return sendError(res, 404, 'not_found', 'Task not found');
    }
    tasks.splice(index, 1);
    res.status(204).end();
});

export default router;

Wszystkie lekcje w sekcji API REST

Poćwicz samodzielnie: Edytor online Express