Step 3
Open the index.js
file and add the following import to the top of it.
const UserDao = require("./data/UserDao");
Add the following instantiation right next to where NoteDao
is constructed.
const users = new UserDao();
Add the following route handlers between where the app
variable is declared and the app.listen
is invoked.
app.get("/api/users", async (req, res) => {
const { username, role } = req.query;
if (username && role) {
res
.status(400)
.json({
message:
"You must query the database based on either a username or user role.",
});
} else {
const data = username
? await users.readOne(username)
: await users.readAll(role);
res.json({ data: data ? data : [] });
}
});
app.get("/api/users/:id", async (req, res) => {
const { id } = req.params;
const data = await users.read(id);
res.json({ data: data ? data : [] });
});
app.post("/api/users", async (req, res) => {
try {
const { username, password, role } = req.body;
const data = await users.create({ username, password, role });
res.status(201).json({ data });
} catch (err) {
res.status(err.status).json({ message: err.message });
}
});
app.delete("/api/users/:id", async (req, res) => {
try {
const { id } = req.params;
const data = await users.delete(id);
res.json({ data });
} catch (err) {
res.status(err.status).json({ message: err.message });
}
});
app.put("/api/users/:id", async (req, res) => {
try {
const { id } = req.params;
const { password, role } = req.body;
const data = await users.update(id, { password, role });
res.json({ data });
} catch (err) {
res.status(err.status).json({ message: err.message });
}
});
This routing for the "user" resource is similar to the "note" resource.
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).