@mojojs/core
    Preparing search index...

    Class App

    Application class.

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

    Command line interface.

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

    Application config.

    // 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.

    // 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").

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

    Application home directory.

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

    Application hooks.

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

    Application logger.

    // Log debug message
    app.log.debug('It works');
    maxRequestSize: number = ...

    Maximum request body size in bytes, defaults to 16777216 (16 MiB). Requests exceeding the limit are answered with 413 when the body is read. Can also be changed for individual requests with ctx.req.maxMessageSize.

    // Allow larger uploads for the whole application
    app.maxRequestSize = 1024 * 1024 * 1024;
    mime: Mime = ...

    MIME types.

    // 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.

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

    Application renderer.

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

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

    Application router.

    // 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.

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

    Encrypted cookie based session manager.

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

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

    Static file server.

    // 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.

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

    JSON schema validator.

    // Add a named schema for later use
    app.validator.addSchema({type: 'object', properties: {test: {type: 'number'}}}, 'testForm');
    • Add an application hook to extend the framework.

      Parameters

      • name: string
      • fn: AppHook

      Returns this

      // 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 this

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

      Parameters

      Returns this

      // 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

      // 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 this

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

      Parameters

      Returns Route

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

      Parameters

      Returns Route

      // 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 } = {}

      Returns MojoContext

      // 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>

      // 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 this

      // 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 this

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

      Parameters

      Returns Route

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

      Parameters

      Returns Route

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

      Type Parameters

      • T

      Parameters

      • plugin: (app: App, options: Record<string, any>) => T
      • options: Record<string, any> = {}

      Returns T

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

      // Load configuration from file
      app.plugin(jsonConfigPlugin, {file: 'myapp.conf'});

    post

    • post(...args: RouteArguments): Route

      Generate route matching only POST requests.

      Parameters

      Returns Route

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

      Parameters

      Returns Route

      // Route with destination
      app.put('/user').to('User#replace');
    • Generate route matching only QUERY requests.

      Parameters

      Returns Route

      // Route with destination
      app.query('/search').to('Search#index');
    • Start the command line interface.

      Parameters

      • Optionalcommand: string
      • ...args: string[]

      Returns Promise<void>

      // 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

      // 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

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