Skip to content

chubbyts/chubbyts-undici-server-node

Repository files navigation

chubbyts-undici-server-node

CI Coverage Status Mutation testing badge npm-version

bugs code_smells coverage duplicated_lines_density ncloc sqale_rating alert_status reliability_rating security_rating sqale_index vulnerabilities

Description

Use @chubbyts/chubbyts-undici-server on node.js.

Requirements

Installation

Through NPM as @chubbyts/chubbyts-undici-server-node.

npm i @chubbyts/chubbyts-undici-server-node@^1.0.1

Usage

import { STATUS_CODES } from 'node:http';
import type { Server } from 'node:http';
import { createServer } from 'node:http';
import type { Handler, ServerRequest } from '@chubbyts/chubbyts-undici-server/dist/server';
import { Response } from '@chubbyts/chubbyts-undici-server/dist/server';
import {
  createNodeRequestToUndiciRequestFactory,
  createUndiciResponseToNodeResponseEmitter,
} from '@chubbyts/chubbyts-undici-server-node/dist/node';

const serverHost = process.env.SERVER_HOST as string;
const serverPort = parseInt(process.env.SERVER_PORT as string);

const shutdownServer = (server: Server) => {
  server.close((err) => {
    if (err) {
      console.warn(`Shutdown server with error: ${err}`);
      process.exit(1);
    }

    console.log('Shutdown server');
    process.exit(0);
  });
};

const nodeRequestToUndiciRequestFactory = createNodeRequestToUndiciRequestFactory('https://example.com');

// for example @chubbyts/chubbyts-framework app (which implements Handler)
const handler: Handler = async (serverRequest: ServerRequest<{name: string}>): Promise<Response> => {
  return new Response(`Hello, ${serverRequest.attributes.name}`, {
    status: 200,
    statusText: STATUS_CODES[200],
    headers: {'content-type': 'text/plain'}
  });
};

const undiciResponseToNodeResponseEmitter = createUndiciResponseToNodeResponseEmitter();

const server = createServer(async (req, res) => {
  const serverRequest = nodeRequestToUndiciRequestFactory(req);
  const response = await handler(serverRequest);
  undiciResponseToNodeResponseEmitter(response, res);
});

server.listen(serverPort, serverHost, () => {
  console.log(`Listening to ${serverHost}:${serverPort}`);
});

process.on('SIGINT', () => shutdownServer(server));
process.on('SIGTERM', () => shutdownServer(server));

Copyright

2025 Dominik Zogg

About

Use @chubbyts/chubbyts-undici-server on node.js.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published