Typesense Firestore 搜索扩展教程
1. 项目的目录结构及介绍
firestore-typesense-search/
├── functions/
│ ├── index.js
│ ├── package.json
│ └── ...
├── extension.yaml
├── README.md
└── ...
- functions/: 包含云函数代码,用于同步 Firestore 文档到 Typesense。
- index.js: 主入口文件,定义了同步逻辑。
- package.json: 依赖管理文件。
- extension.yaml: 扩展配置文件,定义了扩展的参数和行为。
- README.md: 项目说明文档。
2. 项目的启动文件介绍
functions/index.js
这是项目的启动文件,主要负责以下功能:
- 监听 Firestore 集合的变化(创建、更新、删除)。
- 将 Firestore 文档同步到 Typesense。
- 提供数据回填功能。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const Typesense = require('typesense');
admin.initializeApp();
const typesenseClient = new Typesense.Client({
nodes: [
{
host: 'your-typesense-host',
port: '8108',
protocol: 'http',
},
],
apiKey: 'your-typesense-api-key',
});
exports.syncFirestoreToTypesense = functions.firestore
.document('books/{bookID}')
.onWrite(async (change, context) => {
const book = change.after.exists ? change.after.data() : null;
const bookId = context.params.bookID;
if (book) {
await typesenseClient.collections('books').documents().upsert({
id: bookId,
...book,
});
} else {
await typesenseClient.collections('books').documents(bookId).delete();
}
});
3. 项目的配置文件介绍
extension.yaml
这是扩展的配置文件,定义了扩展的参数和行为。
name: firestore-typesense-search
version: 0.1.0
spec:
params:
- name: FIRESTORE_COLLECTION
description: Firestore collection that needs to be indexed into Typesense
default: books
- name: TYPESENSE_HOSTS
description: A comma-separated list of Typesense Hosts
default: your-typesense-host
- name: TYPESENSE_API_KEY
description: Typesense API Key
default: your-typesense-api-key
resources:
- name: syncFirestoreToTypesense
type: firebaseextensions.v1beta.function
description: Sync Firestore documents to Typesense
entryPoint: syncFirestoreToTypesense
location: us-central1
runtime: nodejs14
eventTrigger:
resource: projects/${PROJECT_ID}/databases/(default)/documents/${FIRESTORE_COLLECTION}/{bookID}
eventType: providers/cloud.firestore/eventTypes/document.write
- FIRESTORE_COLLECTION: 需要索引到 Typesense 的 Firestore 集合。
- TYPESENSE_HOSTS: Typesense 主机的逗号分隔列表。
- TYPESENSE_API_KEY: Typesense API 密钥。
通过这些配置,可以灵活地设置扩展的行为,以适应不同的项目需求。