My server is written as follows, is there any flaws or issues anyone could help me spot, still a bit new to APIs. Thank you in advance for any feedback.
import express from ‘express’;
import cors from ‘cors’;
import dotenv from ‘dotenv’;
import { OpenAI } from ‘openai’;
dotenv.config();
console.log(‘OPENAI_API_KEY:’, process.env.OPENAI_API_KEY ? ‘[FOUND]’ : ‘[MISSING]’);
const app = express();
const PORT = 3001;
app.use(cors());
app.use(express.json());
// Initialize OpenAI client with your API key from .env
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
app.get(‘/api/generate’, (req, res) => {
res.send(‘Please send a POST request with JSON { “prompt”: “your prompt here” } to generate text.’);
});
app.post(‘/api/generate’, async (req, res) => {
const { prompt } = req.body;
if (!prompt || prompt.trim() === ‘’) {
return res.status(400).json({ error: ‘Prompt is required.’ });
}
try {
const completion = await openai.chat.completions.create({
model: ‘gpt-3.5-turbo’,
messages: [{ role: ‘user’, content: prompt }],
});
const result = completion.choices[0].message.content;
res.json({ result });
} catch (error) {
console.error(‘OpenAI error:’, error);
// Handle specific errors gracefully
if (error.code === 'invalid_api_key') {
return res.status(401).json({ error: 'Invalid API key. Please check your .env file.' });
}
if (error.code === 'insufficient_quota') {
return res.status(429).json({ error: 'Quota exceeded. Please check your OpenAI account usage and billing.' });
}
res.status(500).json({ error: 'Failed to generate text.' });
}
});
app.listen(PORT, () => {
console.log(Server listening on http://localhost:${PORT}
);
});