commit 6bd82af80af558f986af0caf1800f24c5ece0936 Author: fmatte Date: Mon Sep 1 17:08:04 2025 -0400 Add SSE diff --git a/SSE.md b/SSE.md new file mode 100644 index 0000000..83cdc64 --- /dev/null +++ b/SSE.md @@ -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 } +```