-
Notifications
You must be signed in to change notification settings - Fork 17
/
uploadImages.ts
83 lines (68 loc) · 2.2 KB
/
uploadImages.ts
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
import 'dotenv/config'
import axios from 'axios'
import * as FormData from 'form-data'
import { readdirSync, createReadStream } from 'node:fs'
import { readJSONFile, updateJSONFile } from './helper/utils'
const extensions = ['png', 'jpg', 'jpeg', 'svg', 'webp']
const imgDirectoryPath = './images/tokens'
const uploadImage = async (imageName: string) => {
if (!process.env.CLOUD_FLARE_API_KEY || !process.env.CLOUD_FLARE_ACCOUNT_ID) {
throw new Error('Cloud flare api keys not found!')
}
try {
const formData = new FormData()
formData.append(
'file',
createReadStream(`${imgDirectoryPath}/${imageName}`)
)
const data = (await axios.post(
`https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUD_FLARE_ACCOUNT_ID}/images/v1`,
formData,
{
headers: {
...formData.getHeaders(),
Authorization: `Bearer ${process.env.CLOUD_FLARE_API_KEY}`
}
}
)) as { data: { result: { filename: string; variants: string[] } } }
console.log(
` ✅ Uploaded image: ${data.data.result.filename} with url ${data.data.result.variants[0]}`
)
const updatedTokenImagePaths = {
...readJSONFile({
path: 'data/tokenImagePaths.json',
fallback: {}
}),
[imageName]: data.data.result.variants[0]
}
await updateJSONFile('data/tokenImagePaths.json', updatedTokenImagePaths)
} catch (e) {
console.log('Error uploadImage', e)
}
}
const uploadImages = async () => {
console.log({
CLOUD_FLARE_API_KEY: process.env.CLOUD_FLARE_API_KEY,
CLOUD_FLARE_ACCOUNT_ID: process.env.CLOUD_FLARE_ACCOUNT_ID
})
try {
const uploadedImages = readJSONFile({
path: 'data/tokenImagePaths.json',
fallback: {}
})
const files = readdirSync(imgDirectoryPath)
const filteredFileNames = files.filter(
(fileName) =>
extensions.includes(fileName.split('.').pop() as string) &&
!uploadedImages[fileName]
)
for (const filename of filteredFileNames) {
await uploadImage(filename)
}
console.log('✅✅✅ UploadImages')
} catch (e) {
console.log('Error uploadImages', e)
throw new Error('Error uploadImages')
}
}
uploadImages()