Content-Length: 267822 | pFad | http://github.com/ljlm0402/typescript-express-starter/issues/215

99 Graceful close · Issue #215 · ljlm0402/typescript-express-starter · GitHub
Skip to content

Graceful close #215

Open
Open
@jeanniton-mnr

Description

@jeanniton-mnr

Graceful close

Motivation

I want to ensure there is no brute (sub-)process termination and that any open requests are fulfilled when the Express server is closing.

// POST endpoint to process the shopping cart
app.post('/purchase', (req, res) => {
  // Get the items from the request body

  try {
      const { buyer, items } = req.body;
      
      // Process the items (e.g., calculate total price, initiate payment, etc.)
      const totalPrice = calculateTotalPrice(items);
      // Charge the buyer for the purchase
      const payment = chargeBuyerForPurchase(totalPrice);
      
      // 🥷 I don't want the server to close before it executes this line for every request
      // Create shipping for the purchased items
      const shipping = carrierAPI.createShipping(items, buyer.address);

      res.status(200).json([totalPrice, payment, shipping]);
      // 💁‍♂️ This is now safe to close the server
    } catch (error) {
      next(error);
    }

});

Proposed Solution

See documentation at this link

// ./src/app.ts
import process from 'node:process';

// Begin reading from stdin so the process does not exit.
process.stdin.resume();

process.on('SIGINT', () => {
  console.log('Received SIGINT. Press Control-D to exit.');
});

// FYI docker "stop" <container>, a process manager, and most hosts will send SIGTERM signal when it is shutting down.
// server.close stops the server from accepting new connections and closes all connections connected to this server that are not sending a request or waiting for a response
function gracefulClose(signal) {
  console.log(`Received ${signal}`);
  const server = this.app.listen(this.port, () => { ... } );
  server.close( () => { log('HTTP(S) server closed') } );

}

process.on('SIGINT', gracefulClose);
process.on('SIGTERM', gracefulClose);

Is it a feature to implement? Is this feature redundant?

Metadata

Metadata

Assignees

Labels

⚡ FeatureSuggest an idea for this project

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions









    ApplySandwichStrip

    pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


    --- a PPN by Garber Painting Akron. With Image Size Reduction included!

    Fetched URL: http://github.com/ljlm0402/typescript-express-starter/issues/215

    Alternative Proxies:

    Alternative Proxy

    pFad Proxy

    pFad v3 Proxy

    pFad v4 Proxy