@aichatkit/storage-adapter
Version:
Base storage adapter for Hypermode ChatKit
86 lines (85 loc) • 2.64 kB
JavaScript
// src/index.ts
var StorageAdapter = class {
/**
* Set network callbacks for syncing with backend
* @param callbacks Network adapter callbacks
*/
setNetworkCallbacks(callbacks) {
this.callbacks = callbacks;
}
/**
* Adds a message to a conversation (convenience method)
* @param conversationId ID of the conversation
* @param message Message to add
* @returns Promise that resolves with the updated conversation or null if not found
*/
async addMessage(conversationId, message) {
const messageItem = {
id: message.id,
type: "message",
content: message.content,
role: message.role,
timestamp: message.timestamp
};
return this.addItem(conversationId, messageItem);
}
/**
* Get conversation history (messages only) - syncs with backend if callback available
* @param conversationId ID of the conversation
* @returns Promise with array of messages
*/
async getConversationHistory(conversationId) {
const items = await this.getConversationItems(conversationId);
return items.filter((item) => item.type === "message").map((item) => {
const msgItem = item;
return {
id: msgItem.id,
content: msgItem.content,
role: msgItem.role,
timestamp: msgItem.timestamp
};
});
}
/**
* Sync all conversations with backend to ensure consistency
* @returns Promise that resolves when sync is complete
*/
async syncAllConversationsWithBackend() {
var _a;
if (!((_a = this.callbacks) == null ? void 0 : _a.getConversationItems)) {
return Promise.resolve();
}
try {
const conversations = await this.getAllConversations();
for (const conversation of conversations) {
const agentId = await this.getConversationAgent(conversation.id);
if (agentId) {
try {
const backendItems = await this.callbacks.getConversationItems(agentId);
conversation.items = backendItems;
await this.saveConversation(conversation);
} catch (error) {
console.error(
`Failed to sync conversation ${conversation.id}:`,
error
);
}
}
}
} catch (error) {
console.error("Failed to sync conversations with backend:", error);
}
return Promise.resolve();
}
/**
* Optional method to initialize the adapter
* @param config Optional configuration object
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async initialize(config) {
return Promise.resolve();
}
};
export {
StorageAdapter
};