test-local-import.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import axios from 'axios';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import * as os from 'os';
  5. async function testLocalImport() {
  6. const baseURL = 'http://localhost:3001/api';
  7. const username = process.argv[2] || 'admin';
  8. const password = process.argv[3];
  9. const sourceFolder = process.argv[4];
  10. const tenantId = process.argv[5];
  11. if (!password) {
  12. console.error('Usage: ts-node scripts/test-local-import.ts <username> <password> [sourceFolder] [tenantId]');
  13. process.exit(1);
  14. }
  15. try {
  16. // 1. Login to get JWT Token
  17. console.log(`Logging in as ${username} to ${baseURL}...`);
  18. const loginRes = await axios.post(`${baseURL}/auth/login`, {
  19. username,
  20. password
  21. });
  22. const jwtToken = loginRes.data.access_token;
  23. console.log('Login successful.');
  24. // 2. Get API Key using JWT Token
  25. console.log('Retrieving API key...');
  26. const apiKeyRes = await axios.get(`${baseURL}/auth/api-key`, {
  27. headers: { Authorization: `Bearer ${jwtToken}` }
  28. });
  29. const apiKey = apiKeyRes.data.apiKey;
  30. console.log('API Key retrieved:', apiKey);
  31. // From now on, using x-api-key for authentication
  32. const authHeaders: any = { 'x-api-key': apiKey };
  33. if (tenantId) {
  34. authHeaders['x-tenant-id'] = tenantId;
  35. console.log(`Target tenant set to: ${tenantId}`);
  36. }
  37. // 3. Prepare folder structure
  38. let targetPath = sourceFolder;
  39. let isTemp = false;
  40. if (!targetPath) {
  41. isTemp = true;
  42. targetPath = path.join(os.tmpdir(), `aurak-test-${Date.now()}`);
  43. const subDir = path.join(targetPath, 'subfolder');
  44. fs.mkdirSync(targetPath, { recursive: true });
  45. fs.mkdirSync(subDir, { recursive: true });
  46. fs.writeFileSync(path.join(targetPath, 'root-file.md'), '# Root File\nContent in root.', 'utf8');
  47. fs.writeFileSync(path.join(subDir, 'sub-file.txt'), 'Content in subfolder.', 'utf8');
  48. console.log(`Created temporary test structure at: ${targetPath}`);
  49. } else {
  50. console.log(`Using provided source folder: ${targetPath}`);
  51. if (!fs.existsSync(targetPath)) {
  52. throw new Error(`The specified folder does not exist: ${targetPath}`);
  53. }
  54. }
  55. // 4. Initial check for embedding models
  56. const modelsRes = await axios.get(`${baseURL}/models`, {
  57. headers: authHeaders
  58. });
  59. const embeddingModel = modelsRes.data.find((m: any) => m.type === 'embedding' && m.isEnabled !== false);
  60. if (!embeddingModel) {
  61. throw new Error('No enabled embedding model found');
  62. }
  63. console.log(`Using embedding model: ${embeddingModel.id}`);
  64. // 5. Call local-folder import endpoint
  65. console.log('Triggering local folder import...');
  66. const importRes = await axios.post(`${baseURL}/upload/local-folder`, {
  67. sourcePath: targetPath,
  68. embeddingModelId: embeddingModel.id,
  69. useHierarchy: true
  70. }, {
  71. headers: authHeaders
  72. });
  73. console.log('Import response:', importRes.data);
  74. // 6. Verification
  75. if (isTemp) {
  76. console.log('Waiting for background processing (10s)...');
  77. await new Promise(resolve => setTimeout(resolve, 10000));
  78. const kbRes = await axios.get(`${baseURL}/knowledge-bases`, {
  79. headers: authHeaders
  80. });
  81. const importedFiles = kbRes.data.filter((f: any) =>
  82. f.originalName === 'root-file.md' || f.originalName === 'sub-file.txt'
  83. );
  84. console.log(`Found ${importedFiles.length} imported files in KB.`);
  85. if (importedFiles.length === 2) {
  86. console.log('SUCCESS: All files imported.');
  87. } else {
  88. console.log('FAILURE: Not all files were imported.');
  89. }
  90. } else {
  91. console.log('Custom folder import triggered. Please check the UI or database for results.');
  92. }
  93. } catch (error: any) {
  94. if (error.response) {
  95. console.error(`Test failed with status ${error.response.status}:`, JSON.stringify(error.response.data));
  96. } else {
  97. console.error('Test failed:', error.message);
  98. }
  99. process.exit(1);
  100. }
  101. }
  102. testLocalImport();