@rowanmanning/app v1.0.0-alpha.32
@rowanmanning/app
Build Express applications with all of my preferences baked in.
Should I use this?
Not really. Unless you're Rowan Manning. Even then it's not advisable because this does too much - use express-config instead.
Table of Contents
Requirements
This library requires the following to run:
- Node.js 14+
Usage
Install with npm:
npm install @rowanmanning/appLoad the library into your code with a require call:
const App = require('@rowanmanning/app');Creating an app
To create an app, create an instance of the App class. options is an object, available options are documented here.
const app = new App(options);You may also want to extend the App class in order to add additional features or default some of the options to something that makes sense for you.
You'll also need to create the directory structure that your application needs. These folders are configurable, but the default directory structure is:
app
├── client
| ├── public
| └── sass
└── server
├── controller
├── model
└── viewStarting the app
To start the application, you'll need to use the setup method. This does not return anything, if you want to know when the application has started you can use events.
app.setup();Stopping the app
You can stop the application safely with:
app.teardown();App options
When you initialise a new application, the following options are available:
basePath:String. The path to look for application files in, prepended to all other paths. Defaults to<CWD>controllerSubPath:String. The path to look for application controllers in. Will be prepended withoptions.basePath. Defaults toserver/controllerdatabaseUrl:String. A MongoDB connection string to use for persistent storage. Defaults tonullenforceHttps:Boolean. Whether to use redirect HTTP requests to HTTPS. Defaults totruewhenoptions.envisproduction, andfalsewhenoptions.envisdevelopmentenv:String. The environment that the application is running in. Defaults to theNODE_ENVenvironment variable, ordevelopmentif it's not setlogger:Object. An object with log methods. Defaults toconsolelogger.info:Function. A function used to log information. Defaults toconsole.infologger.error:Function. A function used to log errors. Defaults toconsole.errorlogger.debug:Function. A function used to log debug messages. Defaults toconsole.debugmodelSubPath:String. The path to look for application models in. Will be prepended withoptions.basePath. Defaults toserver/modelname:String. The name of the application. Used in logs. Defaults toAppport:Number. The port that the application should run on. Defaults to thePORTenvironment variable or8080if it's not set.publicCacheMaxAge:Number. The cache max-age for public resources in production. Defaults to604800000(one week)publicSubPath:String. The path to look for application public files in. Will be prepended withoptions.basePath. Defaults toclient/publicrequestLogFormat:String. The request log format, see the Morgan documentation for more information. Defaults tocombinedwhenoptions.envisproduction, anddevwhenoptions.envisdevelopmentrequestLogOutputStream:Stream. The stream to pipe request logs into. Defaults toprocess.stdoutsecurityConfig:Object. Security configuration to pass into Helmet. Defaults toundefined.sassBundles:Object. A map of CSS URLs and Sass source paths, where each key is the URL path that the CSS bundle is served on, and each value is the location of the entry point Sass source file for that bundle, see Resave Sass for more information. The source paths are relative tooptions.basePathandoptions.sassSubPath. Defaults to{'/main.css': 'main.scss'}sassSubPath: The path to look for Sass files in. Will be prepended withoptions.basePath. Defaults toclient/sasssessionSecret:String. A secret used to sign session cookies with. If not set, sessions and flash messages are disabled. See express-session and connect-flash for documentation on these. Defaults tonulltrustProxy: Express trust proxy settings. This is only used ifoptions.envis "production". Defaults totrueuseSecureCookies:Boolean. Whether to use secure cookies. Defaults totruewhenoptions.envisproduction, andfalsewhenoptions.envisdevelopmentviewSubPath:String. The path to look for application views in. Will be prepended withoptions.basePath. Defaults toserver/view
View data
The following variables are automatically added to response.locals, and are available in all view files:
app:Object. TheAppinstance.request:Object. The Expressrequestobject that resulted in the render.currentUrl:String. The Expressrequest.url.currentPath:String. The Expressrequest.path.
App events
The App class extends EventEmitter, and you can listen on the following events:
database:connected: emitted when the MongoDB database connection has been set up.server:created: emitted when the node HTTP server has been set up. Called with the created HTTP serverserver:started: emitted when the HTTP server has started listening on a port. Called with the HTTP serversetup:error: emitted when thesetupmethod fails to set up the application. In this scenario it is no longer possible to start the application so it should be torn down
Extending
It's possible to extend the App class to add additional features or provide default options:
class MyApp extends App {
constructor(options = {}) {
options.name = 'My App';
super(options);
}
}The following methods can also be overridden to add or change behaviour. They are called in this order during startup:
setupClientAssetCompilation: Set up client-side asset compilation middlewaresetupControllers: Load controllers from the file systemsetupDatabase: Initialise the MongoDB database. See also thedatabase:connectedeventsetupExpress: Initialise express and an HTTP serversetupModels: Load models from the file system and add them toapp.modelsstartServer: Start the HTTP server
Examples
A ready-to-use main application file looks something like this:
const App = require('@rowanmanning/app');
const app = new App({
basePath: __dirname,
databaseUrl: process.env.DATABASE_URL,
name: 'My Application',
sessionSecret: process.env.SESSION_SECRET
});
// Catch setup errors
app.once('setup:error', error => {
process.exitCode = 1;
app.log.error(error.stack);
app.teardown();
});
// Set up the application
app.setup();There are also a few example implementations in the repo which demonstrate some features:
Basic: the simplest use of the library to render pages. Run
npm run example-basicto start the application and visit localhost:8080.TODO: a TODO-list application. Run
npm run example-todoto start the application and visit localhost:8080.
Contributing
The contributing guide is available here. All contributors must follow this library's code of conduct.
License
Licensed under the MIT license. Copyright © 2019, Rowan Manning
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago