↑ ↓ to move · Enter to open · Esc to close

Core

Cache, environment and shutdown

ctx.cache, typed environment variables, and clean start-up and shutdown.

#Cache

js
export default (router, ctx) => {
  router.get('/', async (req, res) => {
    // runs once even when many requests arrive together; a failure is not cached
    const posts = await ctx.cache.wrap('posts', () => db.posts(), '30s');
    res.json(posts);
  });
};

ctx.cache is shared by all routes and plugins. For a separate cache use createCache({ ttl: '5m', max: 500 }). It has get, set, has, delete, clear, wrap and size; the least recently used entry goes first. Durations are milliseconds or strings such as '30s', '5m', '1h', '2d'.

cacheControl('1h') is a route middleware that sets Cache-Control for browsers and CDNs; cacheControl(0) sends no-store.

#Environment

js
import { defineEnv } from 'white-js';

export const env = defineEnv({
  PORT: 'port',
  DATABASE_URL: 'url',
  DEBUG: { type: 'boolean', default: false },
  LEVEL: ['debug', 'info', 'warn'],              // one of
  SENTRY_DSN: { type: 'url', optional: true },
});

Types: string (default), number, integer, port, boolean, url. Every problem is reported at once, and the result is frozen.

#Start-up, shutdown and cleanup

js
export default (app, ctx) => {
  const db = connect();
  ctx.onClose(() => db.end(), { name: 'database' });   // runs on shutdown, and if start-up fails
};
  • If anything fails while the app is being built (a plugin throws, a route file is invalid, a protocol is blocked), the onClose handlers of everything that was already set up run in reverse order and the original error is thrown. A failed start leaves no open connections.
  • On SIGTERM or SIGINT the server stops accepting requests, /ready answers 503, running requests finish, the handlers run (last registered first, one failing does not stop the others) and the process exits with 0. A second signal during shutdown is ignored.
  • shutdownTimeout (10 seconds) limits the whole shutdown, handlers included. When it runs out the remaining connections are closed, the log names the handlers that did not finish, and the exit code is 1.
  • start() can be called repeatedly (you get the same server); after stop() it rejects. A port that is taken rejects with PortInUseError.

Programmatic use (createApp returns { app, ctx, start, stop, state }) and the full state machine are in docs/lifecycle.md.