Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ability to pass middleware to @astrojs/node when using standalone… #11516

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/nervous-ladybugs-wonder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/node': minor
---

add ability to pass node middleware to @astrojs/node when using standalone mode
3 changes: 3 additions & 0 deletions packages/integrations/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ export default function createIntegration(userOptions: UserOptions): AstroIntegr
if (!userOptions?.mode) {
throw new AstroError(`Setting the 'mode' option is required.`);
}
if (userOptions.mode !== 'standalone' && userOptions.standaloneMiddleware) {
throw new AstroError(`'standaloneMiddleware' option is only available in 'standalone' mode.`);
}

let _options: Options;
return {
Expand Down
20 changes: 20 additions & 0 deletions packages/integrations/node/src/standalone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,20 @@ export default function standalone(app: NodeApp, options: Options) {
const host = process.env.HOST ?? hostOptions(options.host);
const handler = createStandaloneHandler(app, options);
const server = createServer(handler, host, port);

// optionally add standalone middleware (if passed)
if (options.standaloneMiddleware) {
import(options.standaloneMiddleware)
.then((middleware) => {
server.updateServerListener((req: http.IncomingMessage, res: http.ServerResponse) => {
middleware.default(req, res, () => {
handler(req, res);
});
});
})
.catch(() => {});
}

server.server.listen(port, host);
if (process.env.ASTRO_NODE_LOGGING !== 'disabled') {
logListeningOn(app.getAdapterLogger(), server.server, options);
Expand Down Expand Up @@ -72,6 +86,11 @@ export function createServer(listener: http.RequestListener, host: string, port:
httpServer.addListener('error', reject);
});

const updateServerListener = (middleware: http.RequestListener) => {
httpServer.removeListener('request', listener);
httpServer.addListener('request', middleware);
}

const previewable = {
host,
port,
Expand All @@ -87,6 +106,7 @@ export function createServer(listener: http.RequestListener, host: string, port:

return {
server: httpServer,
updateServerListener,
...previewable,
};
}
4 changes: 4 additions & 0 deletions packages/integrations/node/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export interface UserOptions {
* - 'standalone' - Build to a standalone server. The server starts up just by running the built script.
*/
mode: 'middleware' | 'standalone';
/**
* Optional file path that (default) exports middleware function to be used in the standalone mode.
*/
standaloneMiddleware?: string;
}

export interface Options extends UserOptions {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const combineMiddleware = (...middlewares) => {
return (req, res, next) => {
let index = 0;

const run = (err) => {
if (err) {
return next(err);
}
if (index >= middlewares.length) {
return next();
}
const middleware = middlewares[index++];
try {
middleware(req, res, run);
} catch (error) {
next(error);
}
};

run();
};
};

const middleware_one = (req, res, next) => {
if (req.url === '/middleware-one') {
res.end('This is middleware one');
} else {
next();
}
};

const middleware_two = (req, res, next) => {
if (req.url === '/middleware-two') {
res.end('This is middleware two');
} else {
next();
}
};

export default combineMiddleware(middleware_one, middleware_two);
123 changes: 123 additions & 0 deletions packages/integrations/node/test/node-middleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,126 @@ describe('behavior from middleware, middleware', () => {
assert.equal(body.text().includes("Here's a random number"), true);
});
});

describe('behavior from middleware, standalone `mode` passing `standaloneMiddleware` path', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
let server;

before(async () => {
process.env.PRERENDER = false;
fixture = await loadFixture({
root: './fixtures/node-middleware/',
output: 'server',
adapter: nodejs(
{
mode: 'standalone',
standaloneMiddleware: new URL('./fixtures/node-middleware/src/node-middleware.mjs', import.meta.url).toString(),
}
),
});
await fixture.build();
const { startServer } = await fixture.loadAdapterEntryModule();
let res = await startServer();
server = res.server;
await waitServerListen(server.server);
});

after(async () => {
await server.stop();
await fixture.clean();
delete process.env.PRERENDER;
});

describe('middleware-one', async () => {
it('when mode is standalone, calling middleware-one', async () => {
const res = await fetch(`http://${server.host}:${server.port}/middleware-one`);

assert.equal(res.status, 200);

const html = await res.text();
const $ = cheerio.load(html);

const body = $('body');
assert.equal(body.text().includes('This is middleware one'), true);
});
});

describe('middleware-two', async () => {
it('when mode is standalone, calling middleware-two', async () => {
const res = await fetch(`http://${server.host}:${server.port}/middleware-two`);

assert.equal(res.status, 200);

const html = await res.text();
const $ = cheerio.load(html);

const body = $('body');
assert.equal(body.text().includes('This is middleware two'), true);
});
});
});

describe('behavior from middleware, standalone `mode` dont pass `standaloneMiddleware` option', () => {
/** @type {import('./test-utils').Fixture} */

it('when mode is `middleware` and `standaloneMiddleware` is passed.', async () => {
try {
await loadFixture({
root: './fixtures/node-middleware/',
output: 'server',
adapter: nodejs({ mode: 'middleware', standaloneMiddleware: new URL('./fixtures/node-middleware/src/node-middleware.mjs', import.meta.url).toString() }),
});
assert.fail('should have thrown an error');
} catch (err) {
assert.equal(err.message, `'standaloneMiddleware' option is only available in 'standalone' mode.`);
}
});
});

describe('behavior from middleware, standalone mode with incorrect standaloneMiddleware path', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
let server;

before(async () => {
process.env.PRERENDER = false;
fixture = await loadFixture({
root: './fixtures/node-middleware/',
output: 'server',
adapter: nodejs({ mode: 'standalone', standaloneMiddleware: `wrong-path/node-middleware.mjs` }),
});
await fixture.build();
const { startServer } = await fixture.loadAdapterEntryModule();
let res = startServer();
server = res.server;
await waitServerListen(server.server);
});

after(async () => {
await server.stop();
await fixture.clean();
delete process.env.PRERENDER;
});

describe('404', async () => {
it('when mode is standalone and wrong standaloneMiddleware path, 404 page', async () => {
const res = await fetch(`http://${server.host}:${server.port}/error-page`);

assert.equal(res.status, 404);

const html = await res.text();
const $ = cheerio.load(html);

const body = $('body');
assert.equal(body.text().includes('Page does not exist'), true);
});
});

describe('200', async () => {
it('when mode is standalone and wrong standaloneMiddleware path, 200 page', async () => {
const res = await fetch(`http://${server.host}:${server.port}/`);
assert.equal(res.status, 200);
});
});
});
Loading