-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
62 lines (55 loc) · 1.83 KB
/
app.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
import fetch from 'node-fetch'
import { JSDOM } from 'jsdom'
import { FastifyInstance, FastifyRequest, FastifyServerOptions } from 'fastify'
interface CustomRouteGenericParam {
Params: { url: string }
}
interface CustomRouteGenericQuery {
Querystring: { url: string }
}
export default function (
fastify: FastifyInstance,
options: FastifyServerOptions,
done: () => void
) {
fastify.get(
'/:url',
async function (request: FastifyRequest<CustomRouteGenericParam>, reply) {
const response = await fetch(decodeURI(request.params.url))
const { document } = new JSDOM(await response.text()).window
const ogImageUrl = document.querySelector<HTMLMetaElement>(
'meta[property="og:image"]'
)?.content
reply.send({ ogImage: ogImageUrl })
}
)
fastify.get(
'/image.jpg',
async function (request: FastifyRequest<CustomRouteGenericQuery>, reply) {
const response = await fetch(decodeURI(request.query.url))
const { document } = new JSDOM(await response.text()).window
const ogImageUrl = document.querySelector<HTMLMetaElement>(
'meta[property="og:image"]'
)?.content
if (!ogImageUrl) {
reply.send(null)
return
}
const imageResponse = await fetch(ogImageUrl)
const buffer = await imageResponse.buffer()
reply.header('Access-Control-Allow-Origin', '*')
reply.type('image/jpeg')
reply.send(buffer)
}
)
fastify.options('/image.jpg', async function (request, reply) {
reply.header('Access-Control-Allow-Origin', '*')
reply.send(null)
})
fastify.get('/', async function (request, reply) {
reply.send(
'pass encoded url and return og-image as image/jpeg.\nusage: https://og-image-dlwr.vercel.app/image.jpg?url=https%3A%2F%2Fopen.spotify.com%2Falbum%2F063f8Ej8rLVTz9KkjQKEMa'
)
})
done()
}