-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFittingImage.js
92 lines (83 loc) · 2.52 KB
/
FittingImage.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
81
82
83
84
85
86
87
88
89
90
91
92
const express = require('express')
const router = express.Router()
const axios = require('axios')
const https = require('https')
const User = require('../models/User')
const Clothes = require('../models/Closet')
const fittingApiUrl = process.env.AI_FITTING_API_URL
async function isImageValid(imageUrl) {
return new Promise((resolve, reject) => {
const options = {
method: 'HEAD',
url: imageUrl,
};
const req = https.request(imageUrl, options, (res) => {
if (res.statusCode === 200) {
resolve(true);
} else {
resolve(false);
}
});
req.on('error', (error) => {
console.error(`Error checking image URL: ${imageUrl}`, error);
resolve(false);
});
req.end();
});
}
router.post('/fitting', async (req, res) => {
try {
const { userId, clothID } = req.body
// 사용자 이미지 가져오기
const user = await User.findOne({ _id: userId })
if (!user) {
return res.status(404).json({ error: 'User not found' })
}
const userImageUrl = user.file
const cloth = await Clothes.findOne({ _id: clothID })
if (!cloth) {
return res.status(404).json({ error: 'Cloth not found' })
}
const clothImageUrl = cloth.clothesImageLink
// 이미 피팅이미지가 있으면
if (cloth && cloth.fittingImageLink) {
const isValid = await isImageValid(cloth.fittingImageLink)
if (isValid) {
return res
.status(200)
.json({ fittingImageLink: cloth.fittingImageLink })
} else {
console.warn(
'Stored fittingImageLink is not valid. Fetching new image.'
)
}
}
const response = await axios.post(fittingApiUrl, null, {
headers: {
'Content-Type': 'application/json',
},
params: {
ID: userId,
image_url: userImageUrl,
cloth_url: clothImageUrl,
},
})
if (response.data.success) {
console.log('Fitting request sent successfully.')
const imageUrl = response.data.file_name
await Clothes.updateOne(
{ userId, clothesImageLink: clothImageUrl },
{ $set: { fittingImageLink: imageUrl } }
)
res.status(200).json({ fittingImageLink: imageUrl })
} else {
console.log(error.response)
console.error('Error:', response.data.error)
res.status(500).json({ error: response.data.error })
}
} catch (error) {
console.error('Fitting Request Error:', error)
res.status(500).json({ error: 'Fitting Request Error' })
}
})
module.exports = router