diff --git a/src/index.ts b/src/index.ts index c9ad370b..9423e607 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5997,15 +5997,24 @@ export default class Elysia< * // Sometime later * app.stop() * ``` + * + * @example + * ```typescript + * const app = new Elysia() + * .get("/", () => 'hi') + * .listen(3000) + * + * app.stop(true) // Abruptly any requests inflight + * ``` */ - stop = async () => { + stop = async (closeActiveConnections?: boolean) => { if (!this.server) throw new Error( "Elysia isn't running. Call `app.listen` to start the server." ) if (this.server) { - this.server.stop() + this.server.stop(closeActiveConnections) this.server = null if (this.event.stop.length) diff --git a/test/core/stop.test.ts b/test/core/stop.test.ts new file mode 100644 index 00000000..f4bc2a6f --- /dev/null +++ b/test/core/stop.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'bun:test' + +import { Elysia } from '../../src' + +describe('Stop', () => { + + it("shuts down the server when stop(true) is called", async () => { + const app = new Elysia(); + app.get("/health", "hi"); + + const port = 8080; + const server = app.listen(port); + + await fetch(`http://localhost:${port}/health`); + + await server.stop(true); + + // Check if the server is still running + try { + await fetch(`http://localhost:${port}/health`); + throw new Error("Server is still running after teardown"); + } catch (error) { + expect((error as Error).message).toContain('Unable to connect'); + } + }) + + it("does not shut down the server when stop(false) is called", async () => { + const app = new Elysia(); + app.get("/health", "hi"); + + const port = 8081; + const server = app.listen(port); + + await fetch(`http://localhost:${port}/health`) + + await server.stop(false); + + // Check if the server is still running + try { + const response = await fetch(`http://localhost:${port}/health`); + expect(response.status).toBe(200); + expect(await response.text()).toBe("hi"); + } catch (error) { + throw new Error("Server unexpectedly shut down"); + } + }) + +}) \ No newline at end of file