fix: memory leak warning #151

Massimo Melina committed Mar 14, 2023 at 15:04 UTC e80e0718870e2660c6f25386d679c9fdd42ad7b0
1 file changed +6 -2
src/api.plugins.ts
+6 -2
@@ -11,7 +11,7 @@ import {
11 } from './plugins'
12 import _ from 'lodash'
13 import assert from 'assert'
14 -import { newObj, onOff, wait } from './misc'
14 +import { Callback, newObj, onOff, wait } from './misc'
15 import { ApiHandlers, SendListReadable } from './apiMiddleware'
16 import events from './events'
17 import { rm } from 'fs/promises'
@@ -80,6 +80,10 @@ const apis: ApiHandlers = {
80 return new SendListReadable({
81 async doAtStart(list) {
82 try {
83 + // avoid creating N listeners on ctx.req, and getting a warning
84 + const undo: Callback[] = []
85 + ctx.req.once('close', () => undo.forEach(x => x()))
86 +
87 const folder2repo = getFolder2repo()
88 for await (const pl of searchPlugins(text)) {
89 const repo = pl.id
@@ -91,7 +95,7 @@ const apis: ApiHandlers = {
95 })
96 list.add(pl)
97 // watch for events about this plugin, until this request is closed
94 - ctx.req.on('close', onOff(events, {
98 + undo.push(onOff(events, {
99 pluginInstalled: p => {
100 if (p.repo === repo)
101 list.update({ id: repo }, { installed: true })