快速入门|使用MemFire Cloud构建Next.js应用程序

MemFire Cloud是一款提供云数据库,用户可以创建云数据库,并对数据库进行管理,还可以对数据库进行备份操作。它还提供后端即服务,用户可以在1分钟内新建一个应用,使用自动生成的API和SDK,访问云数据库、对象存储、用户认证与授权等功能,可专注于编写前端应用程序代码,加速WEB或APP应用开发。

快速入门|使用MemFire Cloud构建Next.js应用程序

此示例提供了使用 MemFire Cloud 和 Next.js构建简单用户管理应用程序(从头开始)的步骤。这包括:

  • MemFire Cloud云数据库:用于存储用户数据的 MemFireDB数据库。

  • MemFire Cloud用户验证:用户可以使用魔法链接登录(不需要密码,只需要电子邮件)。

  • MemFire Cloud存储:用户可以上传照片。

  • 行级安全策略:数据受到保护,因此个人只能访问自己的数据。

  • 即时API:创建数据库表时会自动生成 API。

在本指南结束时,您将拥有一个允许用户登录和更新一些基本个人资料详细信息的应用程序:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-K6Vnosrg-1663723902918)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=ZDUyZjU2MWZmZmI0NjdhMjBlZDUzZWQxZWY2NmNhNWVfd3ZVZk03Qmw3bGtkTndqYU9tVEtCVndJdjF4ZmhxNFBfVG9rZW46Ym94Y25PUDNDcDZ5bWJxV0hVWTR4ZHZWNlRiXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

创建应用

目的:我们的应用就是通过在这里创建的应用来获得数据库、云存储等一系列资源,并将获得该应用专属的API访问链接和访问密钥,用户可以轻松的与以上资源进行交互。

登录https://cloud.memfiredb.com/auth/login创建应用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-44KaEAKR-1663723902919)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=N2I3ZmRjMDRjOTVjMzk3NTg3MWVjNTcxNTdiZmNhZjdfVFFERDZGMWZaanBwUFc4ckdvY1JyVTRRQXBFMzBHWXNfVG9rZW46Ym94Y24yMzJuYWN2YTF4SjRITUlrYVluQWplXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

创建数据表

点击应用,视图化创建数据表

  1. 创建profiles表;

在数据表页面,点击“新建数据表”,页面配置如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qQ3sQCXy-1663723902919)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=NTA2NmQyOTkwZmY0NDQ3MjNjNmU4OGY4OWRmY2JjZDFfTlJlSVAyRG9RZkV3UGpUTWRPN0lVNG1nT1VrWWRJSnVfVG9rZW46Ym94Y25jTEVUQ0NuODNDWnFUMFpGRHJUZFBlXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

其中profiles表字段id和auth.users表中的id字段(uuid类型)外键关联。

  1. 开启Profiles的RLS数据安全访问规则;

选中创建的Profiles表,点击表权限栏,如下图所示,点击"启用RLS"按钮

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kV37ml76-1663723902919)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=OWMxMWMzZDE1Yzk4MDc2ODg1M2VmMzE4NDU0OTdmNDZfZWJwWW5tb2ZJZTJHUk5xcVpTaGIwcU1vZjEyWE9sMzFfVG9rZW46Ym94Y25oeWtyQmdZYllidWUwTHVXcU9vYTllXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

  1. 允许每个用户可以查看公共的个人信息资料;

点击"新规则"按钮,在弹出弹框中,选择"为所有用户启用访问权限",输入策略名称,选择"SELECT(查询)"操作,点击“创建策略”按钮,如下图。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2l1hVXUA-1663723902920)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=ZDI3NjMxNzZhNGU4YzU3MDNiNDJiZGYxZjNkNDc0NzBfaW9TeU1ZbTVHV2pBOXhYVnphbDZRaGtOM1RoZVMyYkFfVG9rZW46Ym94Y25aWXBsbnRNSkpPYWdHeUlmMzJlM0xjXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

  1. 仅允许用户增删改查本人的个人资料信息;

点击"新规则"按钮,在弹出弹框中,选择"根据用户ID为用户启用访问权限",输入策略名称,选择"ALL(所有)"操作,点击“创建策略”按钮,如下图。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HbIoZJgF-1663723902925)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=YzIwNDhiNTJlNDA2M2QzZTViMGVlODc4ZDYwOWMxNTBfUmpPd2JsbGR2dk85ZTh3SXlYcjFnZVpGNmxndXE1b0ZfVG9rZW46Ym94Y25mRGkwSUtCYXM3RG5BNWh2UUR5MkpnXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

创建avatars存储桶

创建云存储的存储桶,用来存储用户的头像图片,涉及操作包括:

  1. 创建一个存储桶avatars

在该应用的云存储导航栏,点击“新建Bucket”按钮,创建存储桶avatars。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-crdjl4dB-1663723902926)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=MWYxMDM5Y2YyMThlMDJkZDhjYWZhM2ZkY2JjMDE3NDRfR3FOVHVDQ0ptSVRWV0RoTVpPVW52ZFdLbGx5RUdQTVpfVG9rZW46Ym94Y25SSDV0Mlh6bVp6aVRIZWdBQmtLYU44XzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

  1. 允许每个用户可以查看存储桶avatars

选中存储桶avatars,切换到权限设置栏,点击“新规则”按钮,弹出策略编辑弹框,选择“自定义”,如下图所示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-puWZV2DP-1663723902927)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=NjNmMmU4OTlkNWIzYjk1NDM5MDUxM2UxZjlkODZkMGNfV29IUU90dEEyQlRBVzNaaXhyNFVtQ0l6ZE4zOUxXcGlfVG9rZW46Ym94Y25jUnVkbEVFVWV4VDdHNFdHTklDdXhkXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

选择SELECT操作,输入策略名称,点击“生成策略”按钮,如下图所示。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xd2SHI8A-1663723902927)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=MTBiNWQ4MTU4NTRhOTFmNjBiMWZkZjdhYTkzNzllZWRfa20yTjBUZmFsZThFd1hQamNaZXpUYnMwbldTUmIwVFZfVG9rZW46Ym94Y25JRkdXTHg1bDk0WGdxVlA5WGRIMkxiXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

  1. 允许用户上传存储桶avatars;

选中存储桶avatars,切换到权限设置栏,点击“新规则”按钮,弹出策略编辑弹框,选择“自定义”,如下图所示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2X3SUcGT-1663723902928)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=Y2MwNTYwNDE5ZjU2M2U2NzgyNzAwNzkzYWNmNmQyMjVfZjZtTkI3M0pDdVV0ZURCaUw4ZEZzMzE2RExacjZ0a0VfVG9rZW46Ym94Y25lTzBYR29LcU9kUXlkbGdYN0hpSU9kXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

选择INSERT操作,输入策略名称,点击“生成策略”按钮,如下图所示。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bwStQMiv-1663723902929)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=MjljYjViYjM0NDJmMGVjZGY0YjFmYjIwYTQzMjVhMDVfM0N1ZWcyTnl0Znh1S242TWRUa3RyN25nRXZrN0VhTEtfVG9rZW46Ym94Y25vT2tDV0YzMUc4elhydnBxeWMxb29kXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

查看结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7gmJKS6u-1663723902929)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=MzJiY2YzMzU4MTNkYjg1M2MxNzgyNzdiZjEzNjU2NDNfS1o1NUprY2l0eWtJVXM0b0Myc0NzOElBSHNQd0dtZjBfVG9rZW46Ym94Y25rcDVubkpGM1c1aG9CaDN6RDhUODJmXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

所有数据表及RLS的sql(策略名称用英文代替)

-- Create a table for public "profiles"
create table profiles (
  id uuid references auth.users not null,
  updated_at timestamp with time zone,
  username text unique,
  avatar_url text,
  website text,

  primary key (id),
  unique(username),
);

alter table profiles enable row level security;

create policy "Public profiles are viewable by everyone."
  on profiles for select
  using ( true );

create policy "Users can insert their own profile."
  on profiles for insert
  with check ( auth.uid() = id );

create policy "Users can update own profile."
  on profiles for update
  using ( auth.uid() = id );
-- Set up Storage!
insert into storage.buckets (id, name)
values ('avatars', 'avatars');

create policy "Avatar images are publicly accessible."
  on storage.objects for select
  using ( bucket_id = 'avatars' );

create policy "Anyone can upload an avatar."
  on storage.objects for insert
  with check ( bucket_id = 'avatars' );

获取 API密钥

现在您已经创建了一些数据库表,您可以使用自动生成的 API 插入数据。我们只需要从API设置中获取您在上面复制的URL和anon的密钥。

在应用->概括页面,获取服务地址以及token信息。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-p172GkuF-1663723902929)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=OTI0OGNkODdkMmQxZWE4ZTZkZDJmNTA1Y2JhMDFhZjVfU3VzY2tMTVlTVmZOR0REN2x1QnBWWHZ2N1lzY0s3TlJfVG9rZW46Ym94Y25neVZSYlQ5MVRrd0p6VVVsS3JKVGZjXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

Anon(公开)密钥是客户端API密钥。它允许“匿名访问”您的数据库,直到用户登录。登录后,密钥将切换到用户自己的登录令牌。这将为数据启用行级安全性。

注意:service_role(秘密)密钥可以绕过任何安全策略完全访问您的数据。这些密钥必须保密,并且要在服务器环境中使用,绝不能在客户端或浏览器上使用。 在后续示例代码中,需要提供supabaseUrl和supabaseKey。

认证设置

当用户点击邮件内魔法链接进行登录时,是需要跳转到我们应用的登录界面的。这里需要在认证设置中进行相关URL重定向的配置。

因为我们最终的应用会在本地的3000端口启动(亦或者其他端口),所以这里我们暂时将url设置为http://localhost:3000/

除此之外,在此界面也可以自定义使用我们自己的smtp服务器。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gNdiMOe8-1663723902929)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=MDY2NmZkNWEyZjJiZDY2YWU3MTcwM2Y1MTk1ODY3NjZfbXBRekllUWZzMEkzNk9RUVdOc2o5WGoyMmFVd0E4THVfVG9rZW46Ym94Y240eVZQREM4M3lzbEw3YW0wY0Z3TTVnXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

构建应用程序

让我们从头开始构建 NextJs 应用程序。

初始化一个 NextJs 应用程序

我们可以create-next-app用来初始化一个名为memfiredb-nextjs:

npx create-next-app memfiredb-nextjs
cd memfiredb-nextjs

然后让我们安装唯一的附加依赖项:supabase-js

npm install @supabase/supabase-js

最后,我们需要创建一个可以访问我们应用程序数据的客户端,我们使用了Supabase 客户端,使用他生态里提供的功能(登录、注册、增删改查等)去进行交互。创建一个可以访问我们应用程序数据的客户端需要接口的地址(URL)和一个数据权限的令牌(ANON_KEY),我们需要去应用的概览里面去获取这两个参数然后配置到supabaseClient.js里面去。

utils/supabaseClient.js

import { createClient } from '@supabase/supabase-js'

const url = URL
const key = ANON_KEY

export const supabase = createClient(url, key)

更新样式

可以看到界面实在是不怎么优雅,更新下样式,让它好看一些。 修改styles/globals.css文件。

html,
body {
  --custom-font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu,
    Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  --custom-bg-color: #101010;
  --custom-panel-color: #222;
  --custom-box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.8);
  --custom-color: #fff;
  --custom-color-brand: #24b47e;
  --custom-color-secondary: #666;
  --custom-border: 1px solid #333;
  --custom-border-radius: 5px;
  --custom-spacing: 5px;

  padding: 0;
  margin: 0;
  font-family: var(--custom-font-family);
  background-color: var(--custom-bg-color);
}

* {
  color: var(--custom-color);
  font-family: var(--custom-font-family);
  box-sizing: border-box;
}

html,
body,
#__next {
  height: 100vh;
  width: 100vw;
  overflow-x: hidden;
}

/* Grid */

.container {
  width: 90%;
  margin-left: auto;
  margin-right: auto;
}
.row {
  position: relative;
  width: 100%;
}
.row [class^='col'] {
  float: left;
  margin: 0.5rem 2%;
  min-height: 0.125rem;
}
.col-1,
.col-2,
.col-3,
.col-4,
.col-5,
.col-6,
.col-7,
.col-8,
.col-9,
.col-10,
.col-11,
.col-12 {
  width: 96%;
}
.col-1-sm {
  width: 4.33%;
}
.col-2-sm {
  width: 12.66%;
}
.col-3-sm {
  width: 21%;
}
.col-4-sm {
  width: 29.33%;
}
.col-5-sm {
  width: 37.66%;
}
.col-6-sm {
  width: 46%;
}
.col-7-sm {
  width: 54.33%;
}
.col-8-sm {
  width: 62.66%;
}
.col-9-sm {
  width: 71%;
}
.col-10-sm {
  width: 79.33%;
}
.col-11-sm {
  width: 87.66%;
}
.col-12-sm {
  width: 96%;
}
.row::after {
  content: '';
  display: table;
  clear: both;
}
.hidden-sm {
  display: none;
}

@media only screen and (min-width: 33.75em) {
  /* 540px */
  .container {
    width: 80%;
  }
}

@media only screen and (min-width: 45em) {
  /* 720px */
  .col-1 {
    width: 4.33%;
  }
  .col-2 {
    width: 12.66%;
  }
  .col-3 {
    width: 21%;
  }
  .col-4 {
    width: 29.33%;
  }
  .col-5 {
    width: 37.66%;
  }
  .col-6 {
    width: 46%;
  }
  .col-7 {
    width: 54.33%;
  }
  .col-8 {
    width: 62.66%;
  }
  .col-9 {
    width: 71%;
  }
  .col-10 {
    width: 79.33%;
  }
  .col-11 {
    width: 87.66%;
  }
  .col-12 {
    width: 96%;
  }
  .hidden-sm {
    display: block;
  }
}

@media only screen and (min-width: 60em) {
  /* 960px */
  .container {
    width: 75%;
    max-width: 60rem;
  }
}

/* Forms */

label {
  display: block;
  margin: 5px 0;
  color: var(--custom-color-secondary);
  font-size: 0.8rem;
  text-transform: uppercase;
}

input {
  width: 100%;
  border-radius: 5px;
  border: var(--custom-border);
  padding: 8px;
  font-size: 0.9rem;
  background-color: var(--custom-bg-color);
  color: var(--custom-color);
}

input[disabled] {
  color: var(--custom-color-secondary);
}

/* Utils */

.block {
  display: block;
  width: 100%;
}
.inline-block {
  display: inline-block;
  width: 100%;
}
.flex {
  display: flex;
}
.flex.column {
  flex-direction: column;
}
.flex.row {
  flex-direction: row;
}
.flex.flex-1 {
  flex: 1 1 0;
}
.flex-end {
  justify-content: flex-end;
}
.flex-center {
  justify-content: center;
}
.items-center {
  align-items: center;
}
.text-sm {
  font-size: 0.8rem;
  font-weight: 300;
}
.text-right {
  text-align: right;
}
.font-light {
  font-weight: 300;
}
.opacity-half {
  opacity: 50%;
}

/* Button */

button,
.button {
  color: var(--custom-color);
  border: var(--custom-border);
  background-color: var(--custom-bg-color);
  display: inline-block;
  text-align: center;
  border-radius: var(--custom-border-radius);
  padding: 0.5rem 1rem;
  cursor: pointer;
  text-align: center;
  font-size: 0.9rem;
  text-transform: uppercase;
}

button.primary,
.button.primary {
  background-color: var(--custom-color-brand);
  border: 1px solid var(--custom-color-brand);
}

/* Widgets */

.card {
  width: 100%;
  display: block;
  border: var(--custom-border);
  border-radius: var(--custom-border-radius);
  padding: var(--custom-spacing);
}

.avatar {
  border-radius: var(--custom-border-radius);
  overflow: hidden;
  max-width: 100%;
}
.avatar.image {
  object-fit: cover;
}
.avatar.no-image {
  background-color: #333;
  border: 1px solid rgb(200, 200, 200);
  border-radius: 5px;
}

.footer {
  position: absolute;
  max-width: 100%;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-flow: row;
  border-top: var(--custom-border);
  background-color: var(--custom-bg-color);
}
.footer div {
  padding: var(--custom-spacing);
  display: flex;
  align-items: center;
  width: 100%;
}
.footer div > img {
  height: 20px;
  margin-left: 10px;
}
.footer > div:first-child {
  display: none;
}
.footer > div:nth-child(2) {
  justify-content: left;
}

@media only screen and (min-width: 60em) {
  /* 960px */
  .footer > div:first-child {
    display: flex;
  }
  .footer > div:nth-child(2) {
    justify-content: center;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.mainHeader {
  width: 100%;
  font-size: 1.3rem;
  margin-bottom: 20px;
}

.avatarPlaceholder {
  border: var(--custom-border);
  border-radius: var(--custom-border-radius);
  width: 35px;
  height: 35px;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Auth */

.auth-widget {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.auth-widget > .button {
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background-color: #444444;
  text-transform: none !important;
  transition: all 0.2s ease;
}

.auth-widget .button:hover {
  background-color: #2a2a2a;
}

.auth-widget .button > .loader {
  width: 17px;
  animation: spin 1s linear infinite;
  filter: invert(1);
}

/* Account */

.account {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.account > * > .avatarField {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.account > * > .avatarField > .avatarContainer {
  margin-right: 20px;
}

/* Profile Card */

.profileCard {
  border-radius: 5px;
  display: flex;
  border: var(--custom-border);
  background-color: var(--custom-panel-color);
  padding: 20px 20px;
  margin-bottom: 20px;
}

.profileCard:last-child {
  margin-bottom: 0px;
}

.profileCard > .userInfo {
  margin-left: 20px;
  font-weight: 300;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.profileCard > .userInfo > p {
  margin: 0;
}

.profileCard > .userInfo > .username {
  font-size: 1.3rem;
  font-weight: 500;
  margin-bottom: 5px;
}

.profileCard > .userInfo > .website {
  font-size: 0.9rem;
  color: var(--custom-color-brand);
  margin-bottom: 10px;
  text-decoration: none;
}

设置登录组件

让我们设置一个 React 组件来管理登录和注册。我们将使用 Magic Links,因此用户无需使用密码即可使用电子邮件登录。

components/Auth.js

import { useState } from 'react'
import { supabase } from '../utils/supabaseClient'

export default function Auth() {
  const [loading, setLoading] = useState(false)
  const [email, setEmail] = useState('')

  const handleLogin = async (email) => {
    try {
      setLoading(true)
      const { error } = await supabase.auth.signIn({ email })
      if (error) throw error
      alert('请检查您的电子邮件以获取登录链接!')
    } catch (error) {
      alert(error.error_description || error.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="row flex flex-center">
      <div className="col-6 form-widget">
        <h1 className="header">memfiredb + Next.js</h1>
        <p className="description">使用下面的电子邮件通过魔法链接登录</p>
        <div>
          <input
            className="inputField"
            type="email"
            placeholder="Your email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>
        <div>
          <button
            onClick={(e) => {
              e.preventDefault()
              handleLogin(email)
            }}
            className="button block"
            disabled={loading}
          >
            <span>{loading ? 'Loading' : '发送魔法链接'}</span>
          </button>
        </div>
      </div>
    </div>
  )
}

用户信息页面

用户登录后,我们可以允许他们编辑他们的个人资料详细信息并管理他们的用户信息。

让我们为它创建一个名为Account.js.

components/Account.js

import { useState, useEffect } from 'react'
import { supabase } from '../utils/supabaseClient'

export default function Account({ session }) {
  const [loading, setLoading] = useState(true)
  const [username, setUsername] = useState(null)
  const [website, setWebsite] = useState(null)
  const [avatar_url, setAvatarUrl] = useState(null)

  useEffect(() => {
    getProfile()
  }, [session])

  async function getProfile() {
    try {
      setLoading(true)
      const user = supabase.auth.user()

      let { data, error, status } = await supabase
        .from('profiles')
        .select(`username, website, avatar_url`)
        .eq('id', user.id)
        .single()

      if (error && status !== 406) {
        throw error
      }

      if (data) {
        setUsername(data.username)
        setWebsite(data.website)
        setAvatarUrl(data.avatar_url)
      }
    } catch (error) {
      alert(error.message)
    } finally {
      setLoading(false)
    }
  }

  async function updateProfile({ username, website, avatar_url }) {
    try {
      setLoading(true)
      const user = supabase.auth.user()

      const updates = {
        id: user.id,
        username,
        website,
        avatar_url,
        updated_at: new Date(),
      }

      let { error } = await supabase.from('profiles').upsert(updates, {
        returning: 'minimal', // Don't return the value after inserting
      })

      if (error) {
        throw error
      }
      alert('修改成功')
    } catch (error) {
      alert(error.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="form-widget">
      <div>
        <label htmlFor="email">邮箱</label>
        <input id="email" type="text" value={session.user.email} disabled />
      </div>
      <div>
        <label htmlFor="username">名称</label>
        <input
          id="username"
          type="text"
          value={username || ''}
          onChange={(e) => setUsername(e.target.value)}
        />
      </div>
      <div>
        <label htmlFor="website">网站</label>
        <input
          id="website"
          type="website"
          value={website || ''}
          onChange={(e) => setWebsite(e.target.value)}
        />
      </div>
      <div>
        <button
          className="button block primary"
          onClick={() => updateProfile({ username, website, avatar_url })}
          disabled={loading}
        >
          {loading ? 'Loading ...' : '修改'}
        </button>
      </div>

      <div>
        <button className="button block" onClick={() => supabase.auth.signOut()}>
          登出
        </button>
      </div>
    </div>
  )
}

修改项目入口文件

pages/index.js

import { useState, useEffect } from 'react'
import { supabase } from '../utils/supabaseClient'
import Auth from '../components/Auth'
import Account from '../components/Account'

export default function Home() {
  const [session, setSession] = useState(null)

  useEffect(() => {
    setSession(supabase.auth.session())

    supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session)
    })
  }, [])

  return (
    <div className="container" style={{ padding: '50px 0 100px 0' }}>
      {!session ? <Auth /> : <Account key={session.user.id} session={session} />}
    </div>
  )
}

完成后,在终端窗口中运行它:

npm run dev

然后打开浏览器到localhost:3000,你应该会看到完整的应用程序。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DUdLEUe8-1663723902930)(https://g8nb5c2xl3.feishu.cn/space/api/box/stream/download/asynccode/?code=NjZlZmI0OGVmZWRmM2ZlZTJjNzk1ZDZlNTJhYzdhNTZfWEJya0FKVWdZVGM2Rm5HSTBWSmpxak1vOE9hVFVZczVfVG9rZW46Ym94Y25QMmdZQ0RQV0hvNnMzYzQ5OTR0dzZkXzE2NjM3MjM4ODE6MTY2MzcyNzQ4MV9WNA)]

实现:上传头像及更新用户信息

每个 MemFire Cloud项目都配置了存储,用于管理照片和视频等大文件。

创建上传小组件

让我们为用户创建一个头像,以便他们可以上传个人资料照片。我们可以从创建一个新组件开始:

components/Avatar.js

import { useEffect, useState } from 'react'
import { supabase } from '../utils/supabaseClient'

export default function Avatar({ url, size, onUpload }) {
  const [avatarUrl, setAvatarUrl] = useState(null)
  const [uploading, setUploading] = useState(false)

  useEffect(() => {
    if (url) downloadImage(url)
  }, [url])

  async function downloadImage(path) {
    try {
      const { data, error } = await supabase.storage.from('avatars').download(path)
      if (error) {
        throw error
      }
      const url = URL.createObjectURL(data)
      setAvatarUrl(url)
    } catch (error) {
      console.log('Error downloading image: ', error.message)
    }
  }

  async function uploadAvatar(event) {
    try {
      setUploading(true)

      if (!event.target.files || event.target.files.length === 0) {
        throw new Error('请上传图片')
      }

      const file = event.target.files[0]
      const fileExt = file.name.split('.').pop()
      const fileName = `${Math.random()}.${fileExt}`
      const filePath = `${fileName}`

      let { error: uploadError } = await supabase.storage
        .from('avatars')
        .upload(filePath, file)

      if (uploadError) {
        throw uploadError
      }

      onUpload(filePath)
    } catch (error) {
      alert(error.message)
    } finally {
      setUploading(false)
    }
  }

  return (
    <div>
      {avatarUrl ? (
        <img
          src={avatarUrl}
          alt="Avatar"
          className="avatar image"
          style={{ height: size, width: size }}
        />
      ) : (
        <div className="avatar no-image" style={{ height: size, width: size }} />
      )}
      <div style={{ width: size }}>
        <label className="button primary block" htmlFor="single">
          {uploading ? 'Uploading ...' : 'Upload'}
        </label>
        <input
          style={{
            visibility: 'hidden',
            position: 'absolute',
          }}
          type="file"
          id="single"
          accept="image/*"
          onChange={uploadAvatar}
          disabled={uploading}
        />
      </div>
    </div>
  )
}

将组建引入到Account页面

components/Account.js

import { useState, useEffect } from 'react'
import { supabase } from '../utils/supabaseClient'
import Avatar from './Avatar'

export default function Account({ session }) {
  const [loading, setLoading] = useState(true)
  const [username, setUsername] = useState(null)
  const [website, setWebsite] = useState(null)
  const [avatar_url, setAvatarUrl] = useState(null)

  useEffect(() => {
    getProfile()
  }, [session])

  async function getProfile() {
    try {
      setLoading(true)
      const user = supabase.auth.user()

      let { data, error, status } = await supabase
        .from('profiles')
        .select(`username, website, avatar_url`)
        .eq('id', user.id)
        .single()

      if (error && status !== 406) {
        throw error
      }

      if (data) {
        setUsername(data.username)
        setWebsite(data.website)
        setAvatarUrl(data.avatar_url)
      }
    } catch (error) {
      alert(error.message)
    } finally {
      setLoading(false)
    }
  }

  async function updateProfile({ username, website, avatar_url }) {
    try {
      setLoading(true)
      const user = supabase.auth.user()

      const updates = {
        id: user.id,
        username,
        website,
        avatar_url,
        updated_at: new Date(),
      }

      let { error } = await supabase.from('profiles').upsert(updates, {
        returning: 'minimal', // Don't return the value after inserting
      })

      if (error) {
        throw error
      }
      alert('修改成功')
    } catch (error) {
      alert(error.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="form-widget">
      <div>
        <label htmlFor="email">邮箱</label>
        <input id="email" type="text" value={session.user.email} disabled />
      </div>
      <div>
        <label htmlFor="username">名称</label>
        <input
          id="username"
          type="text"
          value={username || ''}
          onChange={(e) => setUsername(e.target.value)}
        />
      </div>
      <div>
        <label htmlFor="website">网站</label>
        <input
          id="website"
          type="website"
          value={website || ''}
          onChange={(e) => setWebsite(e.target.value)}
        />
      </div>
      <Avatar
      url={avatar_url}
      size={150}
      onUpload={(url) => {
        setAvatarUrl(url)
        updateProfile({ username, website, avatar_url: url })
      }}
    />
      <div>
        <button
          className="button block primary"
          onClick={() => updateProfile({ username, website, avatar_url })}
          disabled={loading}
        >
          {loading ? 'Loading ...' : '修改'}
        </button>
      </div>

      <div>
        <button className="button block" onClick={() => supabase.auth.signOut()}>
          登出
        </button>
      </div>
    </div>
  )
}

恭喜!在这个阶段,您拥有一个功能齐全的应用程序!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值