FaunaDB环境搭建 #

一、注册Fauna账户 #

1.1 注册步骤 #

text
注册流程:
├── 1. 访问 https://fauna.com
├── 2. 点击 "Start Free"
├── 3. 填写注册信息
├── 4. 验证邮箱
└── 5. 登录Dashboard

1.2 Dashboard概览 #

text
Dashboard功能:
├── 数据库管理
├── 集合管理
├── 索引管理
├── Shell终端
├── GraphQL Playground
├── 密钥管理
└── 监控面板

二、创建数据库 #

2.1 通过Dashboard创建 #

text
创建步骤:
├── 1. 登录Dashboard
├── 2. 点击 "Create Database"
├── 3. 输入数据库名称
├── 4. 选择区域(可选)
├── 5. 点击 "Create"
└── 数据库创建完成

2.2 通过Shell创建 #

javascript
// 创建数据库
CreateDatabase({
  name: "my_database"
})

// 创建子数据库
CreateDatabase({
  name: "child_database"
}, {
  parent: Database("parent_database")
})

三、管理密钥 #

3.1 密钥类型 #

类型 权限 用途
Admin 完全管理权限 数据库管理
Server 数据库完全访问 后端服务
Server-ReadOnly 只读访问 分析、报表
Client 受限访问 前端应用

3.2 创建密钥 #

通过Dashboard:

text
创建步骤:
├── 1. 选择数据库
├── 2. 进入 "Security" 选项卡
├── 3. 点击 "New Key"
├── 4. 选择角色
├── 5. 可选:设置过期时间
├── 6. 点击 "Save"
└── 7. 复制密钥(只显示一次)

通过Shell:

javascript
// 创建Admin密钥
CreateKey({
  role: "admin"
})

// 创建Server密钥
CreateKey({
  role: "server",
  database: Database("my_database")
})

// 创建自定义角色密钥
CreateKey({
  role: Role("custom_role"),
  database: Database("my_database")
})

3.3 密钥安全 #

text
安全建议:
├── 不要在客户端暴露Server密钥
├── 使用环境变量存储密钥
├── 定期轮换密钥
├── 为不同环境使用不同密钥
└── 删除不再使用的密钥

四、安装CLI工具 #

4.1 安装方式 #

macOS:

bash
# 使用Homebrew
brew install fauna-shell

# 或使用npm
npm install -g fauna-shell

Windows:

bash
# 使用npm
npm install -g fauna-shell

# 或使用Chocolatey
choco install fauna-shell

Linux:

bash
# 使用npm
npm install -g fauna-shell

# 或下载二进制文件
curl https://github.com/fauna/fauna-shell/releases/latest/download/fauna-shell-linux -o fauna
chmod +x fauna
sudo mv fauna /usr/local/bin/

4.2 验证安装 #

bash
# 查看版本
fauna --version

# 查看帮助
fauna --help

五、配置CLI #

5.1 添加端点 #

bash
# 添加云端点
fauna add-endpoint https://db.fauna.com

# 添加区域端点
fauna add-endpoint https://db.us.fauna.com
fauna add-endpoint https://db.eu.fauna.com

5.2 配置密钥 #

bash
# 交互式配置
fauna cloud-login

# 或手动配置
# 创建 ~/.fauna-shell 配置文件

配置文件示例:

json
{
  "default": "cloud",
  "endpoints": {
    "cloud": {
      "domain": "db.fauna.com",
      "scheme": "https",
      "secret": "your-secret-key"
    },
    "us-region": {
      "domain": "db.us.fauna.com",
      "scheme": "https",
      "secret": "your-us-secret-key"
    }
  }
}

5.3 环境变量 #

bash
# 设置密钥环境变量
export FAUNA_SECRET="your-secret-key"

# 设置端点
export FAUNA_DOMAIN="db.fauna.com"
export FAUNA_SCHEME="https"
export FAUNA_PORT="443"

六、CLI基本命令 #

6.1 数据库操作 #

bash
# 创建数据库
fauna create-database my_database

# 列出数据库
fauna list-databases

# 删除数据库
fauna delete-database my_database

6.2 集合操作 #

bash
# 创建集合
fauna create-collection my_collection

# 列出集合
fauna list-collections

# 删除集合
fauna delete-collection my_collection

6.3 Shell操作 #

bash
# 进入Shell
fauna shell my_database

# 执行脚本文件
fauna eval my_database --file=query.fql

# 执行内联查询
fauna eval my_database 'Paginate(Collections())'

6.4 导入导出 #

bash
# 导出数据
fauna export my_database --output=./backup

# 导入数据
fauna import my_database --file=./data.json

七、安装客户端驱动 #

7.1 JavaScript/Node.js #

bash
# 安装驱动
npm install fauna

# 或使用yarn
yarn add fauna

基本使用:

javascript
const { Client, query } = require('fauna');
const client = new Client({
  secret: process.env.FAUNA_SECRET,
});

// 或使用ES模块
import { Client, query } from 'fauna';

7.2 Python #

bash
# 安装驱动
pip install fauna

# 或使用poetry
poetry add fauna

基本使用:

python
from fauna import fql
from fauna.client import FaunaClient

client = FaunaClient(secret='your-secret-key')

7.3 Go #

bash
# 安装驱动
go get github.com/fauna/fauna-go

基本使用:

go
package main

import (
    "github.com/fauna/fauna-go"
)

func main() {
    client := fauna.NewFaunaClient("your-secret-key")
}

7.4 Java #

Maven:

xml
<dependency>
    <groupId>com.faunadb</groupId>
    <artifactId>faunadb-java</artifactId>
    <version>4.2.0</version>
</dependency>

Gradle:

groovy
implementation 'com.faunadb:faunadb-java:4.2.0'

八、创建第一个项目 #

8.1 项目初始化 #

bash
# 创建项目目录
mkdir fauna-project
cd fauna-project

# 初始化Node.js项目
npm init -y

# 安装Fauna驱动
npm install fauna

# 创建环境变量文件
echo "FAUNA_SECRET=your-secret-key" > .env

8.2 项目结构 #

text
fauna-project/
├── src/
│   ├── index.js
│   ├── db.js
│   └── queries/
│       └── user.fql
├── .env
├── .gitignore
└── package.json

8.3 连接示例 #

javascript
// db.js
const { Client, query } = require('fauna');

const client = new Client({
  secret: process.env.FAUNA_SECRET,
});

module.exports = { client, q: query };
javascript
// index.js
require('dotenv').config();
const { client, q } = require('./db');

async function main() {
  try {
    // 创建集合
    await client.query(
      q.CreateCollection({ name: 'users' })
    );
    console.log('Collection created');

    // 创建文档
    const result = await client.query(
      q.Create(q.Collection('users'), {
        data: { name: 'Tom', email: 'tom@example.com' }
      })
    );
    console.log('Document created:', result);
  } catch (error) {
    console.error('Error:', error);
  }
}

main();

九、使用Shell #

9.1 启动Shell #

bash
# 进入Shell
fauna shell my_database

# 使用特定端点
fauna shell my_database --endpoint us-region

9.2 Shell命令 #

javascript
// 创建集合
CreateCollection({ name: "products" })

// 创建索引
CreateIndex({
  name: "products_by_name",
  source: Collection("products"),
  terms: [{ field: ["data", "name"] }]
})

// 插入数据
Create(Collection("products"), {
  data: { name: "iPhone", price: 999 }
})

// 查询数据
Get(Ref(Collection("products"), "123456"))

// 退出Shell
.exit

十、GraphQL设置 #

10.1 启用GraphQL #

text
启用步骤:
├── 1. 进入数据库Dashboard
├── 2. 点击 "GraphQL" 选项卡
├── 3. 上传Schema文件
└── GraphQL API启用完成

10.2 Schema示例 #

graphql
type User {
  name: String!
  email: String! @unique
  age: Int
  posts: [Post!] @relation
}

type Post {
  title: String!
  content: String
  author: User! @relation
}

type Query {
  allUsers: [User!]!
  findUserByEmail(email: String!): User
}

10.3 GraphQL端点 #

text
GraphQL端点格式:
https://graphql.fauna.com/graphql

请求头:
Authorization: Bearer your-secret-key

十一、开发环境最佳实践 #

11.1 环境分离 #

text
推荐配置:
├── 开发环境
│   └── dev_database
├── 测试环境
│   └── test_database
└── 生产环境
    └── prod_database

11.2 密钥管理 #

javascript
// 使用环境变量
const client = new Client({
  secret: process.env.FAUNA_SECRET,
  domain: process.env.FAUNA_DOMAIN || 'db.fauna.com',
});

// 不同环境配置
const config = {
  development: {
    secret: process.env.FAUNA_DEV_SECRET,
  },
  production: {
    secret: process.env.FAUNA_PROD_SECRET,
  }
};

11.3 错误处理 #

javascript
const { Client, query, errors } = require('fauna');

async function safeQuery(queryFn) {
  try {
    return await client.query(queryFn);
  } catch (error) {
    if (error instanceof errors.FaunaHTTPError) {
      console.error('Fauna Error:', error.message);
      console.error('Description:', error.description);
    }
    throw error;
  }
}

十二、常见问题 #

12.1 连接问题 #

text
问题:无法连接到Fauna
解决方案:
├── 检查网络连接
├── 验证密钥是否正确
├── 确认端点配置
└── 检查防火墙设置

12.2 权限问题 #

text
问题:权限不足错误
解决方案:
├── 检查密钥角色
├── 确认数据库访问权限
├── 验证自定义角色配置
└── 检查资源权限设置

12.3 区域问题 #

text
问题:延迟过高
解决方案:
├── 选择就近区域
├── 使用区域端点
├── 配置区域复制
└── 优化查询性能

十三、总结 #

环境搭建要点:

步骤 说明
注册账户 获取免费账户
创建数据库 创建第一个数据库
管理密钥 创建并保存密钥
安装CLI 安装命令行工具
安装驱动 安装客户端驱动

下一步,让我们学习FQL语法基础!

最后更新:2026-03-27