-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.cjs
204 lines (161 loc) · 4.71 KB
/
server.cjs
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
const express = require("express");
const app = express();
const PORT =8002;
var jwt = require("jsonwebtoken");
const JWT_SECRET = "secret";
const bodyParser = require("body-parser");
var jsonParser = bodyParser.json();
const cors = require("cors");
app.use(cors());
app.use(jsonParser);
const User=require("./Employee.cjs")
const bcrypt = require("bcrypt");
const mongoose=require('mongoose');
const connectDb=require('./dbCon.cjs')
connectDb();
const dotenv = require("dotenv")
const multer=require('multer')
const axios = require('axios');
const {Configuration,OpenAIApi}=require("openai");
const fs=require('fs');
dotenv.config()
let USER_ID_COUNTER = 0;
const configuration=new Configuration({
apiKey:process.env.REACT_APP_API_KEY
})
console.log(configuration.apiKey);
const openai=new OpenAIApi(configuration);
const API_KEY = process.env.REACT_APP_API_KEY;
app.post('/completions', async (req, res) => {
const options = {
method: 'POST',
data: {
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: req.body.message }],
max_tokens: 1000,
},
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
};
try {
const response = await axios('https://api.openai.com/v1/chat/completions', options);
res.send(response.data);
console.log(`${API_KEY} came from completions endpoint`)
} catch (error) {
console.error(error);
}
});
app.post('/generations',async (req, res) => {
const { prompt } = req.body;
const options = {
method: "POST",
headers: {
"Authorization": `Bearer ${API_KEY}`,
"Content-Type": "application/json"
},
data:{
prompt: prompt,
n: 2,
size: "1024x1024"
}
};
try {
const response = await axios("https://api.openai.com/v1/images/generations", options);
res.send(response.data);
} catch (error) {
console.error(error);
}
});
app.post('/signup',async function(req, res) {
const { email, password } = req.body;
/* const userExists = USERS.find(user => user.email === email);
*/
const userExists=await User.findOne({email:email}).exec();
if (userExists) {
res.status(400).send({ message: "User already exists" });
} else {
bcrypt.hash(password, 10,async function(err, hash) {
if (err) {
res.status(500).send({ message: "Internal server error" });
} else {
/* USERS.push({ email, password: hash, id: USER_ID_COUNTER+1});
USER_ID_COUNTER++; */
/* console.log(USER_ID_COUNTER)
*/
const result=await User.create({
"email":email,
"password":hash,
"id":USER_ID_COUNTER+1
})
USER_ID_COUNTER++;
console.log(result)
res.status(200).send({ message: "User created" });
}
});
}
});
app.post('/login',async function(req, res) {
const { email, password } = req.body;
/* const userExists = USERS.find(user => user.email === email);
*/
const userExists = await User.findOne({ email: email }).exec();
console.log(userExists);
if (userExists===null) {
res.status(400).send({ message: "User does not exist" });
} else {
bcrypt.compare(password, userExists.password, function(err, result) {
if (err) {
res.status(500).send({ message: "Internal server error" });
} else if (result) {
const token = jwt.sign({ id: userExists.id }, JWT_SECRET);
console.log(token+"came from login endpoint");
console.log("logged in")
res.status(200).send({ message: "User logged in", token });
} else {
res.status(400).send({ message: "Invalid credentials" });
}
});
}
});
const storage=multer.diskStorage({
destination:(req,file,cb)=>{
cb(null,"")
},
filename:(req,file,cb)=>{
console.log('file',file)
cb(null,file.originalname)
}
})
const upload=multer({storage:storage}).single('file')
let filePath
app.post('/upload', async (req, res) => {
upload(req, res, (err) => {
if (err instanceof multer.MulterError) {
return res.status(500).json(err);
} else if (err) {
return res.status(500).json(err);
}
// Process the uploaded file or perform any other desired operations
// without sending a response here
console.log(req.file)
filePath=req.file.path
});
});
app.post('/variations',async (req, res) => {
try{
const response = await openai.createImageVariation(
fs.createReadStream(filePath),
3,
"512x512"
);
res.send(response.data.data);
}catch(error){
console.error(error)
}
});
mongoose.connection.on('open', () => {
console.log('Connected to MongoDB');
app.listen(PORT, () => console.log("Your server is running on port " + PORT));
});