Computer >> 컴퓨터 >  >> 프로그래밍 >> Redis

Remix와 서버리스 Redis(Upstash)로 TODO 앱 만들기

이번 글에서는 Remix서버리스 Redis(Upstash)를 활용해 간단한 TODO 앱을 직접 만들어 보겠습니다.

Remix는 사용자 인터페이스에 집중하고 웹의 근본적인 원리를 기반으로 작업하여 빠르고 매끄러우며 탄력적인 사용자 경험을 제공할 수 있도록 도와주는 풀스택 웹 프레임워크입니다.

Remix 프로젝트 생성하기

터미널에서 아래 명령어를 실행합니다:

npx create-remix@latest

Remix와 서버리스 Redis(Upstash)로 TODO 앱 만들기

프로젝트가 준비되었습니다. 이제 의존성을 설치하고 개발 서버를 실행해 보겠습니다:

npm install
npm run dev

Remix와 서버리스 Redis(Upstash)로 TODO 앱 만들기

사용자 인터페이스 만들기

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 () => {
  // 예시 데이터
  return [
    { id: 1, text: "Task 1", status: false },
    { id: 2, text: "Task 2", status: true },
  ];
};

export const action: ActionFunction = async ({ request }) => {
  // 생성, 수정, 삭제 작업에 사용됩니다
};

export default function Index() {
  // 로딩 및 폼 액션 상태 추적
  const transition = useTransition();

  // 로드한 데이터를 페이지에서 사용
  const todos: Todo[] = useLoaderData();

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

  // 완료 / 미완료 항목 분리
  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(() => {
    // 생성 후 폼 초기화 및 포커스 이동
    if (isAdding) return;
    formRef.current?.reset();
    inputRef.current?.focus();
  }, [isAdding]);

  return (
    <main className="container">
      {/* 생성 폼 */}
      <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>

      {/* 미완료 항목 */}
      <div className="todos">
        {uncheckedTodos.map((todo) => (
          <TodoItem key={todo.id} {...todo} />
        ))}
      </div>

      {/* 완료된 항목 */}
      {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">
        {/* hidden input이 해당 TODO 항목의 데이터를 유지합니다 */}
        <input
          type="hidden"
          name="todo"
          defaultValue={JSON.stringify({ id, text, status })}
        />
        {/* Remix의 폼은 전통적인 웹 폼처럼 동작합니다 */}
        <button type="submit" className="checkbox">
          {status && "✓"}
        </button>
      </Form>

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

이제 스타일을 적용할 차례입니다. 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;
}

root.tsx 파일에서 위 CSS를 임포트합니다:

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() {
  // ...
}

여기까지 완료하면 아래와 같은 화면을 확인할 수 있습니다:

Remix와 서버리스 Redis(Upstash)로 TODO 앱 만들기

데이터베이스 준비하기

데이터는 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,
      },
    });
  }

  // 작업 후마다 최신 목록을 불러오기 위해 리다이렉트
  return redirect("/");
};

// ...

이제 저장된 항목들을 목록으로 불러오겠습니다:

// 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,
  }));
  // 날짜순 정렬 (id = 타임스탬프)
  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();

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

  // 수정 (완료 여부 토글)
  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/