100秒内即可实现实时离线聊天应用

2025-06-10

100秒内即可实现实时离线聊天应用

Amplify DataStore提供了一个持久的设备存储库,供您在在线或离线时写入、读取和观察数据变化,并无缝同步到云端以及跨设备。

它是免费的、开源的,并由AWS Amplify团队提供支持。我想向您展示如何轻松地使用它为您的应用添加实时、离线优先的 CRUD 功能!在本例中,我们将使用 React,但您也可以轻松地使用本指南为使用任何框架构建的应用添加实时、离线优先的 CRUD 功能。

100秒视频版

YouTube:https://youtu.be/pSSfTWqSXbU

Dev.to 嵌入:

基于文本的版本 - 3 个步骤

下面的内容是上面视频的脚本,因此您可以复制/粘贴!

步骤 1:设置 React Chat 应用

假设您已经设置了 Amplify CLI,我们将启动一个标准的 React 应用程序并安装我在包下准备的一个特殊的演示聊天react-demos组件

npx create react-app amplifychatapp
cd amplifychatapp
yarn add react-demos # or npm install react-demos
Enter fullscreen mode Exit fullscreen mode

让我们尝试一下这个演示组件来熟悉它!

// src/App.js
import React from 'react'
import { Chat, useChatLocalState } from 'react-demos'

export default function App() {
  const {
    currentUser,
    sendMessage,
    loginUser,
    messages,
    usersOnline,
  } = useChatLocalState()
  return (
    <div>
      <Chat
        {...{
          currentUser,
          sendMessage,
          loginUser,
          messages,
          usersOnline,
        }}
      />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

现在我们可以启动应用了npm run start,它运行起来了!不过,这些数据不会被存储或共享——当你重新加载页面或在隐身浏览器中加载时,消息会从头开始。这可不像个聊天应用!

步骤 2:设置 Amplify DataStore

我们将启动一个新的 Amplify 项目,并amplify add api确保启用“冲突解决”(启用 Amplify 数据存储):

yarn add aws-amplify @aws-amplify/datastore 
# or use npm install

amplify init 
# go with all default answers... and when you are done...

amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: # Any Name Is Fine
? Choose the default authorization type for the API API key
? Enter a description for the API key: # Any Description Is Fine
? After how many days from now the API key should expire (1-365): 7
? Do you want to configure advanced settings for the GraphQL API Yes, I want to make some additional changes.
? Configure additional auth types? No
? Configure conflict detection? Yes # IMPORTANT
? Select the default resolution strategy Auto Merge
? Do you have an annotated GraphQL schema? No
? Choose a schema template: Single object with fields (e.g., “Todo” with ID, name, description)
# some instructions here...
? Do you want to edit the schema now? Yes
Enter fullscreen mode Exit fullscreen mode

这将打开您的编辑器,我们可以在其中为数据存储区指定 GraphQL 架构(它与AWS AppSync 的 GraphQL Transform完全相同的架构定义语言)。我们将粘贴这个非常简单的架构:

# /amplify/backend/api/YOURAPINAME/schema.graphql
type User @model {
  id: ID!
  name: String
}

type Message @model {
  id: ID!
  user: String
  text: String
}
Enter fullscreen mode Exit fullscreen mode

保存文件并amplify push --y开始配置 AWS 后端!

在此过程中,我们将运行amplify codegen models并生成我们将在 React 应用程序中使用的DataStore 模型。

步骤 3:将 DataStore 与 React 连接起来

现在让我们开始使用它:


import React from "react";
import { DataStore } from "@aws-amplify/datastore";
import { User, Message } from "./models";
import { Chat } from "react-demos";
import Amplify from 'aws-amplify';
import awsconfig from './aws-exports';
Amplify.configure(awsconfig); // will not sync if you forget this

function App() {
  const [currentUser, setCurrentUser] = React.useState(null);
  const [usersOnline, setUsersOnline] = React.useState([]);
  const [messages, setMessages] = React.useState([]);

  React.useEffect(() => {
    fetchMessage();
    DataStore.observe(Message).subscribe(fetchMessage);
  }, []);
  React.useEffect(() => {
    fetchMessage();
    DataStore.observe(User).subscribe(() => 
      DataStore.query(User).then(setUsersOnline)
    );
  }, []);
  async function fetchMessage() {
    const _Messages = await DataStore.query(Message);
    setMessages(_Messages);
  }

  async function loginUser(name) {
    const user = await DataStore.save(new User({ name }));
    setCurrentUser(user);
  }
  async function sendMessage(text) {
    await DataStore.save(
      new Message({
        user: currentUser.name,
        text,
      })
    );
  }

  return (
    <div>
      <Chat
        {...{
          currentUser,
          sendMessage,
          loginUser,
          messages,
          usersOnline,
        }}
      />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

现在您已经拥有了它 - 一个带有 Amplify DataStore 的实时、离线持久聊天应用程序!

结论

现在您已经初步了解了,请务必前往文档以获得更全面的了解,或者观看 Richard Threlkeld 的 Re:Invent 2019 演讲,其中首次介绍了 Amplify DataStore!

附言:如果您担心按照本指南操作会产生 AWS 费用,只需amplify delete在最后运行以下命令即可删除您刚刚设置的所有内容!Amplify DataStore 本身免费使用,但它使用AWS AppSync 进行存储,因此您在计划生产使用时应查看其定价。

分享

喜欢这个格式/教程/视频吗?想看更多?欢迎评论分享,或者订阅我的 YouTube 频道

鏂囩珷鏉ユ簮锛�https://dev.to/swyx/realtime-offline-first-chat-app-in-100-seconds-with-amplify-datastore-react-and-graphql-47d4
PREV
21+ 个地方为您的网站/应用程序寻找免费插图、高清图像和图标
NEXT
设置 React + Typescript Storybook 设计系统的快速指南 简短版本 DIY 版本 您的第一个 Typescript 组件 是时候构建和发布您的(一键式)设计系统了