* Upload content to storage as a .txt file, create a document record, * and trigger processing via the existing pipeline.
( knowledgeBaseId: string, connectorId: string, connectorType: string, extDoc: ExternalDocument, kbOwner: KnowledgeBaseOwner, sourceConfig?: Record<string, unknown> )
| 1171 | * and trigger processing via the existing pipeline. |
| 1172 | */ |
| 1173 | async function addDocument( |
| 1174 | knowledgeBaseId: string, |
| 1175 | connectorId: string, |
| 1176 | connectorType: string, |
| 1177 | extDoc: ExternalDocument, |
| 1178 | kbOwner: KnowledgeBaseOwner, |
| 1179 | sourceConfig?: Record<string, unknown> |
| 1180 | ): Promise<DocumentData> { |
| 1181 | const documentId = generateId() |
| 1182 | const contentBuffer = Buffer.from(extDoc.content, 'utf-8') |
| 1183 | const safeTitle = sanitizeStorageTitle(extDoc.title) |
| 1184 | const customKey = `kb/${Date.now()}-${documentId}-${safeTitle}.txt` |
| 1185 | |
| 1186 | const fileInfo = await StorageService.uploadFile({ |
| 1187 | file: contentBuffer, |
| 1188 | fileName: `${safeTitle}.txt`, |
| 1189 | contentType: 'text/plain', |
| 1190 | context: 'knowledge-base', |
| 1191 | customKey, |
| 1192 | preserveKey: true, |
| 1193 | metadata: kbOwnershipMetadata(kbOwner, `${safeTitle}.txt`), |
| 1194 | }) |
| 1195 | |
| 1196 | const fileUrl = `${getInternalApiBaseUrl()}${fileInfo.path}?context=knowledge-base` |
| 1197 | |
| 1198 | const tagValues = extDoc.metadata |
| 1199 | ? resolveTagMapping(connectorType, extDoc.metadata, sourceConfig) |
| 1200 | : undefined |
| 1201 | |
| 1202 | const processingFilename = `${safeTitle}.txt` |
| 1203 | |
| 1204 | try { |
| 1205 | await db.transaction(async (tx) => { |
| 1206 | const isActive = await isKnowledgeBaseActiveInTx(tx, knowledgeBaseId) |
| 1207 | if (!isActive) { |
| 1208 | throw new Error(`Knowledge base ${knowledgeBaseId} is deleted`) |
| 1209 | } |
| 1210 | |
| 1211 | await tx.insert(document).values({ |
| 1212 | id: documentId, |
| 1213 | knowledgeBaseId, |
| 1214 | filename: extDoc.title, |
| 1215 | fileUrl, |
| 1216 | storageKey: fileInfo.key, |
| 1217 | fileSize: contentBuffer.length, |
| 1218 | mimeType: 'text/plain', |
| 1219 | chunkCount: 0, |
| 1220 | tokenCount: 0, |
| 1221 | characterCount: 0, |
| 1222 | processingStatus: 'pending', |
| 1223 | enabled: true, |
| 1224 | connectorId, |
| 1225 | externalId: extDoc.externalId, |
| 1226 | contentHash: extDoc.contentHash, |
| 1227 | sourceUrl: extDoc.sourceUrl ?? null, |
| 1228 | ...tagValues, |
| 1229 | uploadedAt: new Date(), |
| 1230 | }) |
no test coverage detected