どのようにnextjsとfaunadbを使用して自分のbitlyクローンを作った🔥


私の使用bit.ly 私のURLを短くするが、彼らのダッシュボードは乱雑です.私は、私が好きでなかったウェブサイトに、より多くがあるということを意味します.それで、私は似たようなものを作るようにしましたが、短いリンクに集中するだけでした.だから、ここで私がしたことです.

使用技術

  • タイプスクリプト
  • ファウンダム
  • 日本学術振興会
  • 私がFaunadbとTypesScriptで働いているので、これは初めてです.

    コード


    マニトープ66 / URLの短縮


    URL短縮


    NextJSプロジェクトの作成


    以下のコマンドを実行して空のnextjsプロジェクトを起動します
    npx create-next-app url-shortener
    

    スクリプトの追加


    クリエイトアtsconfig.json ルートフォルダ内のファイルを以下のコマンドを実行します.
    yarn add --dev typescript @types/react @types/node
    
    改名_app.js to _app.tsx コードの下にペーストする
    import type { AppProps /*, AppContext */ } from "next/app";
    import "../styles/globals.css";
    
    function MyApp({ Component, pageProps }: AppProps) {
      return <Component {...pageProps} />;
    }
    
    export default MyApp;
    

    依存

  • Axios ( APIコール用)
  • faunadb ( Serverless DB用)
  • 一意のIDを生成する(短いURLを生成する場合)
  • データベースの作成

  • 移動するfaunadb
  • 無料アカウントとログインの作成
  • データベースを作成する
  • コレクションを作成するurls
  • 移動するkeys セクションを作成し、キーを作成してコピーする
  • クリエイトア.env.local ルートフォルダのファイルとキーを貼り付けます
  • NEXT_PUBLIC_FAUNA_KEY=YOUR_KEY
    

    メインロジック


    このアイデアは以下の形式のJSONオブジェクトを保存することです
    {
       "url":"https://dev.to",
       "short_url":"547382"
    }
    
    ユーザが入るたびに{your-domain}/547382 彼らはhttps://dev.to

    無記名関数の記述


    オリジナルURLから短いURLを作る


    移動するpages/api とファイルを作成するcreateUrl.ts
    import type { NextApiRequest, NextApiResponse } from "next";
    const generateUniqueId = require("generate-unique-id");
    const faunadb = require("faunadb"),
      q = faunadb.query;
    
    const client = new faunadb.Client({
      secret: process.env.NEXT_PUBLIC_FAUNA_KEY,
    });
    
    export default async (req: NextApiRequest, res: NextApiResponse) => {
      const { url } = req.body;
    
      const id = generateUniqueId({
        length: 8,
        useLetters: false,
      });
    
      try {
        const info = await client.query(
          q.Create(q.Collection("urls"), {
            data: {
              ourl: url,
              surl: id,
            },
          })
        );
    
        res.status(200).send(id);
      } catch (error) {
        res.status(400).send(error.message);
      }
    };
    

    短いURLから元のURLを取得するには


    移動するpages/api とファイルを作成するgetShortUrl.ts
    import type { NextApiRequest, NextApiResponse } from "next";
    const faunadb = require("faunadb"),
      q = faunadb.query;
    
    const client = new faunadb.Client({
      secret: process.env.NEXT_PUBLIC_FAUNA_KEY,
    });
    
    export default async (req: NextApiRequest, res: NextApiResponse) => {
      try {
        const ourl = await client.query(
          q.Map(
            q.Paginate(q.Match(q.Index("get_short_url"), req.body.url)),
            q.Lambda("X", q.Get(q.Var("X")))
          )
        );
    
        res.send(ourl.data[0].data.ourl);
      } catch (error) {
        res.status(400).send(error.message);
      }
    };
    
    それはバックエンドのためです!

    フロントエンド


    基本的に2路線
  • 短いURLを作成する
  • ユーザをリダイレクトする
  • 1 .短いURLを作成するには


    pages/index.tsx


    import Axios from "axios";
    import React, { useState } from "react";
    import Head from "next/head";
    const index = () => {
      const [url, setUrl] = useState<string>("");
      const [surl, setsUrl] = useState<string>("");
      const [load, setLoad] = useState<boolean>(false);
      const home =
        process.env.NODE_ENV === "development" ? "localhost:3000" : "zf.vercel.app";
    
      const getShortUrl = async () => {
        setLoad(true);
        await Axios.post("/api/createUrl", {
          url: url,
        })
          .then((res) => {
            setsUrl(`${home}/${res.data}`);
            setLoad(false);
          })
          .catch((e) => console.log(e));
      };
      return (
        <div className="container">
          <Head>
            <link rel="preconnect" href="https://fonts.gstatic.com" />
            <link
              href="https://fonts.googleapis.com/css2?family=Acme&display=swap"
              rel="stylesheet"
            />
            <title>URL Shortener 🐱‍🚀</title>
          </Head>
          <h1 className="title">
            URL Shortener <span>😎</span>
          </h1>
          <input
            className="inp"
            placeholder="enter URL to be shorten"
            onChange={(e) => setUrl(e.target.value)}
          />
          <style jsx>{`
            .container {
              display: flex;
              padding: 10px;
              flex-direction: column;
              justify-content: center;
              align-items: center;
            }
            .title {
              font-family: "Acme", sans-serif;
              font-size: 20px;
            }
            .inp {
              padding: 20px;
              margin: 10px;
              width: 80%;
              border-radius: 5px;
              border: 1px solid #000;
              border-radius: 5px;
              text-align: center;
              font-family: "Acme", sans-serif;
              font-size: 20px;
            }
            .btn {
              padding: 10px 20px;
              margin: 10px;
              border: none;
              background: #3254a8;
              color: white;
              border-radius: 10px;
              font-family: "Acme", sans-serif;
              font-size: 20px;
              cursor: pointer;
            }
            .surl {
              font-family: "Acme", sans-serif;
              padding: 10px;
              margin: 10px;
              background-color: #32a852;
              border-radius: 10px 20px;
              color: white;
            }
          `}</style>
          <button onClick={getShortUrl} className="btn">
            {load ? "loading" : "Shorten"}
          </button>
          {surl.length > 0 ? <p className="surl">{surl}</p> : null}
        </div>
      );
    };
    
    export default index;
    

    出力



    2リダイレクトルートを作成するには


    この部分は難しいです、我々はこのルートでユーザーに何も表示する必要はありません.我々は、単に元のURLに
    URL内のクエリ

    pages/[url].tsx


    import Axios from "axios";
    import { GetServerSideProps } from "next";
    
    const Url = () => {
      return null;
    };
    
    export const getServerSideProps: GetServerSideProps = async (context: any) => {
      const { url } = context.params;
    
      const home =
        process.env.NODE_ENV === "development"
          ? "http://localhost:3000"
          : "https://zf.vercel.app";
    
      const info = await Axios.post(`${home}/api/getShortUrl`, {
        url: url,
      });
      return {
        redirect: {
          destination: info.data,
          permanent: true,
        },
      };
    };
    
    export default Url;
    
    それだ!以下のコマンドをローカルで実行するには
    yarn dev
    

    Give a ⭐