Core
Cache, environment and shutdown
ctx.cache, typed environment variables, and clean start-up and shutdown.
#Cache
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
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
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
onClosehandlers 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
SIGTERMorSIGINTthe server stops accepting requests,/readyanswers 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); afterstop()it rejects. A port that is taken rejects withPortInUseError.
Programmatic use (createApp returns { app, ctx, start, stop, state }) and the full state machine are in docs/lifecycle.md.