-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.js
69 lines (57 loc) · 1.68 KB
/
api.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
60
61
62
63
64
65
66
67
68
69
const Router = require('./router')
const BASE = 'archillect.com'
let lastID = 0
const buildURL = url => {
const urlObj = new URL(url)
const newURL = urlObj.href.replace(urlObj.host, BASE)
return newURL
}
/**
* Response with the last archillect image id
* @param {Request} request
*/
async function lastIdHandler(request) {
const { url } = request
const parts = url.split('/')
if (parts.length < 5 || !parts[3].includes('api')) {
return new Response('Not found', { status: 404 })
}
const dropResponse = await fetch(buildURL('https://archillect.com/'));
const rewriter = new HTMLRewriter();
let flag = false;
await rewriter
.on('a.post', {
element(element) {
if (!flag) {
lastID = element.getAttribute('href').split('/')[1]
flag = true
}
},
})
.transform(dropResponse)
.text()
return new Response(JSON.stringify({lastID}), {
headers: { 'content-type': 'text/plain' },
})
}
/**
* Response with a random archillect image
* @param {Request} request
*/
async function randomHandler(request) {
const { url } = request
const parts = url.split('/')
if (parts.length < 5 || !parts[3].includes('api')) {
return new Response('Not found', { status: 404 })
}
const randomID = Math.floor(Math.random() * lastID) + 1;
return Response.redirect(`https://archillect.mhsattarian.workers.dev/${randomID}/img`, 301);
}
module.exports = async function handleRequest(request) {
const r = new Router()
// Replace with the approriate paths and handlers
r.get('/api/last', () => lastIdHandler(request))
r.get('/api/random', () => randomHandler(request))
const resp = await r.route(request)
return resp
}