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

Xây Dựng LinkTree Alternative Miễn Phí, Open-Source Với Astro, Upstash Và GitHub

Trong bài này, tôi nói về cách itsmy.fyi (alternative open-source cho LinkTree) xây dựng với Upstash, Astro, GitHub và Edgio. Upstash giúp manage (CRUD) data tất cả user, offer rate limiting hào phóng hơn so với GitHub API cho CRUD operations, và implement granular rate limiting.

Xây Dựng LinkTree Alternative Miễn Phí, Open-Source Với Astro, Upstash Và GitHub

Công Nghệ Sử Dụng

  • Astro (Front-end và Back-end)
  • Upstash (Rate Limiting & CRUD Operations)
  • GitHub Issue & Webhooks (Public CMS manage user profiles)
  • Tailwind CSS (Styling)
  • Edgio (Deployment)

Những Gì Bạn Cần

  • Tài khoản GitHub
  • Tài khoản Upstash tạo database

Thiết Lập Upstash Redis

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

Xây Dựng LinkTree Alternative Miễn Phí, Open-Source Với Astro, Upstash Và GitHub

Xây Dựng LinkTree Alternative Miễn Phí, Open-Source Với Astro, Upstash Và GitHub

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

Xây Dựng LinkTree Alternative Miễn Phí, Open-Source Với Astro, Upstash Và GitHub

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 LinkTree Alternative Miễn Phí, Open-Source Với Astro, Upstash Và GitHub

Thiết Lập Dự Án

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

git clone https://github.com/rishi-raj-jain/itsmy.fyi
cd itsmy.fyi
yarn install

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

Trông như:

# Obtained from your GitHub repo
GITHUB_API_TOKEN="to_create_and_update_github_comments"
GITHUB_WEBHOOK_SECRET="if_you_are_matching_github_webhooks_sha256"
# Obtained from the steps as above
UPSTASH_DB="your_upstash_redis_from_above"
UPSTASH_REDIS_REST_URL="your_upstash_redis_rest__url_from_above"
UPSTASH_REDIS_REST_TOKEN="your_upstash_redis_rest__token_from_above"

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

yarn run edgio:dev

Cấu Trúc Repository

Cấu trúc folder chính dự án. Đã khoanh tròn đỏ các file sẽ thảo luận tiếp deal với CRUD Operations, Rate Limiting và file chúng referenced.

Xây Dựng LinkTree Alternative Miễn Phí, Open-Source Với Astro, Upstash Và GitHub

High-Level Data Flow

High-level diagram data flow.

  • Nếu user visit itsmy.fyi/me/slug và response page không cached (hoặc revalidating), gọi function getUserInfo lần lượt retrieve user json từ Upstash DB
  • Nếu user create(s), update(s) hoặc delete(s) GitHub Issue, GitHub trigger Webhook POST đến endpoint. Trong endpoint, trước dùng Upstash Rate Limiting evaluate nếu requested change có thể làm, sau đó dùng Upstash create, update hoặc delete user json(s).

Xây Dựng LinkTree Alternative Miễn Phí, Open-Source Với Astro, Upstash Và GitHub

User Profile(s) CRUD Operations Via Upstash Redis

Phần này deep dive vào cách data fetching, updating, deletion cho user profile(s). Liên tục dùng Upstash (via ioredis) fetch và display data.

Tại Sao Chuyển Từ GitHub Sang Upstash Cho CRUD Operations?

Mặc dù bắt đầu với GitHub như source data management: từ Github Issues làm data forms đến GitHub Webhooks CRUD user jsons trong repository, giới hạn GitHub REST API: 1,000 requests per hour per repository dường như restrict và regress intended usage platform.

Upstash nổi bật hơn vì offer 10K commands daily free plan, và rate rất minimal khi usage scale. Approach này cho phép greater user acquisition near zero cost, iterate faster mà không lo scaling và managing cost database.

getUserInfo: Function Lấy User Profile

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

// File: lib/Upstash/users/get.js
// Read User Profile Code
import redis from "../setup";
export async function getUserInfo(slug) {
  try {
    const userData = await redis.hget("profiles", slug);
    const parsedData = JSON.parse(userData);
    if (parsedData.slug === slug) {
      return { ...parsedData, code: 1 };
    }
    return { code: 0, error: `slug doesn't match for the user.`, };
  } catch (e) {
    const error = e.message || e.toString();
    console.log(error);
    return { code: 0, error, };
  }
}

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

import redis from "../setup";
// File: @/lib/Upstash/users/delete.js
// Delete User Profile Code
export async function deleteUserInfo(slug) {
  try {
    await redis.hdel("profiles", slug);
    return { code: 1 };
  } catch (e) {
    console.log(e.message || e.toString());
    return { code: 0, };
  }
}
// File: @/lib/Upstash/users/post.js
// Create/Update User Profile Code
export async function postUserInfo(data) {
  try {
    await redis.hset("profiles", data.slug, JSON.stringify(data));
    return { code: 1 };
  } catch (e) {
    const error = e.message || e.toString();
    console.log(error);
    return { code: 0, error, };
  }
}

Rate Limiting

Triển khai rate-limiting trong serverless environments với Edgio, dùng Upstash Redis database client và rate limiter library @upstash/ratelimit.

// Reference Function to ratelimiting
// @/lib/Upstash/ratelimit.js
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { getENV } from "@/lib/env";
const url = getENV("UPSTASH_REDIS_REST_URL");
const token = getENV("UPSTASH_REDIS_REST_TOKEN");
export const ratelimit = (number, time) => {
  if (url && token) {
    return new Ratelimit({
      redis: new Redis({ url, token, }),
      limiter: Ratelimit.fixedWindow(number, time),
    });
  }
  return;
};

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

A. Làm Việc Dịch Vụ - Hoàn Toàn Free & Unlimited

Dùng Rate Limiting, expose profile creation API publicly! Cho phép showcase benefits hệ thống: ease of setup profile via GUI. Bất kỳ ai tạo 3 profiles trong tuần qua website (itsmy.fyi) chính nó, và unlimited access features như edit profile, create unlimited profiles, user switch sang GitHub way tạo profile. Enforce rate limit 3 profiles trong tuần dựa trên IP address làm key.

// Rate limit 3 profiles in a week via the web for a user
const ratelimitUser = ratelimit(3, 7 * 24 * 60 * 60 + " s");
if (rateLimiter) {
  // Look at the x-0-client-ip set by Edgio in serverless
  const result = await rateLimiter.limit("x-0-client-ip");
  limit = result.limit;
  remaining = result.remaining;
  if (!result.success) {
    // Return a message
  }
}

B. Triển Khai Granular Moderation Số Lượng Edit Bởi User

Cũng qua Rate Limiting, moderate số edit user làm trong phút dựa trên GitHub usernames. Hiện tại cho phép lên tới 3 changes trong một phút. Giúp giảm unseen spam.

// @/pages/github/hook/issue.js
const rateLimiter = ratelimit(3, "60 s");
if (rateLimiter) {
  const result = await rateLimiter.limit(context.sender.login);
  limit = result.limit;
  remaining = result.remaining;
  if (!result.success) {
    return {
      headers: {
        "X-RateLimit-Limit": limit,
        "X-RateLimit-Remaining": remaining,
      },
      body: JSON.stringify({ message: "Too many updates in 1 minute. Please try again in a few minutes.", }),
    };
  }
}

Triển Khai Stale-While-Revalidate Trên Edge Cho Tất Cả User Profiles

Code sau mô tả cách dùng concept Stale While Revalidate cải thiện cache hit rates. Trong code (trong routes.js), function router.match match tất cả user profiles (bắt đầu /me/). Bên trong cache method, prevent caching page trong browser và enable chỉ edge caching luôn serve user fast và latest content. Option edge set maxAgeSeconds: 1 đảm bảo data cached chỉ một giây. Option staleWhileRevalidateSeconds set một năm cho phép data served trực tiếp từ cache trong khi cache được refresh.

// User path(s)
router.match("/me/:path", ({ cache, removeUpstreamResponseHeader }) => {
  // Remove the cache-control header from Astro's standalone server
  removeUpstreamResponseHeader("cache-control");
  // Disable in browser caching, and use Edgio's edge to use SWR
  cache({
    edge: {
      maxAgeSeconds: 1,
      staleWhileRevalidateSeconds: 60 * 60 * 24 * 365,
    },
    browser: false,
  });
});

Dùng Stale While Revalidate cải thiện performance app bằng cách giảm load server và cung cấp response nhanh hơn cho user.

Tạo Dynamic User Profiles On The Fly

Astro làm super easy setup dynamic routes. Trong app, tìm src/pages/me/[slug].astro, map page bắt đầu /me/. Ví dụ /me/rishi-raj-jain và /me/some-other-user.

Fetching User Profiles

Fetch data current user bằng cách dùng slug query parameter extracted từ Astro params, gọi function getUserInfo (mô tả trên) lấy tất cả related user data. Trường hợp not found hoặc error, redirect visitor đến 404.

import { getUserInfo } from "@/lib/Upstash/users";
// Extract slug query
const { slug } = Astro.params;
// Get data from Upstash using the getUserInfo function
const { name: userName, image: userImage, links = [], socials = [], about = "", og = {}, background = {}, code = 1, } = await getUserInfo(userSlug);
// In case the code: 0 is recevied, redirect to a 404
if (code === 0) {
  return Astro.redirect("/404");
}

Deploy Từ CLI

Production build app test local dùng:

yarn run edgio:build && yarn run edgio:production

Deploy yêu cầu account Edgio. Sign up free tại đây. Khi có account, deploy Edgio chạy lệnh sau root folder project:

yarn run edgio:deploy

Xong deployment! Vâng, chỉ thế thôi.

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 trong serverless, dùng GitHub issues làm CMS, và quyết định tốt hơn ship MVP dùng service scale theo nhu cầu, ví dụ Upstash.