-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathhttp-routes.ts
119 lines (103 loc) · 2.78 KB
/
http-routes.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
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
import path from "path"
import fs from "fs-extra"
import { fetchRemoteFile } from "gatsby-core-utils/fetch-remote-file"
import { hasFeature } from "../has-feature"
import { ImageCDNUrlKeys } from "./utils/url-generator"
import { getFileExtensionFromMimeType } from "./utils/mime-type-helpers"
import { transformImage } from "./transform-images"
import { getRequestHeadersForUrl } from "./utils/get-request-headers-for-url"
import type { Application } from "express"
import type { Store } from "gatsby"
export function polyfillImageServiceDevRoutes(
app: Application,
store?: Store
): void {
if (hasFeature(`image-cdn`)) {
return
}
addImageRoutes(app, store)
}
export function addImageRoutes(app: Application, store?: Store): Application {
app.get(`/_gatsby/file/:url/:filename`, async (req, res) => {
const outputDir = path.join(
global.__GATSBY?.root || process.cwd(),
`public`,
`_gatsby`,
`file`
)
const url = req.query[ImageCDNUrlKeys.URL] as string
const filePath = await fetchRemoteFile({
directory: outputDir,
url,
name: req.params.filename,
httpHeaders: getRequestHeadersForUrl(url, store),
})
fs.createReadStream(filePath).pipe(res)
})
app.get(`/_gatsby/image/:url/:params/:filename`, async (req, res) => {
const { url, params, filename } = req.params
const remoteUrl = decodeURIComponent(
req.query[ImageCDNUrlKeys.URL] as string
)
const searchParams = new URLSearchParams(
decodeURIComponent(req.query[ImageCDNUrlKeys.ARGS] as string)
)
const resizeParams: {
width: number
height: number
quality: number
format: string
} = {
width: 0,
height: 0,
quality: 75,
format: ``,
}
for (const [key, value] of searchParams) {
switch (key) {
case `w`: {
resizeParams.width = Number(value)
break
}
case `h`: {
resizeParams.height = Number(value)
break
}
case `fm`: {
resizeParams.format = value
break
}
case `q`: {
resizeParams.quality = Number(value)
break
}
}
}
const outputDir = path.join(
global.__GATSBY?.root || process.cwd(),
`public`,
`_gatsby`,
`_image`,
url,
params
)
const httpHeaders = getRequestHeadersForUrl(remoteUrl, store) as
| Record<string, string>
| undefined
const filePath = await transformImage({
outputDir,
args: {
url: remoteUrl,
filename,
httpHeaders,
...resizeParams,
},
})
res.setHeader(
`content-type`,
getFileExtensionFromMimeType(path.extname(filename))
)
fs.createReadStream(filePath).pipe(res)
})
return app
}