Add SSE

master
fmatte 2025-09-01 17:08:04 -04:00
commit 6bd82af80a
1 changed files with 71 additions and 0 deletions

71
SSE.md Normal file

@ -0,0 +1,71 @@
# ./server/index.js
```js
import command from './admin/command/command.js'
server.use(servu.get('/admin/command/', redirect('/admin/command')))
server.use(servu.get('/admin/command', command.index))
server.use(servu.get('/admin/command/run/:id', command.run))
```
# ./admin/command/command.js
```js
import { nameChanged } from '#comico/commands/healthNameChanged'
import { infoCount } from '#comico/commands/infoCount'
import { importFromLibraries } from '#comico/commands/importFromLibraries'
const commands = {
1: { name: "Info: Count", func: infoCount },
2: { name: "Health: Name Changed", func: nameChanged },
3: { name: "Import", func: importFromLibraries }
}
const index = async (context) => {
const list = Object.keys(commands).map(id => ({ id, name: commands[id].name }))
await context.html(import.meta.dirname + '/command.mustache', { list, url: context.req.url }, {})
}
const run = async (context) => {
const { id } = context.req.params
const command = commands[id]
await context.sse(async (log) => {
log({ event: 'start', data: command.name })
await comico.command(command.func, (data) => log({ event: 'log', data }))
log({ event: 'stop', data: command.name })
})
}
export default { index, run }
```
# ./server/context.js
```js
const context = (req, res) => {
return {
sse: async (callback) => {
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
await callback((log) => {
res.write(`event: ${log.event}\ndata:${log.data}\n\n`)
})
res.end()
}
}
}
```
# ./comico/commands/infoCount.js
```js
const infoCount = async (comico, event = () => { }) => {
event(comico.comicsRepo.values.length + ' comics')
}
export { infoCount }
```