-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
65 lines (56 loc) · 1.61 KB
/
index.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
const Koa = require('koa')
const Router = require('koa-router')
const logger = require('koa-logger')
const ratelimit = require('koa-ratelimit')
const fs = require('fs')
const path = require('path')
const app = new Koa()
const router = new Router()
const imageTag = fs.readdirSync('./images')
const images = imageTag.map(el=> ({ type: el, list: fs.readdirSync(path.join('./images', el)) }))
router.get('/', (ctx) => {
ctx.body = { love: 'iu', document: 'https://github.com/wonderlandpark/iu-api' }
})
router.get('/images/:type', (ctx) => {
const type = images.find(e=> e.type === ctx.params.type)
if(!type) {
ctx.status = 404
ctx.body = 'Not Foundd'
return
}
const src = random(type.list)
const image = fs.createReadStream(path.join(`./images/${type.type}`, src))
ctx.response.set('content-type', ContentType[src.split('.').pop()] ?? 'image/png')
ctx.body = image
})
app.use(logger())
app.use(ratelimit({
driver: 'memory',
duration: 2000,
errorMessage: { error: 'Slowdown' },
db: new Map(),
headers: {
remaining: 'Rate-Limit-Remaining',
reset: 'Rate-Limit-Reset',
total: 'Rate-Limit-Total'
},
max: 1,
whitelist: (ctx) => {
if(process.env.IU_API_TOKEN === (ctx.get('Authorization') ?? 'MUST_NOT_BE_A_KEY')) return true
return false
}
}))
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(4000, () => {
console.log('iu api server is listening to port 4000')
})
function random(items){
return items[Math.floor(Math.random() * items.length)]
}
const ContentType = {
png: 'image/png',
jpeg: 'image/jpeg',
jpg: 'image/jpeg',
gif: 'image/gif'
}