-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
63 lines (61 loc) · 2.24 KB
/
worker.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
export default {
fetch: (req, env) => env.LOGGER.get(env.LOGGER.idFromName(new URL(req.url).hostname)).fetch(req)
}
export class Logger {
constructor(state, env) {
this.state = state
this.env = env
}
async fetch(req) {
const { user, redirect, body } = await this.env.CTX.fetch(req).then(res => res.json())
if (redirect) return Response.redirect(redirect)
const { origin, hostname, pathname, search, searchParams } = new URL(req.url)
const api = {
icon: '📕',
name: 'Logging.do',
description: 'Logging-as-a-Service API',
url: 'https://logging.do',
api: 'https://logging.do/api',
endpoints: {
getLogs: origin + '/api',
getEvent: origin + '/api/:eventId',
logEvent: origin + '/:level/:message',
},
type: 'https://apis.do',
repo: 'https://github.com/drivly/logging.do',
}
if (pathname == '/api') {
// const list = await this.state.storage.list({reverse: true, limit: 10}).then(list => Object.fromEntries(list))
const list = await this.state.storage.list({reverse: true, limit: 10}).then(list => Object.values(Object.fromEntries(list)))
return new Response(JSON.stringify({
api,
list,
user,
}, null, 2), { headers: { 'content-type': 'application/json; charset=utf-8' } })
} else if (pathname.startsWith('/api/')) {
const [_,id] = pathname.split('/api/')
console.log({id})
const event = await this.state.storage.get(id)
return new Response(JSON.stringify({
api,
id,
event,
user,
}, null, 2), { headers: { 'content-type': 'application/json; charset=utf-8' } })
}
const [_,level = null, message = null] = pathname.split('/')
const params = Object.fromEntries(searchParams)
const data = body
const ts = Date.now()
const time = new Date(ts).toISOString()
const id = req.headers.get('cf-ray')
const url = origin + '/api/' + id
const logged = { id, url, hostname, level, message, params, data, ts, time, user }
await this.state.storage.put(id, logged)
return new Response(JSON.stringify({
api,
logged,
user,
}, null, 2), { headers: { 'content-type': 'application/json; charset=utf-8' } })
}
}