Application class.

Hierarchy

  • App

Constructors

  • Parameters

    Returns App

Properties

_contextClass: any = ...
_nestedHelpers: Record<string, NestedHelpers> = {}
cli: CLI = ...

Command line interface.

Example

// Add another path to load commands from
app.cli.commandPaths.push(app.home.child('cli').toString());
config: Record<string, any>

Application config.

Example

// Remove value
delete app.config.foo;

// Assign multiple values at once
Object.assign(app.config, {foo: 'test', bar: 23});
defaults: Record<string, any> = {}

Default stash values.

Example

// Remove value
delete app.defaults.foo;

// Assign multiple values at once
Object.assign(app.defaults, {foo: 'test', bar: 23});
detectImport: boolean

Detect if the application has been imported and disable the command line interface if it has.

exceptionFormat: string

Format for HTTP exceptions ("html", "json", or "txt").

Example

// Change default exception format for whole application
app.exceptionFormat = 'json';
home: default = ...

Application home directory.

Example

// Portably generate path relative to home directory
const path = app.home.child('data', 'important.txt');
hooks: Hooks = ...

Application hooks.

Example

// Run a custom hook
await app.hooks.runHook('my:hook', foo, bar);
log: Logger

Application logger.

Example

// Log debug message
app.log.debug('It works');
mime: Mime = ...

MIME types.

Example

// Get MIME type for extension
const type = app.mime.extType('txt');
mode: string

Operating mode for application. Defaults to the value of the NODE_ENV environment variable or development.

models: MojoModels = {}

Storage for user defined models.

Example

// Store database connection
app.models.pg = new Pg('postgres://127.0.0.1:5432/db');
renderer: Renderer = ...

Application renderer.

Example

// Disable compression
app.renderer.autoCompress = false;

// Add another "views" directory
app.renderer.viewPaths.push(app.home.child('views').toString());
router: Router = ...

Application router.

Example

// Add routes
const r = app.router;
r.get('/foo/bar').to('test#foo', {title: 'Hello Mojo!'});
r.post('/baz').to('test#baz');

// Add another path to load controllers from
app.router.controllerPaths.push(app.home.child('more-controllers').toString());
secrets: string[]

Rotating secret passphrases used for signed cookies and the like.

Example

// Rotate passphrases
app.secrets = ['new_passw0rd', 'old_passw0rd', 'very_old_passw0rd'];
session: Session = ...

Encrypted cookie based session manager.

Example

// Change name of cookie used for all sessions
app.sessions.cookieName = 'mysession';

// Disable SameSite feature
app.sessions.sameSite = 'none';
static: Static = ...

Static file server.

Example

// Add another "public" directory
app.static.publicPaths.push('/home/sri/public');

// Add another "public" directory with higher precedence
app.static.publicPaths.unshift('/home/sri/themes/blue/public');
ua: UserAgent = ...

HTTP/WebSocket user-agent.

Example

# Perform HTTP request
const res = await app.ua.get('http://example.com');
validator: Validator = ...

JSON schema validator.

Example

// Add a named schema for later use
app.validator.addSchema({type: 'object', properties: {test: {type: 'number'}}}, 'testForm');

Methods

  • Add an application hook to extend the framework.

    Parameters

    • name: string
    • fn: AppHook

    Returns App

    Example

    // Run code whenever a server has been started
    app.addAppHook('server:start', async app => {
    ...
    });
  • Add a context hook to extend the framework.

    Parameters

    • name: string
    • fn: ContextHook

    Returns App

    Example

    // Run code after a new request has been received
    app.addContextHook('dispatch:before', async ctx => {
    ...
    });
  • Add a helper.

    Parameters

    Returns App

    Example

    // Render response with header
    app.addHelper('renderWithHeader', async (ctx, ...args) => {
    ctx.res.set('X-Mojo', 'I <3 mojo.js!');
    await ctx.render(...args);
    });

    // Render response with header using nested helper
    app.addHelper('renderWith.header', async (ctx, ...args) => {
    ctx.res.set('X-Mojo', 'I <3 mojo.js!');
    await ctx.render(...args);
    });
  • Generate route matching any of the listed HTTP request methods or all.

    Parameters

    Returns Route

    Example

    // Route with pattern and destination
    app.any('/user').to('User#whatever');

    // Route with HTTP methods, pattern, restrictive placeholders and destination
    app.any(['DELETE', 'PUT'], '/:foo', {foo: /\w+/}).to('Foo#bar');

    // Route with pattern, name and destination
    app.any('/:foo').name('foo_route').to('Foo#bar');

    // Route with pattern, condition and destination
    app.any('/').requires({agent: /Firefox/}).to('Foo#bar');

    // Route with pattern and a closure as destination
    app.any('/:foo', async ctx => ctx.render({text: 'Hello World!'}));
  • Decorate context class with a method or getter/setter.

    Parameters

    • name: string
    • fn: Decoration

    Returns App

    Example

    // Decorate context with getter
    app.decorateContext('helloWorld', {get: () => 'Hello World!'});
  • Generate route matching only DELETE requests.

    Parameters

    Returns Route

    Example

    // Route with destination
    app.delete('/user').to('User#remove');
  • Generate route matching only GET requests.

    Parameters

    Returns Route

    Example

    // Route with destination
    app.get('/user').to('User#show');
  • Handle a new incoming request, used by servers.

    Parameters

    Returns Promise<void>

  • Create a mock context for application. Very useful for testing helpers.

    Parameters

    • options: {
          headers?: string[];
          method?: string;
          url?: string;
      } = {}
      • Optional headers?: string[]
      • Optional method?: string
      • Optional url?: string

    Returns MojoContext

    Example

    // Use a mock context to call a helper
    const ctx = app.newMockContext();
    const html = ctx.assetTag('/app.js');
  • Create a new test user-agent for application.

    Parameters

    Returns Promise<TestUserAgent>

    Example

    // Test plain text endpoint
    const ua = await app.newTestUserAgent();
    (await ua.getOk('/')).statusIs(200).bodyIs('Hello World!');
  • Your main hook into the application, it is a shortcut for the app:start hook and runs during application startup. You can use it to perform tasks like preparing database connections.

    Parameters

    • fn: AppHook

    Returns App

    Example

    // Perform async operations on application startup
    app.onStart(async app => {
    if (app.models.db === undefined) app.models.db = new SomeDatabase();
    await app.models.db.connect();
    });
  • The opposite of onStart, it is a shortcut for the app:stop hook and runs during application shutdown. You can use it to perform tasks like closing database connections gracefully.

    Parameters

    • fn: AppHook

    Returns App

    Example

    app.onStop(async app => {
    await app.models.db.disconnect();
    });
  • Generate route matching only OPTIONS requests.

    Parameters

    Returns Route

    Example

    // Route with destination
    app.options('/user').to('User#overview');
  • Generate route matching only PATCH requests.

    Parameters

    Returns Route

    Example

    // Route with destination
    app.patch('/user').to('User#update');
  • Register plugin.

    Type Parameters

    • T

    Parameters

    • plugin: ((app, options) => T)
        • (app, options): T
        • Parameters

          • app: App
          • options: Record<string, any>

          Returns T

    • options: Record<string, any> = {}

    Returns T

    Example

    // Mount application under "/prefix"
    app.plugin(mountPlugin, {app: myOtherApp, path: '/prefix'});

    // Load configuration from file
    app.plugin(jsonConfigPlugin, {file: 'myapp.conf'});
  • Generate route matching only POST requests.

    Parameters

    Returns Route

    Example

    // Route with destination
    app.post('/user').to('User#create');
  • Generate route matching only PUT requests.

    Parameters

    Returns Route

    Example

    // Route with destination
    app.put('/user').to('User#replace');
  • Start the command line interface.

    Parameters

    • Optional command: string
    • Rest ...args: string[]

    Returns Promise<void>

    Example

    // Get arguments from "process.argv"
    app.start();

    // Always start server (rarely used)
    app.start('server', '-l', 'http://*:8080');
  • Generate route for a nested route with its own intermediate destination.

    Parameters

    Returns Route

    Example

    // Intermediate destination and prefix shared between two routes
    const auth = app.under('/user').to('User#auth');
    auth.get('/show').to('User#show');
    auth.post('/create').to('User#create');
  • Warmup the cache, usually called automatically.

    Returns Promise<void>

  • Generate route matching only WebSocket handshake requests.

    Parameters

    Returns Route

    Example

    // Route with destination
    app.websocket('/echo').to('Example#echo');

Generated using TypeDoc