-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
65 lines (52 loc) · 1.28 KB
/
index.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
import { stdin as input, stdout as output } from 'node:process'
import * as readline from 'node:readline/promises'
const { HOST = '', AUTH = '' } = process.env
Bun.serve({
async fetch(req) {
const { pathname } = new URL(req.url)
const name = pathname.slice(1)
const path = `tmp/${name}`
console.log(`=== ${name} ===`)
if (!name.endsWith('.json')) {
return new Response('404!', { status: 404 })
}
const file = Bun.file(path)
if (await file.exists()) {
console.log('exists!')
return new Response(await file.text(), {
headers: {
'content-type': 'application/json',
},
})
}
let answer = ''
const requestUrl = `${HOST}${name}`
try {
const original = await fetchOriginal(`${requestUrl}`)
answer = original
console.log('success!')
} catch {
const rl = readline.createInterface({ input, output })
answer = await rl.question(`${requestUrl}\n> `)
rl.close()
await Bun.write(path, answer)
}
return new Response(answer, {
headers: {
'content-type': 'application/json',
},
})
},
})
async function fetchOriginal(url: string) {
const response = await fetch(url, {
headers: {
authorization: AUTH,
},
redirect: 'follow',
})
if (response.ok) {
return response.text()
}
throw new Error('failed request!')
}