Redis
 Computer >> コンピューター >  >> プログラミング >> Redis

RemixとサーバーレスRedis(Upstash)でTODOアプリを作成する方法

この記事では、RemixサーバーレスRedis(Upstash)を組み合わせて、シンプルなTODOアプリを作成する手順を解説します。

Remixは、ユーザーインターフェースに集中しながら、Webの基本原則に立ち返ることで、高速で滑らか、そして堅牢なユーザーエクスペリエンスを提供できるフルスタックWebフレームワークです。

Remixプロジェクトの作成

まず、以下のコマンドを実行します。

npx create-remix@latest

プロジェクトの雛形が完成しました。続いて、依存パッケージをインストールし、開発サーバーを起動します。

npm install
npm run dev

ユーザーインターフェースの構築

TODOアイテムを入力するためのシンプルなフォームと、タスクを一覧表示するリストを作成していきます。

// app/routes/index.tsx

import type { ActionFunction, LoaderFunction } from "remix";
import { Form, useLoaderData, useTransition, redirect } from "remix";
import { useEffect, useRef } from "react";
import type { Todo } from "~/components/todo-item";
import TodoItem from "~/components/todo-item";

export const loader: LoaderFunction = async () => {
  // example data
  return [
    { id: 1, text: "Task 1", status: false },
    { id: 2, text: "Task 2", status: true },
  ];
};

export const action: ActionFunction = async ({ request }) => {
  // this will be used for create, update and delete operations
};

export default function Index() {
  // for loading and form actions
  const transition = useTransition();

  // to use the loaded data in the page
  const todos: Todo[] = useLoaderData();

  const isCreating = transition.submission?.method === "POST";
  const isAdding = transition.state === "submitting" && isCreating;

  // split the finished and unfinished items
  const uncheckedTodos = todos.filter((todo) => !todo.status);
  const checkedTodos = todos.filter((todo) => todo.status);

  const formRef = useRef<HTMLFormElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    // reset the form after the create
    if (isAdding) return;
    formRef.current?.reset();
    inputRef.current?.focus();
  }, [isAdding]);

  return (
    <main className="container">
      {/* crete form */}
      <Form ref={formRef} method="post">
        <input
          ref={inputRef}
          type="text"
          name="text"
          autoComplete="off"
          className="input"
          placeholder="What needs to be done?"
          disabled={isCreating}
        />
      </Form>

      {/* uncompleted tasks */}
      <div className="todos">
        {uncheckedTodos.map((todo) => (
          <TodoItem key={todo.id} {...todo} />
        ))}
      </div>

      {/* completed tasks */}
      {checkedTodos.length > 0 && (
        <div className="todos todos-done">
          {checkedTodos.map((todo) => (
            <TodoItem key={todo.id} {...todo} />
          ))}
        </div>
      )}
    </main>
  );
}

続いて、個々のTODOアイテムを表示するコンポーネントです。

// app/components/todo-item.tsx

import { Form } from "remix";

export type Todo = { id: string; text: string; status: boolean };

export default function TodoItem({ id, text, status }: Todo) {
  return (
    <div className="todo">
      <Form method="put">
        {/* this hidden input will keep the data for our todo item */}
        <input
          type="hidden"
          name="todo"
          defaultValue={JSON.stringify({ id, text, status })}
        />
        {/* Remix forms are just like traditional web forms. I like this. */}
        <button type="submit" className="checkbox">
          {status && "✓"}
        </button>
      </Form>

      <span className="text">{text}</span>
    </div>
  );
}

次にスタイルを整えるためのCSSファイルを追加します。app/styles/app.css を新規作成してください。

:root {
  --rounded: 0.25rem;
  --rounded-md: 0.375rem;
  --gray-50: rgb(249, 250, 251);
  --gray-100: rgb(243, 244, 246);
  --gray-200: rgb(229, 231, 235);
  --gray-300: rgb(209, 213, 219);
  --gray-400: rgb(156, 163, 175);
  --gray-500: rgb(107, 114, 128);
  --gray-600: rgb(75, 85, 99);
  --gray-700: rgb(55, 65, 81);
  --gray-800: rgb(31, 41, 55);
  --gray-900: rgb(17, 24, 39);
}

*,
::before,
::after {
  box-sizing: border-box;
  border: 0;
  padding: 0;
}

button,
input,
optgroup,
select,
textarea {
  font-family: inherit;
  font-size: 100%;
  line-height: inherit;
  color: inherit;
  margin: 0;
  padding: 0;
}

button {
  cursor: pointer;
  background-color: white;
}

html {
  font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
  line-height: 1.5;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: var(--gray-800);
}

.container {
  padding: 8rem 1rem 0;
  margin: 0 auto;
  max-width: 28rem;
}

.input {
  width: 100%;
  padding: 0.75rem 1rem;
  background-color: var(--gray-100);
  border-radius: var(--rounded-md);
}

.input::placeholder {
  color: var(--gray-400);
}

.input:disabled {
  color: var(--gray-600);
  background-color: var(--gray-200);
}

.todos {
  margin-top: 1.5rem;
}

.todos.todos-done {
  background-color: var(--gray-100);
  color: var(--gray-500);
  border-radius: var(--rounded-md);
}

.todo {
  display: flex;
  align-items: center;
  padding: 0.75rem;
  border-radius: var(--rounded-md);
}

.todo + .todo {
  border-top: 1px solid var(--gray-100);
}

.todo .checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1.25rem;
  height: 1.25rem;
  border-radius: var(--rounded);
  border: 1px solid var(--gray-300);
  box-shadow: 0 1px 1px 0 rgb(0 0 0 / 10%);
}

.todo .text {
  margin-left: 0.75rem;
}

作成したCSSを root.tsx 内でインポートします。

import {
  Links,
  LiveReload,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
} from "remix";
import type { MetaFunction } from "remix";
import styles from "./styles/app.css";

export function links() {
  return [{ rel: "stylesheet", href: styles }];
}

export const meta: MetaFunction = () => {
  return { title: "Remix Todo App with Redis" };
};

export default function App() {
  // ...
}

ここまで進めると、ブラウザ上では次のような画面が表示されているはずです。

データベースの準備

アプリのデータはUpstash Redisに保存します。まずはUpstashコンソールでデータベースを作成しましょう。今回はHTTPベースのUpstashクライアントを使用するため、以下のコマンドでインストールします。

npm install @upstash/redis

補足: UpstashはRedis APIと互換性があるため、任意のRedisクライアントを利用できます。ただし、その場合は後述のコードを環境に合わせて変更する必要があります。

それでは、フォームを送信するだけで新しいTODOアイテムを追加できるようにします。追加されたアイテムはRedis Hashに保存されます。

Upstashコンソールから UPSTASH_REDIS_REST_URLUPSTASH_REDIS_REST_TOKEN をコピーして、コード内に貼り付けてください。

// app/routes/index.tsx

// ...
import { Redis } from "@upstash/redis";

const redis = new Redis({
  url: "UPSTASH_REDIS_REST_URL",
  token: "UPSTASH_REDIS_REST_TOKEN",
});

export const action: ActionFunction = async ({ request }) => {
  const form = await request.formData();

  if (request.method === "POST") {
    const text = form.get("text");
    if (!text) return redirect("/");

    await redis.hset("remix-todo-example", {
      [Date.now().toString()]: {
        text,
        status: false,
      },
    });
  }

  // to fetch the list after each operation
  return redirect("/");
};

// ...

続いて、保存したアイテムを一覧表示する処理をloaderに実装します。

// app/routes/index.tsx

export const loader: LoaderFunction = async () => {
  const res = await redis.hgetall<Record<string, object>>(DATABASE_KEY);
  const todos = Object.entries(res ?? {}).map(([key, value]) => ({
    id: key,
    ...value,
  }));
  // sort by date (id=timestamp)
  return todos.sort((a, b) => parseInt(b.id) - parseInt(a.id));
};

これで「作成」と「一覧表示」の機能が揃いました。最後に、ユーザーがチェックボックスをクリックしてTODOアイテムを完了済みとしてマークできる機能を追加します。

// app/routes/index.tsx

export const action: ActionFunction = async ({ request }) => {
  const form = await request.formData();

  // create
  if (request.method === "POST") {
    // ...
  }

  // update
  if (request.method === "PUT") {
    const todo = form.get("todo");
    const { id, text, status } = JSON.parse(todo as string);

    await redis.hset("remix-todo-example", {
      [id]: {
        text,
        status: !status,
      },
    });
  }

  return redirect("/");
};

これですべての実装が完了しました!筆者は今後、同じTODOアプリケーションをNext.jsやSvelteKitでも実装し、各フレームワークでの開発体験を比較する予定です。

最新情報はTwitterやDiscordでも発信していますので、ぜひフォローしてお見逃しなく。

プロジェクトのソースコード

https://github.com/upstash/redis-examples/tree/master/remix-todo-app-with-redis

プロジェクトのデモページ

https://remix-todo-app-with-redis.vercel.app/

  1. Cloudflare WorkersとRedisで実現するエッジコンピューティング活用術

    エッジコンピューティングは、近年もっとも注目されている技術のひとつです。CDNがファイルをユーザーの近くに配置できるようにしたのと同じように、エッジコンピューティングはアプリケーションそのものをユーザーの近くで実行できるようにします。これにより、開発者はグローバルに分散され、高いパフォーマンスを発揮するアプリケーションを構築できるようになります。 Cloudflare Workersとステートレス性の課題 現在この分野をリードしている製品がCloudflare Workersです。コールドスタートのないサーバーレス実行環境を提供し、Cloudflareのグローバルネットワークを活かすことで、ア

  2. Redis GEORADIUSBYMEMBERコマンドの使い方を実例付きで解説 – Redisチュートリアル

    このチュートリアルでは、Redisに保存された地理空間データ(ジオスペーシャル値)の中から、特定の範囲内に含まれる要素を取得する方法を学びます。そのために使用するのが GEORADIUSBYMEMBER コマンドです。 GEORADIUSBYMEMBERコマンドとは GEORADIUSBYMEMBERコマンドは、キーに保存された地理空間値(ソート済みセット)のメンバーのうち、指定したメンバーの経度・緯度と半径の引数から算出される円形エリアの境界内にある1つ以上のメンバーを返すために使用します。このエリアは、指定したメンバーの経度・緯度を円の中心位置とし、指定した単位による半径を円の半径として計