Swift On Server 的

发布: (2025年12月25日 GMT+8 01:47)
3 min read
原文: Dev.to

Source: Dev.to

Cover image for Swift On Server's

Vapor 绘图后端 – 项目概述

一个使用 Vapor(Swift)构建的协作笔记后端,支持实时协作、身份验证以及绘图笔画的持久化。

技术栈

  • 框架: Vapor 4.115.0
  • 数据库: MongoDB 与 Fluent ORM
  • 认证: JWT(JSON Web Tokens)
  • 实时: WebSockets
  • 语言: Swift 6.0

已实现功能

1. 认证系统

基于 JWT 的认证,提供用户注册和登录功能。

// User model with email and password
final class User: Model, Content, Authenticatable {
    static let schema = "users"

    @ID(key: .id)
    var id: UUID?

    @Field(key: "email")
    var email: String

    @Field(key: "password_hash")
    var passwordHash: String
}

端点

  • POST /api/v1/auth/register – 注册新用户
  • POST /api/v1/auth/login – 登录用户
  • GET /api/v1/auth/me – 获取当前用户(受保护)

2. JWT 中间件

自定义中间件,用于验证 JWT 令牌并保护路由。

struct AuthMiddleware: AsyncMiddleware {
    func respond(to request: Request, chainingTo next: any AsyncResponder) async throws -> Response {
        let payload: UserToken = try await request.jwt.verify(as: UserToken.self)

        guard let user = try await User.find(payload.userID, on: request.db) else {
            throw Abort(.unauthorized, reason: "User not found")
        }
        request.auth.login(user)

        return try await next.respond(to: request)
    }
}

3. 使用 Fluent ORM 的 MongoDB

使用 FluentMongoDriver 配置数据库,并自动执行迁移。

// Configure MongoDB
try app.databases.use(
    .mongo(
        connectionString: Environment.get("MONGODB_URI") ?? "mongodb://localhost:27017"
    ),
    as: .mongo
)

// Run migrations
app.migrations.add(User.Migration())
app.migrations.add(NotesModel.Migration())

4. 笔记管理

提供完整的 CRUD 操作,支持绘图笔画。

final class NotesModel: Model, Content {
    @Field(key: "title")
    var title: String

    @Field(key: "strokes")
    var strokes: [DrawingStroke]

    @Parent(key: "user_id")
    var user: User
}

struct DrawingStroke: Codable {
    let points: [DrawingPoint]
    let color: DrawingColor
    let width: Double
    let timestamp: Date
}

端点

  • POST /api/v1/notes – 创建笔记
  • GET /api/v1/notes – 获取所有笔记
  • GET /api/v1/notes/get/:id – 获取单个笔记
  • PUT /api/v1/notes/:id – 更新笔记
  • DELETE /api/v1/notes/:id – 删除笔记

5. 实时 WebSocket 协作

WebSocket 管理器用于协同编辑,并管理笔记会话。

final class WebSocketManager {
    private var connections: [UUID: WebSocket] = [:]
    private var noteCollaborators: [UUID: Set] = [:]

    func joinNoteSession(noteID: UUID, userID: UUID)
    func leaveNoteSession(noteID: UUID, userID: UUID)
    func broadcastToNote(noteID: UUID, message: String, excludeUserID: UUID?)
}

WebSocket 功能

  • 加入/离开笔记会话
  • 实时笔画更新
  • 向所有协作者广播(可排除发送者)
  • 私人消息

端点WS /api/v1/auth/handleInvite(受保护)

6. 笔记分享

通过 JWT 令牌向外部用户分享笔记。

// Share token endpoint
GET /api/v1/notes/shared/:shareToken

// Verifies JWT token and returns note
let payload = try await req.jwt.verify(shareToken, as: ShareTokenPayload.self)

项目结构

Sources/NoterPlayBackend/
├── Controllers/
│   ├── AuthenticationController.swift
│   ├── NotesController.swift
│   └── InviteController.swift
├── Middleware/
│   └── AuthMiddleware.swift
├── Models/
│   ├── User.swift
│   ├── NotesModel.swift
│   ├── UserToken.swift
│   ├── ShareTokenPayload.swift
│   └── InviteModel.swift
├── WSManager/
│   └── WebSocketManager.swift
├── configure.swift
└── routes.swift

入门

# Install dependencies
swift package resolve

# Run the server
swift run

# With Docker
docker-compose up

Vapor 绘图 Github

使用 Vapor 和 Swift ❤️ 构建。

Back to Blog

相关文章

阅读更多 »

Swift #28:Foundation

抱歉,我没有看到需要翻译的具体文字内容。请提供要翻译的摘录或摘要,我会帮您翻译成简体中文。

Combine #13:资源管理

share 和 multicast_: share 大多数 Combine 的 Publisher 是 struct,只是描述一个 pipeline,而不保存共享状态。不会创建一个 i...