-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudinary.js
166 lines (142 loc) · 5.05 KB
/
cloudinary.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
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
import cloudinary from 'cloudinary';
import path from 'path';
import fs from 'fs';
import { fetchWithTimeout } from './utils';
export class CloudinaryService {
static instance;
resources = new Map();
constructor() {
cloudinary.v2.config({
cloud_name: process.env.CL_NAME,
api_key: process.env.CL_APIKEY,
api_secret: process.env.CL_APISECRET
});
}
static async getInstance(name) {
if (!CloudinaryService.instance) {
CloudinaryService.instance = new CloudinaryService();
}
await CloudinaryService.instance.getResourcesFromFolder(name);
return CloudinaryService.instance;
}
async getResourcesFromFolder(folderName) {
console.log('FETCHING NEW FILES!! from CLOUDINARY');
await this.findAndSaveResources(folderName, 'image');
}
async createNewFolder(folderName) {
await this.createFolder(folderName);
await this.uploadFilesToFolder(folderName);
}
async overwriteFile() {
const cloudinaryFileId = "index_nbzca5.js";
const localFilePath = "./src/test.js";
try {
const result = await cloudinary.v2.uploader.upload(localFilePath, {
resource_type: 'auto',
overwrite: true,
invalidate: true,
public_id: cloudinaryFileId
});
console.log(result);
} catch (error) {
console.log(parseError(error))
}
}
async findAndSaveResources(folderName, type) {
try {
const { resources } = await cloudinary.v2.api.resources({ resource_type: type, type: 'upload', prefix: folderName, max_results: 500 });
resources.forEach(async (resource) => {
try {
this.resources.set(resource.public_id.split('/')[1].split('_')[0], resource.url);
await saveFile(resource.url, resource.public_id.split('/')[1].split('_')[0]);
} catch (error) {
console.log(resource);
console.log(parseError(error))
}
});
} catch (error) {
console.log(parseError(error))
}
}
async createFolder(folderName) {
try {
const result = await cloudinary.v2.api.create_folder(folderName);
return result;
} catch (error) {
console.error('Error creating folder:', error);
throw error;
}
}
// Function to upload files from URLs to a specific folder in Cloudinary
async uploadFilesToFolder(folderName) {
const uploadPromises = Array.from(this.resources.entries()).map(async ([key, url]) => {
try {
const result = await cloudinary.v2.uploader.upload_large(url, {
folder: folderName,
resource_type: 'auto',
public_id: key, // Set the key as the public_id
});
return result;
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
});
try {
return await Promise.all(uploadPromises);
} catch (error) {
console.error('Error uploading files:', error);
throw error;
}
}
async printResources() {
try {
this.resources?.forEach((val, key) => {
console.log(key, ":", val);
})
} catch (error) {
console.log(parseError(error))
}
}
get(publicId) {
try {
const result = this.resources.get(publicId)
return result || '';
} catch (error) {
console.log(parseError(error))
}
}
getBuffer(publicId) {
try {
const result = this.resources.get(publicId)
return result || '';
} catch (error) {
console.log(parseError(error))
}
}
}
async function saveFile(url, name) {
const extension = url.substring(url.lastIndexOf('.') + 1, url.length);
const mypath = path.resolve(__dirname, `./${name}.${extension}`);
fetchWithTimeout(url, { responseType: 'arraybuffer' }, 2)
.then(res => {
if (res?.statusText === 'OK') {
try {
if (!fs.existsSync(mypath)) {
fs.writeFileSync(mypath, res.data, 'binary'); // Save binary data as a file
console.log(`${name}.${extension} Saved!!`);
} else {
fs.unlinkSync(mypath);
fs.writeFileSync(mypath, res.data, 'binary'); // Save binary data as a file
console.log(`${name}.${extension} Replaced!!`);
}
} catch (err) {
console.error(err);
}
} else {
throw new Error(`Unable to download file from ${url}`);
}
}).catch(err => {
console.error(err);
});
}