( userId: string, workspaceId?: string | null, scope: KnowledgeBaseScope = 'active' )
| 38 | * Get knowledge bases that a user can access |
| 39 | */ |
| 40 | export async function getKnowledgeBases( |
| 41 | userId: string, |
| 42 | workspaceId?: string | null, |
| 43 | scope: KnowledgeBaseScope = 'active' |
| 44 | ): Promise<KnowledgeBaseWithCounts[]> { |
| 45 | const scopeCondition = |
| 46 | scope === 'all' |
| 47 | ? undefined |
| 48 | : scope === 'archived' |
| 49 | ? sql`${knowledgeBase.deletedAt} IS NOT NULL` |
| 50 | : isNull(knowledgeBase.deletedAt) |
| 51 | |
| 52 | const knowledgeBasesWithCounts = await db |
| 53 | .select({ |
| 54 | id: knowledgeBase.id, |
| 55 | userId: knowledgeBase.userId, |
| 56 | name: knowledgeBase.name, |
| 57 | description: knowledgeBase.description, |
| 58 | tokenCount: sql<number>`COALESCE(SUM(${document.tokenCount}), 0)`.mapWith(Number), |
| 59 | embeddingModel: knowledgeBase.embeddingModel, |
| 60 | embeddingDimension: knowledgeBase.embeddingDimension, |
| 61 | chunkingConfig: knowledgeBase.chunkingConfig, |
| 62 | createdAt: knowledgeBase.createdAt, |
| 63 | updatedAt: knowledgeBase.updatedAt, |
| 64 | deletedAt: knowledgeBase.deletedAt, |
| 65 | workspaceId: knowledgeBase.workspaceId, |
| 66 | docCount: count(document.id), |
| 67 | }) |
| 68 | .from(knowledgeBase) |
| 69 | .leftJoin( |
| 70 | document, |
| 71 | and( |
| 72 | eq(document.knowledgeBaseId, knowledgeBase.id), |
| 73 | eq(document.userExcluded, false), |
| 74 | isNull(document.archivedAt), |
| 75 | isNull(document.deletedAt) |
| 76 | ) |
| 77 | ) |
| 78 | .leftJoin( |
| 79 | permissions, |
| 80 | and( |
| 81 | eq(permissions.entityType, 'workspace'), |
| 82 | eq(permissions.entityId, knowledgeBase.workspaceId), |
| 83 | eq(permissions.userId, userId) |
| 84 | ) |
| 85 | ) |
| 86 | .leftJoin(workspace, eq(knowledgeBase.workspaceId, workspace.id)) |
| 87 | .where( |
| 88 | and( |
| 89 | scopeCondition, |
| 90 | workspaceId |
| 91 | ? // When filtering by workspace |
| 92 | or( |
| 93 | // Knowledge bases belonging to the specified workspace (user must have workspace permissions) |
| 94 | and( |
| 95 | eq(knowledgeBase.workspaceId, workspaceId), |
| 96 | isNotNull(permissions.userId), |
| 97 | isNull(workspace.archivedAt) |
no test coverage detected