-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (70 loc) · 2.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Import required modules
import Express from "express";
import * as dotenv from 'dotenv';
import cors from 'cors';
import { Configuration, OpenAIApi } from 'openai'
import { v2 as cloudinary } from 'cloudinary';
import { createNewPost, getAllPost } from "./mongodb/connection.js";
// Load environment variables from .env file
dotenv.config()
// Create an Express app
export const app = Express();
// Configure middleware
app.use(Express.json({ limit: '50mb' }));
app.use(Express.urlencoded({ extended: false }));
app.use(cors());
// Set up OpenAI configuration
const config = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
})
const openai = new OpenAIApi(config)
// Configure Cloudinary
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
})
// Define API routes
// Endpoint to generate image based on AI prompt
app.post('/api/post', async (req, res) => {
try {
const { prompt } = req.body;
const aiResponse = await openai.createImage({
prompt,
n: 1,
size: '1024x1024',
response_format: 'b64_json',
});
const image = aiResponse.data.data[0].b64_json;
return res
.status(200)
.json({ photo: image });
} catch (error) {
console.log(error?.response.data.error.message);
return res.status(500).send(error?.response.data.error.message);
}
});
// Endpoint to get all posts from the database
app.get('/api/getPosts', async (req, res) => {
try {
const posts = await getAllPost();
res.status(200).json({ success: true, data: posts });
} catch (error) {
res.status(500).json({ success: false, message: error });
}
});
// Endpoint to share a new post
app.post('/api/sharePosts', async (req, res) => {
try {
const { name, prompt, photo } = req.body;
const photoUrl = await cloudinary.uploader.upload(photo);
const newPost = await createNewPost(name, prompt, photoUrl);
res.status(200).json({ success: true, data: newPost });
} catch (error) {
res.status(500).json({ success: false, message: error });
}
});
// Start the server
app.listen(process.env.PORT, () => {
console.log(`Server running on port ${process.env.PORT}`);
});