Vue + Supabase를 사용한 실시간 구독

이봐, 내가 무슨 말을하는지 모르겠다면 읽어야 해.

문맥:

Vue + Supabase(오픈 소스 Firebase 대안)를 사용하여 마이크로블로그를 만들었습니다. 오늘 우리는 데이터베이스에 삽입될 때마다 새 출판물을 보여줄 것입니다.


우리의 출발점은 지난 기사에서 생성된 코드가 될 것이며, repository to view the source code에 액세스할 수 있습니다.

git의 메인 브랜치는 main 입니다. 이 브랜치에서 feat/add-subscription ( you can access it here )라는 브랜치를 만들 것입니다. 명령줄에서 다음 명령을 사용하여 이 작업을 수행할 수 있습니다.

// git clone [email protected]:ftonato/vue-supabase-microblog.git
// cd vue-supabase-microblog

git checkout -b feat/add-subscription


documentation 을(를) 검색하면 구독 방법을 자세히 알아볼 수 있습니다.

구독은 데이터베이스에서 실시간으로 변경 사항을 보는 것과 같습니다. 즉, 이벤트( INSERT , UPDATE , DELETE , * )가 발생할 때마다 함수를 트리거할 수 있습니다.

예:

const mySubscription = supabase
  .from('*')
  .on('*', payload => {
    console.log('Change received!', payload)
  })
  .subscribe()


위의 예에서 우리는 애플리케이션에 "이벤트가 발생할 때마다 테이블이 무엇이든 console.log를 사용하여 페이로드 정보를 인쇄합니다.

우리가 할 일은 예제와 비슷하지만 두 가지 다른 세부 사항이 있습니다.
  • 우리는 하나의 테이블( posts )에서만 볼 것입니다.
  • 우리는 INSERT 이벤트에서만 보고 싶습니다.



  • List.vue 파일에서 subscriptionPosts라는 새 변수와 subscribePosts 메서드를 만듭니다.

    구성 요소를 조립할 때( mounted ) 이 메서드를 호출하고 그 책임은 다음과 같습니다.
  • 이 테이블에 새 레코드가 삽입될 때마다 posts 변수(게시물을 저장하는 로컬 변수)에 추가하십시오.

  • 구현이 있는 코드 아래:

    <template>
      <section class="px-2 pt-16 pb-6 bg-white md:px-0">
        <div class="container items-center max-w-6xl px-8 mx-auto xl:px-5">
          <template v-for="(post, index) in posts">
            <list-item
              :key="`post-${index}`"
              :id="post.id"
              :title="post.title"
              :description="post.description"
            />
          </template>
        </div>
      </section>
    </template>
    
    <script>
    import ListItem from "./ListItem";
    import DatabaseService from "../Database.service";
    
    export default {
      name: "List",
      components: {
        ListItem,
      },
      data: () => ({
        posts: [],
        database: null,
        subscriptionPosts: undefined,
      }),
      created() {
        const database = new DatabaseService();
        this.database = database.getInstance();
      },
      async mounted() {
        await this.fetchPosts();
        this.subscribePosts();
      },
      methods: {
        async fetchPosts() {
          let { error, data } = await this.database
            .from("posts")
            .select()
            .order("id");
          if (error) {
            console.error(error);
            return;
          }
    
          this.setPosts(data);
        },
        setPosts(posts) {
          this.posts = posts;
        },
        subscribePosts() {
          this.subscriptionPosts = this.database
            .from("posts")
            .on("INSERT", (message) => {
              if (message.new) {
                this.posts.push(message.new);
              }
            })
            .subscribe();
        },
      },
    };
    </script>
    


    실시간 구독을 구현하기 위해 필요한 코드입니다.

    결과를 볼 준비가 되셨습니까?



    확실히 장관입니다!


    위에서 수행한 작업으로 충분하지만 응용 프로그램을 약간 관리하고 구성 요소 분해(destroyed)에서 구독을 제거해 보겠습니다.

    Always unsubscribe, when new values in the subscribed stream is no more required or don't matter, it will result in way less number of triggers and increase in performance in a few cases.



    구독 제거를 담당할 unsubscribePosts라는 메서드를 만듭니다.

    <template>
      <section class="px-2 pt-16 pb-6 bg-white md:px-0">
        <div class="container items-center max-w-6xl px-8 mx-auto xl:px-5">
          <template v-for="(post, index) in posts">
            <list-item
              :key="`post-${index}`"
              :id="post.id"
              :title="post.title"
              :description="post.description"
            />
          </template>
        </div>
      </section>
    </template>
    
    <script>
    import ListItem from "./ListItem";
    import DatabaseService from "../Database.service";
    
    export default {
      name: "List",
      components: {
        ListItem,
      },
      data: () => ({
        posts: [],
        database: null,
        subscriptionPosts: undefined,
      }),
      created() {
        const database = new DatabaseService();
        this.database = database.getInstance();
      },
      async mounted() {
        await this.fetchPosts();
        this.subscribePosts();
      },
      destroyed() {
        this.unsubscribePosts();
      },
      methods: {
        async fetchPosts() {
          let { error, data } = await this.database
            .from("posts")
            .select()
            .order("id");
          if (error) {
            console.error(error);
            return;
          }
    
          this.setPosts(data);
        },
        setPosts(posts) {
          this.posts = posts;
        },
        subscribePosts() {
          this.subscriptionPosts = this.database
            .from("posts")
            .on("INSERT", (message) => {
              if (message.new) {
                this.posts.push(message.new);
              }
            })
            .subscribe();
        },
        unsubscribePosts() {
          this.database.removeSubscription(this.subscriptionPosts);
        },
      },
    };
    </script>
    



    그게 다야!

    이것이 응용 프로그램에 제공하는 힘을 생각해 보십시오. 제가 지난 간행물에서 말했듯이: 상상력이 여러분을 인도하고 새로운 지평을 탐험하게 하십시오.

    우리가 만든 프로젝트의 소스 코드에 관심이 있다면 GitHub의 프로젝트 디렉토리로 이동하여 다음과 같은 더 흥미로운 것을 구현하십시오.

    질문이 있는 경우 주저하지 말고 저에게 연락하십시오( [email protected]/또는 Supabase team ).

    좋은 웹페이지 즐겨찾기