GitHub - riousenkai/awesome--anime: Goodreads-inspired application with an emphasis on Anime.
Goodreads-inspired application with an emphasis on Anime. - riousenkai/awesome--anime

the app uses express and pug on the back end with sequelize over postgres. pages are rendered on the server and the parts that need to feel instant talk to a small json api with fetch and patch the dom themselves.

the full catalogue, filterable by genre down the side.
catalogue

the data

users, animes, genre types, reviews, user anime lists, and three join tables that connect them. an anime has a title, a synopsis, a cover and a banner, a studio, an episode count, status, air date, a rating, and two flags, top and winter, that drive the two shelves on the home page. the catalogue is a hundred shows seeded from a script, with covers and banners from anilist's cdn, across ten genres.

every list row has a name, a user and a type, and the type is what makes the four built-in lists special. types 1 to 4 are watched, want to watch, currently watching and favorites, and they're created for you the moment you register. anything with a type of 5 or more is a custom list. the anime in a list live in a join table between the list and the show, so one show can sit on as many lists as you like.

const hashedPassword = await bcrypt.hash(password, 10);
user.password = hashedPassword;
await user.save();

UserAnimeList.create({ name: "Watched",            user_id: user.id, type: 1 });
UserAnimeList.create({ name: "Want to watch",      user_id: user.id, type: 2 });
UserAnimeList.create({ name: "Currently watching", user_id: user.id, type: 3 });
UserAnimeList.create({ name: "Favorites",          user_id: user.id, type: 4 });

loginUser(req, res, user);
return req.session.save(() => {
  res.redirect("/preferences");
});

the password has already been hashed with bcrypt at this point, and the user is logged in and sent straight to the preferences page to pick genres.

sign up. the validators have opinions.
sign up

recommendations

the genre picker on sign up writes one row per chosen genre into a user-genre join table. recommendations are then three queries chained together: which genres does this user like, which anime carry any of those genres, and load those anime. the variable names in the home route tell you how we felt about writing it at 2am.

const recommendedUserGenres = await UserGenreJoin.findAll({
  where: { user_id: userId },
});
const recommendedUserGenresFiltered = recommendedUserGenres.map(
  (genreObject) => genreObject.genre_id
);

const recommendedAnime = await GenreAnimeJoin.findAll({
  where: { genre_id: [...recommendedUserGenresFiltered] },
});
const recommendedUserGenresFiltered2 = recommendedAnime.map(
  (animeObject) => animeObject.anime_id
);

const finallyWeAreDoneOmg = await Anime.findAll({
  where: { id: [...recommendedUserGenresFiltered2] },
  limit: 5,
});

the same chain backs the "recommended" shelf on the home page (capped at five) and the full recommended page under /anime/recommended. there's no scoring, no weighting by how many of your genres a show matches. a show gets in if it shares one genre with you. for a catalogue of a hundred that was fine, and it meant the recommendations changed the instant you changed your genres.

auth and sessions

sessions are stored in postgres through connect-session-sequelize, so there's no separate session store to run and a restart doesn't log everyone out. a middleware runs on every request, reads the user id out of the session, loads the user, and puts it on res.locals so every pug template can check authenticated and read user without each route doing it.

const restoreUser = async (req, res, next) => {
  if (req.session.auth) {
    const { userId } = req.session.auth;
    try {
      const user = await User.findByPk(userId);
      if (user) {
        res.locals.authenticated = true;
        res.locals.user = user;
        next();
      }
    } catch (err) {
      res.locals.authenticated = false;
      next(err);
    }
  } else {
    res.locals.authenticated = false;
    next();
  }
};
login. the demo button signs you in as the demo user so you can look around without an account.
login

login and register forms carry a csrf token, passwords are bcrypt hashed, and registration runs through express-validator with a strong-password regex: at least eight characters, upper and lower case, a number and a symbol. the error messages are the only place in the codebase where we let ourselves be funny. a username over 25 characters is told to sue its parents, and an email without a dot is told it needs the dots and coms.

reviews

we request /api/reviews/:animeId for the reviews with their users included, plus the id of whoever is signed in. that id is what decides which reviews get edit and delete buttons: the comparison happens on the client, but the api only ever hands out the current session's id, so you can't claim someone else's.

// server: /api/reviews/:animeId
const review = await Review.findAll({
  include: User,
  where: { anime_id: req.params.animeId },
  order: [["createdAt", "ASC"]],
});
const currSession = req.session.auth ? req.session.auth.userId : -1;
res.json({ review, currSession });

// client: only your own reviews get the buttons
const reviewChange = review.map(({ description, updatedAt, id }, i, array) => {
  const date = updatedAt.split("T")[0];
  if (array[i].User.id === currSession) {
    return `<li id='list-${id}'>
      ...
      <button class="s-${id} editButton" onclick="return editB(${id})">Edit</button>
      <button class="${id} deleteButton" onclick="return deleteB(${id})">Delete</button>
      ...
    </li>`;
  }
  return `<li id='list-${id}'> ... </li>`;
});
reviewContainer.innerHTML = reviewChange.join("");
an anime page: banner, poster, synopsis, the stats block, the four list buttons plus custom lists, and reviews underneath.
an anime page

lists

the list buttons on an anime page post the show into the list you clicked. the api checks the join table first and only inserts if that pair doesn't already exist, so clicking watched twice doesn't give you two copies. on the list page, removing a row deletes the join entry for that list and show, and deleting a custom list deletes all of its entries and then the list itself.

creating a custom list is an input that listens for enter. it posts the name, gets the new list's id back, and appends an option to the dropdown with that id as its value so the list is usable immediately without a reload.

list.addEventListener("keydown", async (event) => {
  if (event.keyCode === 13) {
    event.preventDefault();
    const body = { list: list.value };

    const newList = await fetch(`/api/animeList`, {
      method: "POST",
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" },
    });
    const { reviewId } = await newList.json();

    const option = document.createElement("option");
    option.setAttribute("value", `${reviewId}`);
    option.innerText = list.value;
    select.appendChild(option);

    list.value = "";
  }
});
a user's lists. the four built-in ones as tabs, custom lists in the dropdown, and the table with a remove button per row.
a user list

there are two searches. the one in the header is a plain form post that renders a results page. for live search, keyup handler sends the current text to the api, which runs a case-insensitive ilike on titles with a limit of ten, and the client rebuilds the results list from the json.

// client
searchInput.addEventListener("keyup", async (e) => {
  resultsContainer.innerHTML = "";
  const res = await fetch(`/api/search/`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ wya: searchInput.value }),
  });
  const { results } = await res.json();
  results.forEach((result) => {
    resultsContainer.innerHTML += `<li class='anime-result'>
      <img src='${result.image_url}' class='anime-img-1'>
      <a class='anime-lnk' href='/anime/${result.id}'>${result.title}</a></li>`;
  });
});

// server
router.put("/search", asyncHandler(async (req, res) => {
  const results = await Anime.findAll({
    where: { title: { [Op.iLike]: `%${req.body.wya}%` } },
    limit: 10,
  });
  res.json({ results });
}));
live search. every keystroke asks the server and the results list is rebuilt in place.
live search

dark mode and the rest

dark mode is a boolean on the user which is toggled by two tiny routes that flip it and redirect back. because it's on the row and not in localstorage, the templates read it off the user on every render and it follows you between browsers.

dark mode is a flag on the user row, so it follows you between devices.
persistent dark mode across cookies
a profile page with the bio and the full collection.
profile page