-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtempnote.js
More file actions
63 lines (51 loc) Β· 1.49 KB
/
tempnote.js
File metadata and controls
63 lines (51 loc) Β· 1.49 KB
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
import { Hoa } from 'hoa'
import { tinyRouter } from '@hoajs/tiny-router'
import { cookie } from '@hoajs/cookie'
import tempnoteHtml from './tempnote.html'
const app = new Hoa()
app.extend(tinyRouter())
app.extend(cookie())
app.get('/:path', async (ctx) => {
const path = ctx.req.params.path
if (!/^[0-9a-zA-Z]+$/.test(path)) {
ctx.res.status = 204
return
}
const type = ctx.req.query.type
const note = await ctx.env.KV.get(path) || ''
ctx.res.set({
'Cache-Control': 'no-store, no-cache, must-revalidate',
Pragma: 'no-cache',
Expires: '0'
})
if (type === 'text') {
ctx.res.type = 'text'
ctx.res.body = note
return
}
const safeNote = note.replace(/<\/textarea>/gi, '<\\/textarea>')
ctx.res.type = 'html'
ctx.res.body = tempnoteHtml.replace(/\{\s*SAFE_NOTE\s*\}/, safeNote)
await ctx.res.setCookie('last_path', path)
})
app.post('/:path', async (ctx) => {
const path = ctx.req.params.path
const text = (await ctx.req.text() || '').trim().slice(0, 65536)
await ctx.env.KV.put(path, text, {
expirationTtl: 86400 * 365
})
ctx.res.status = 200
})
app.use(async (ctx) => {
const lastPath = await ctx.req.getCookie('last_path')
ctx.res.redirect(lastPath || randomPath())
})
export default app
function randomPath (len = 6) {
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
let result = ''
for (let i = 0; i < len; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}