Vapor-firestore 是一个轻量级的提供程序,它允许您轻松地将您的 Vapor 项目连接到 Firestore 数据库,并通过 Firebase REST API 执行基本的 CRUD 操作。
您将需要
在您的 Package.swift 文件中,添加以下行
.package(url: "https://github.com/PitchLabsAsh/vapor-firestore.git", from: "0.1.0")
同时添加 VaporFirestore
作为依赖项
dependencies: ["Vapor", ..., "VaporFirestore"]
VaporFirestore
注册为 Provider 并导入 VaporFirestore
。这通常在 configure.swift
中完成import VaporFirstore
let firestoreConfig = FirestoreConfig(projectId: "projectId", email: "service-account-email", privateKey: "service-account-private-key")
services.register(firestoreConfig)
try! services.register(FirestoreProvider())
首先为您的文档设置一个模型。例如,当前 Vapor-Firestore 的实现在定义文档时使用辅助包装器。
struct ArticleFields: Codable {
var title: Firestore.StringValue
var subTitle: Firestore.StringValue
var isAvailable: Firestore.BooleanValue
var publishedAt: Firestore.TimestampValue
var likeCount: Firestore.IntegerValue
}
要使用此模型创建新文档
let testObject = ArticleFields(title: Firestore.StringValue("A title"), subTitle: Firestore.StringValue("A subtitle"), isAvailable: Firestore.BooleanValue(true), publishedAt: Firestore.TimestampValue(Date()), likeCount: Firestore.IntegerValue(1))
let result = try client.firestore.createDocument(path: "test", fields: testObject, on: request)
要使用此模型检索此集合中所有对象的数组
let result: [Firestore.Document<ArticleFields>] = try client.firestore.listDocuments(path: "test", on: request)
要使用此模型检索此集合中的单个对象
let result: Firestore.Document<ArticleFields> = try client.firestore.getDocument(path: "test/<object-id>", on: request)
要更新包含所有字段的文档
let result = try client.firestore.updateDocument(path: "test/<object-id>", fields: testObject, updateMask: nil, on: request)
要更新文档的特定字段,您必须声明一个仅包含这些字段的新模型并传递一个掩码
struct ArticleUpdateFields: Codable {
var title: Firestore.StringValue
}
let updateObject = ArticleUpdateFields(title: Firestore.StringValue("An updated title again"))
let result = try client.firestore.updateDocument(path: "test/<object-id>", fields: updateObject, updateMask: ["title"], on: request)
Vapor-Firstore 项目包含一些示例简单单元测试。如果您想运行这些测试,您将需要创建一个测试 Firestore 数据库并将服务帐户凭据添加到 Application+Testing.swift
。testUpdateDoc 和 testGetDoc 测试需要一个文档存在才能通过。最简单的方法是首先只运行 testCreateDoc 测试,这将创建一个测试结构的文档并输出其对象 ID。将此 ID 剪切并粘贴到 update 和 get 测试中,然后注释掉 testCreateDoc 以避免在每次运行测试时不断创建文档。
本项目根据 MIT 许可证获得许可 - 有关详细信息,请参阅 LICENSE.md 文件