Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Xây Dựng JIRA Clone Open-Source Với Firebase, Upstash Và SvelteKit

Trong bài này, tôi nói về cách xây dựng alternative open-source cho Jira Kanban Board dùng Upstash, SvelteKit, Firebase Storage.

Xây Dựng JIRA Clone Open-Source Với Firebase, Upstash Và SvelteKit

Công Nghệ Sử Dụng

  • SvelteKit (UI và API Routes)
  • Upstash (CRUD Operations)
  • Tailwind CSS (Styling)
  • Firebase Storage (Lưu trữ Asset [images, pdf, etc.])
  • SvelteKit Auth by Auth.js

Những Gì Bạn Cần

  • Tài khoản Upstash tạo database
  • Tài khoản Firebase tạo storage container
  • Setup Google OAuth 2.0 lấy OAuth credentials

Thiết Lập Upstash Redis

Sau khi tạo tài khoản Upstash và đăng nhập, vào tab Redis tạo database.

Xây Dựng JIRA Clone Open-Source Với Firebase, Upstash Và SvelteKit

Xây Dựng JIRA Clone Open-Source Với Firebase, Upstash Và SvelteKit

Sau khi tạo database, vào tab Details. Cuộn xuống section Connect your database. Copy nội dung lưu nơi an toàn.

Xây Dựng JIRA Clone Open-Source Với Firebase, Upstash Và SvelteKit

Cuộn xuống section REST API chọn nút .env. Copy nội dung lưu an toàn.

Xây Dựng JIRA Clone Open-Source Với Firebase, Upstash Và SvelteKit

Thiết Lập Dự Án

Để setup, clone app repo và follow tutorial học mọi thứ trong đó. Fork project chạy:

git clone https://github.com/rishi-raj-jain/jira-sveltekit-firebase-storage-upstash-starter
cd jira-sveltekit-firebase-storage-upstash-starter
npm install

Sau khi clone repo, tạo file .env. Thêm items lưu từ các section trên.

Trông như:

# .env
# Obtained from Google OAuth 2.0 setup
# https://support.google.com/cloud/answer/6158849?hl=en
GOOGLE_ID="..."
GOOGLE_SECRET="..."
# SvelteKit Auth
AUTH_SECRET="..."
# A random 32 char string
AUTH_TRUST_HOST=true
# Obtained from Upstash as from the steps done above
UPSTASH_REDIS_REST_URL="your_upstash_redis_rest__url_from_above"
UPSTASH_REDIS_REST_TOKEN="your_upstash_redis_rest__token_from_above"
// firebase-adminsdk.json
// with the firebase config obtained from your firebase project
// Read more about firebase config
// https://firebase.google.com/docs/web/learn-more#config-object
{
  "type": "...",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "...",
  "token_uri": "...",
  "auth_provider_x509_cert_url": "...",
  "client_x509_cert_url": "...",
  "universe_domain": "...",
  "storageBucket": "..."
}

Sau các bước, start local environment dùng lệnh:

npm run dev

Cấu Trúc Repository

Cấu trúc folder chính dự án. Đã khử đỏ các file sẽ thảo luận tiếp trong bài deal với CRUD Operations, SvelteKit Auth, File Upload Handler, với file chúng được reference.

Xây Dựng JIRA Clone Open-Source Với Firebase, Upstash Và SvelteKit

Bảo Vệ Edge Function Của SvelteKit Bằng Xác Thực User

Công việc tuyệt vời của team Auth.js làm Auth với SvelteKit trở nên seamless. Project triển khai:

Authorization Trên Tất Cả Page Dùng Google OAuth 2.0

Dùng SvelteKit Server Hooks, enforce Auth trên tất cả incoming request (đến bất kỳ page):

// File: @/hooks.server.ts
import Google from "@auth/core/providers/google";
import { SvelteKitAuth } from "@auth/sveltekit";
import type { Handle } from "@sveltejs/kit";
import { GOOGLE_ID, GOOGLE_SECRET } from "$env/static/private";
// Read more on
// https://kit.svelte.dev/docs/hooks#server-hooks-handle
export const handle = SvelteKitAuth({
  // @ts-ignore
  providers: [Google({ clientId: GOOGLE_ID, clientSecret: GOOGLE_SECRET })],
}) satisfies Handle;

Authorization Trên Edge Function Dùng SvelteKit Server Locals

Dùng SvelteKit Server Locals, opt-in check user authenticated trong bất kỳ server-side only operation. Ví dụ validate user authenticated khi tạo issue mới:

import { json } from '@sveltejs/kit'
import { isAuth } from '@/lib/auth'
import type { RequestEvent } from './$types'
import { getTask, getTasks } from '@/lib/issues'
import type { LayoutServerLoadEvent } from '../routes/$types'
import type { RequestEvent, ServerLoadEvent } from '@sveltejs/kit'
// Get user session if available in event locals
const isAuth = async (event: LayoutServerLoadEvent | ServerLoadEvent | RequestEvent) => {
  const session = await event.locals.getSession()
  if (session?.user?.image) {
    return { session }
  }
  return false
}
export async function GET(event: RequestEvent) {
  // If user is not authenticated throw a 403
  if (!(await isAuth(event))) {
    return new Response(undefined, { status: 403 })
  }
  const url = event.url
  const idSearchParam = url.searchParams.get('id')
  if (idSearchParam) {
    const res = await getTask(idSearchParam)
    return json(res)
  } else if (url.searchParams.get('all')) {
    const res = await getTasks()
    return json(res)
  }
  return new Response(JSON.stringify({ code: 0, error: 'Invalid Request.' }), {
    status: 400,
    headers: { 'content-type': 'application/json' }
  })
}

Issue(s) CRUD Operations Via Upstash Redis

Phần này deep dive vào cách data fetching, updating, deletion cho mỗi issue trên Kanban board. Liên tục dùng Upstash DB (via @upstash/redis) fetch, display, refresh data.

getTask: Function Lấy Dữ Liệu Issue

Function getTask dùng Upstash hget qua id làm key làm API request đến Upstash lấy issue data liên quan, identified bằng unique id. Nếu issue không present (hoặc error), function trả về object { code: 0 } để user redirect đến 404 (issue not found) tự động trong dynamic route SvelteKit.

type Task = { [key: string]: any } | null;
// Get Issue Data
// File: @/lib/issues/get.ts
export async function getTask(id: string) {
  try {
    const redis = (await import("../upstash/setup")).default;
    const task: Task = await redis.hget("issues", id);
    if (!task) {
      return { code: 0, error: "No such issue found.", };
    }
    return { ...task, code: 1 };
  } catch (e: any) {
    const error = e.message || e.toString();
    console.log(error);
    return { code: 0, error, };
  }
}

Tương tự, các CRUD operations còn lại:

// Create Issue
// File: @/lib/issues/create.ts
export async function createTask(info: any) {
  try {
    const redis = (await import("../upstash/setup")).default;
    const id = Math.random().toString().slice(2) + new Date().getUTCMilliseconds();
    await redis.hset("issues", { [id]: info });
    return { code: 1, id, message: "Issue Created Succesfully ✅" };
  } catch (e: any) {
    const error = e.message || e.toString();
    console.log(error);
    return { code: 0, error, };
  }
}
// Delete Issue
// File: @/lib/issues/delete.ts
export async function deleteTask(id: string) {
  try {
    const redis = (await import("../upstash/setup")).default;
    await redis.hdel("issues", id);
    return { code: 1, message: "Deleted Succesfully!" };
  } catch (e: any) {
    const error = e.message || e.toString();
    console.log(error);
    return { code: 0, error, };
  }
}
// Update Issue Data
// File: @/lib/issues/update.ts
export async function updateTask(info: any, id: string) {
  try {
    const redis = (await import("../upstash/setup")).default;
    if (id) {
      const task = await redis.hget("issues", id);
      if (task) {
        await redis.hset("issues", { [id]: info });
        return { code: 1, message: "Updated Successfully" };
      }
    }
    return { code: 0, error: "No such issue was found.", };
  } catch (e: any) {
    const error = e.message || e.toString();
    console.log(error);
    return { code: 0, error, };
  }
}

Rate Limiting

Triển khai rate-limiting ở edge, dùng Upstash Redis database client và rate limiter library @upstash/ratelimit.

// Reference Function to ratelimiting
// File: @/lib/upstash/ratelimit.ts
import { Ratelimit } from "@upstash/ratelimit";
import redis from "./setup";
export const ratelimit = {
  upload: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(2, "60s"),
  }),
  issues: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(5, "60s"),
  }),
};

Dùng Rate Limiting đạt được:

A. Giới Hạn Số Lượng Issue Tạo Per User Phút

Dùng Rate Limiting, limit tạo 5 issues per authenticated user mỗi phút. Enforce rate limit dựa trên user email của authenticated user.

// File: @/routes/api/issue/+server.ts
// Issue Creation POST API SvelteKit Handler
import { ratelimit } from "@/lib/upstash/ratelimit";
export async function POST(event: RequestEvent) {
  const user = await isAuth(event);
  if (!user) {
    return new Response(undefined, { status: 403, });
  }
  if (user.session.user?.email) {
    // Look at the user email of authenticated user at edge
    // Rate limit 5 issues creation per minute
    const result = await ratelimit.issues.limit(user.session.user.email);
    if (!result.success) {
      return new Response(
        JSON.stringify({ code: 0, error: `You can't create more than 5 issues per minute.` }),
        { status: 403, headers: { "content-type": "application/json", }, },
      );
    }
    const { info } = await event.request.json();
    const res = await createTask(info);
    return json(res);
  }
  return new Response(undefined, { status: 403, });
}

B. Giới Hạn Số Lượng File Upload Per User Per Issue Phút

Dùng Rate Limiting, limit file uploads lên tới 2 per authenticated user per task mỗi phút. Enforce rate limit dựa trên user email authenticated user và task's ID. Khi upload thành công, update task trong Upstash DB với fileURL appended.

// File: @/routes/api/content/+server.ts
// File Upload POST API SvelteKit Handler
import { ratelimit } from "@/lib/upstash/ratelimit";
export async function POST(event: RequestEvent) {
  // User Authentication Code
  if (user.session.user?.email) {
    // Validate User, Task ID và nếu file uploaded
    // Look at the user email of authenticated user and task's ID at edge
    // Rate limit 2 uploads per minute
    const result = await ratelimit.upload.limit(
      `${user.session.user.email}_${taskID}`,
    );
    if (!result.success) {
      return new Response(
        JSON.stringify({ code: 0, error: `You can't upload more than 2 files per issue per minute.` }),
        { status: 403, headers: { "content-type": "application/json", }, },
      );
    }
    // File upload code
    // Continue reading the blog to see how
    // file uploads are being taken care of
  }
  return new Response(undefined, { status: 403, });
}

Xử Lý File Upload Và Download Với Firebase Storage

Phần này deep dive vào cách file upload/download của issue handled secure và authenticated manner trên SvelteKit edge. Tận dụng Firebase (v9) Storage fetch và upload file.

Tại Sao Không Dùng Cloudflare R2 Cho Storage?

Mặc dù thấy nhiều community advocacy cho free storage plan Cloudflare R2 và ưu điểm, điều khiến tôi ngại là cần đưa credit card cho Cloudflare trước khi thử system. Điều này khiến tôi suy nghĩ storage solution khác, và đến Firebase Storage cho 5 GB free storage, và nếu exceed, services stop thay vì charge credit card chưa được approve và biết điều gì xảy ra.

SvelteKit Edge Function Upload File Lên Firebase Storage

Trong Edge function sau, look at bất kỳ POST request event và nếu user authenticated, lấy taskID và file từ event formData. Xong, evaluate tiếp continue nếu file size dưới 5 MB. Khi prerequisites xong, tạo unique ID, tạo firebase reference đến unique folder file sẽ upload. Ngay khi file uploaded lên firebase, trả về URL truy cập file uploaded. Append unique URL này vào key files của issue data.

// File: @/routes/api/content/+server.ts
// File Upload POST API SvelteKit Handler
import { initializeApp } from "firebase/app";
import { getDownloadURL, getStorage, ref, uploadBytes } from "firebase/storage";
import fireBaseConfig from "../../../../firebase-adminsdk.json";
export async function POST(event: RequestEvent) {
  // User Authentication Code
  if (user.session.user?.email) {
    const app = initializeApp(fireBaseConfig);
    const storage = getStorage(app);
    const data = await event.request.formData();
    const taskID = data.get("taskID");
    const file = data.get("file");
    // ...Validate User, Task ID and if a file is uploaded
    // ...Rate Limiting Code
    // File Size Restriction(s)
    if (file.size > 5 * 1024 * 1024) {
      return new Response(
        JSON.stringify({ code: 0, error: "File size exceeds the limit of 5 MB." }),
        { status: 400, headers: { "content-type": "application/json", }, },
      );
    }
    // Start File Upload Code
    try {
      // Create a unique ID
      const fileId = uuidv4();
      // If uploaded is not a File type
      if (!(file instanceof File)) return;
      // Create a ref to firebase storage
      const storageRef = ref(storage, `uploads/${fileId}/${file.name}`);
      // Obtain the arrayBuffer of the file uploaded
      const fileBuffer = await file.arrayBuffer();
      // Upload file to Firebase Storage in bytes using Uint8Array
      const { metadata } = await uploadBytes(
        storageRef,
        new Uint8Array(fileBuffer),
      );
      const { fullPath } = metadata;
      // No fullPath is received, the API errored out
      if (!fullPath) {
        return new Response(
          JSON.stringify({ code: 0, error: `<span>There was some error while uploading the file.</span> <span class="mt-1 text-xs text-gray-500">Report an issue with the current URL that you are on and with the code XXX.</span>` }),
          { status: 403, headers: { "content-type": "application/json", }, },
        );
      }
      // If a file is uploaded successfully, append the file to list of attachments to the issue's data
      const { code, ...taskValues } = await getTask(taskID);
      if (code === 1) {
        if (taskValues) {
          if (taskValues.hasOwnProperty("files")) {
            taskValues["files"].push(
              `https://storage.googleapis.com/${storageRef.bucket}/${storageRef.fullPath}`,
            );
          } else {
            taskValues["files"] = [
              `https://storage.googleapis.com/${storageRef.bucket}/${storageRef.fullPath}`,
            ];
          }
        }
        // Update the task's data in Upstash
        await updateTask(taskValues, taskID);
      }
      return json({ code: 1, message: "Uploaded Successfully", });
    } catch (error) {
      return new Response(
        JSON.stringify({ code: 0, error: error.message || error.toString() }),
        { status: 403, headers: { "content-type": "application/json", }, },
      );
    }
  }
  return new Response(undefined, { status: 403, });
}

SvelteKit Edge Function Download File's Public URL Từ Firebase Storage

Như bạn nhớ, append unique URL trả về bởi Firebase vào key files của issue. Nhận unique URL đó làm image parameter trong GET request đến SvelteKit Edge Function retrieve original file. Dùng function getDownloadURL từ firebase library lấy public URL của original media.

// File: @/routes/api/content/+server.ts
// File Upload GET API SvelteKit Handler
import { initializeApp } from "firebase/app";
import { getDownloadURL, getStorage, ref, uploadBytes } from "firebase/storage";
import fireBaseConfig from "../../../../firebase-adminsdk.json";
export async function GET(event: RequestEvent) {
  if (!(await isAuth(event))) {
    return new Response(undefined, { status: 403, });
  }
  const url = event.url;
  const image = url.searchParams.get("image");
  if (image) {
    try {
      const app = initializeApp(fireBaseConfig);
      const storage = getStorage(app);
      const fileRef = ref(storage, image);
      const imagePublicURL = await getDownloadURL(fileRef);
      return json({ code: 1, image: imagePublicURL });
    } catch (error) {
      return new Response(
        JSON.stringify({ code: 0, error: error.message || error.toString() }),
        { status: 500, headers: { "content-type": "application/json", }, },
      );
    }
  }
  return new Response(JSON.stringify({ code: 0, error: "Invalid Request." }), {
    status: 400,
    headers: { "content-type": "application/json", },
  });
}

Như bạn đã nghĩ, có thể multiple media upload, handle trivial case image vs video, thêm if else sau vào front-end:

<!-- File: @/routes/issue/[slug]/+page.svelte -->
{#each fieldFiles as file}
  <div class="mt-8 w-full border border-white/25 p-3">
    {#if /\.(mp4|mov|mkv)/i.test(file)}
      <video class="h-auto w-full" src="{file}" controls>
        <track kind="captions" />
      </video>
    {:else}
      <img alt="{file}" src="{file}" class="h-auto w-full" />
    {/if}
  </div>
{/each}

Tại Sao Alternative Open Source Cho Jira Kanban Board?

Nhiều benefit khiến bạn chọn open source alternative thay vì mua giải pháp trả tiền nặng:

  • Tiết Kiệm Chi Phí Lớn: Một benefit lớn nhất dùng open source alternative là tiết kiệm chi phí. Khác với paid Kanban board như Jira, open source alternative xây bằng SvelteKit, TailwindCSS, Firebase Storage, Upstash Serverless DB, Rate Limiting dùng được không licensing fees.
  • Tùy Chỉnh Không Giới Hạn: Với open source alternative, bạn full control codebase và customize Kanban board theo nhu cầu cụ thể. Flexibility này thường không possible với paid solutions có limited customisation options.
  • Dễ Dàng Tích Hợp: Tận dụng power của APIs kết nối Kanban board với project management systems, version control tools, notification services, và hơn thế. Ngoài ra, bản chất open source cho phép developer extend functionality tạo plugins hoặc integrations tailored yêu cầu cụ thể.

Kết Luận

Kết luận, dự án cung cấp kinh nghiệm quý giá triển khai Granular Rate Limiting, CRUD data operations, implement Firebase Storage APIs get/upload file, tất cả ở edge với thư viện @upstash/redis của Upstash!