ts-api / pages /api /apiList.js
Shuddho's picture
Upload 42 files
d04e364 verified
raw
history blame
1.51 kB
// pages/api/apiList.js
import fs from 'fs';
import path from 'path';
export default function handler(req, res) {
const apiDir = path.join(process.cwd(), 'pages/api');
try {
// Read the directory synchronously
const files = fs.readdirSync(apiDir);
// Filter out the current file and non-JavaScript files
const jsFiles = files.filter(file => file !== 'apiList.js' && file.endsWith('.js'));
// Initialize an array to store API configurations
const apiList = [];
// Load configurations from each JavaScript file
for (const file of jsFiles) {
const filePath = path.join(apiDir, file);
// Read the file content
const fileContent = fs.readFileSync(filePath, 'utf-8');
// Extract JSON using regex
const jsonMatch = fileContent.match(/export\s+const\s+config\s+=\s+({[\s\S]*?})/);
// If JSON is found, parse it and add it to the API list
if (jsonMatch && jsonMatch[1]) {
console.log(jsonMatch[1])
const config = JSON.parse(jsonMatch[1]);
apiList.push({...config });
}
}
// save the json at public/apiList.json (from the root)
fs.writeFileSync(
path.join(process.cwd(), 'public/apiList.json'),
JSON.stringify(apiList, null, 2),
);
// Send the information as a JSON response
res.status(200).json(apiList);
} catch (error) {
console.error('Error reading API directory:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}