Reading Data
Learning objectives
- You rehearse the CRUD pattern.
- You know how to read user-specific data.
Listing todos
Now that the todos are stored per user, where the user is identified with an id, we can modify the listTodos
function in todoService.js
to only return the todos that are associated with the user.
const listTodos = async (userId) => {
const kv = await Deno.openKv();
const todoEntries = await kv.list({ prefix: ["todos", userId] });
const todos = [];
for await (const entry of todoEntries) {
todos.push(entry.value);
}
return todos;
};
For this to work, we need to modify the showForm
function in todoController.js
to pass the user id to the listTodos
function.
const showForm = async (c) => {
return c.html(
eta.render("todos.eta", {
todos: await todoService.listTodos(c.user.id),
}),
);
};
Now, only the todos that have been created by the user are shown in the list of todos.
Viewing a single todo
The next functionality to modify is the functionality related to viewing a single todo. Let's first adjust the function getTodo
in todoService.js
to include the user id to retrieving a todo.
const getTodo = async (userId, id) => {
const kv = await Deno.openKv();
const todo = await kv.get(["todos", userId, id]);
return todo?.value ?? {};
};
And further, let's adjust the showTodo
function in todoController.js
to pass the user id to the getTodo
function.
const showTodo = async (c) => {
const id = c.req.param("id");
return c.html(
eta.render("todo.eta", {
todo: await todoService.getTodo(c.user.id, id),
}),
);
};
Now, only the todos that have been created by the user are shown in the page that is used to view individual todos.
Denying access
Presently, the getTodo
function returns an empty object if the todo is not found. As the key reason for a todo not being found relates to changing the path (or, to a database error), we could also either return the status code 404 (Not Found) or the status code 401 (Unauthorized Access). Both of these status codes would be more appropriate than returning an empty object, which leads to an error during page render.