-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathprocessImages.js
59 lines (53 loc) · 1.52 KB
/
processImages.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
const request = require('request-promise')
const config = require('./config')
const replaceAll = (str, obj) => {
let newStr = str
for (let key in obj) {
newStr = newStr.replace(new RegExp(key, 'g'), obj[key])
}
return newStr
}
/**
*
* @param {string} content
*/
const processImages = async (content) => {
const imgRegExp = /!\[([^\]]+)\]\(([^\)]+)\)/
const imgMatchAll = new RegExp(imgRegExp, 'g')
if (config.s3Bucket) {
const { uploadImage } = require('./s3')
return Promise.all(
(content.match(imgMatchAll) || [])
.map(img => {
const [_, title, oldUrl] = img.match(imgRegExp)
return request({
method: 'GET',
encoding: null, // force a buffer
url: oldUrl,
transform: (body, response) => ({
headers: response.headers,
body,
})
})
// .then(console.log)
// .then(() => { process.exit(1) })
.then(response => uploadImage(config.s3Bucket, response.headers['content-type'])(response.body))
.then(newUrl => {
console.log('Uploaded image: ', newUrl)
return { oldUrl, newUrl }
})
})
).then(replacements => {
return replacements.reduce(
(result, { oldUrl, newUrl }) => {
return result.replace(oldUrl, newUrl)
},
content
)
})
} else {
// no s3 bucket, just return content
return Promise.resolve(content)
}
}
module.exports = processImages