The AppServer class provides static methods to set up and start a Fastify server. This class cannot be instantiated.

The setupFastify method configures the Fastify instance with various hooks and handlers, including logging for incoming requests and responses, periodic idle time checks, and a 404 not found handler. The startFastify method starts the Fastify server on a specified port and handles any errors that occur during startup.

import fastify from 'fastify';
import { AppServer } from './appServer';

const app = fastify();
AppServer.setupFastify(app);

AppServer.startFastify(app, 3000).then(() => {
app.log.info('Server started successfully');
}).catch(err => {
app.log.error('Failed to start server', err);
});

Constructors

Methods

  • Sets up the Fastify instance with various hooks and handlers.

    Parameters

    • app: FastifyInstance<
          RawServerDefault,
          IncomingMessage,
          ServerResponse<IncomingMessage>,
          FastifyBaseLogger,
          FastifyTypeProviderDefault,
      >

      The Fastify instance to set up.

    Returns FastifyInstance<
        RawServerDefault,
        IncomingMessage,
        ServerResponse<IncomingMessage>,
        FastifyBaseLogger,
        FastifyTypeProviderDefault,
    >

    The configured Fastify instance.

    This method configures the Fastify instance with the following:

    • An onRequest hook to log incoming requests and update the last activity time.
    • An onResponse hook to log responses with their status codes.
    • A periodic check for idle time, logging the total idle time if it exceeds 1 minute.
    • A setNotFoundHandler to handle 404 errors and log them.
    import fastify from 'fastify';
    import { setupFastify } from './appServer';

    const app = fastify();
    setupFastify(app);

    app.listen(3000, (err, address) => {
    if (err) {
    app.log.error(err);
    process.exit(1);
    }
    app.log.info(`Server listening at ${address}`);
    });
  • Starts the Fastify server on the specified port.

    Parameters

    • app: FastifyInstance<
          RawServerDefault,
          IncomingMessage,
          ServerResponse<IncomingMessage>,
          FastifyBaseLogger,
          FastifyTypeProviderDefault,
      >

      The Fastify instance to start.

    • port: number

      The port number on which the server should listen.

    Returns Promise<void>

    Will log an error and exit the process if the server fails to start.

    import fastify from 'fastify';
    import { AppServer } from './appServer';

    const app = fastify();
    AppServer.setupFastify(app);