@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/app
Load 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
└── view
Starting 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/controller
databaseUrl
:String
. A MongoDB connection string to use for persistent storage. Defaults tonull
enforceHttps
:Boolean
. Whether to use redirect HTTP requests to HTTPS. Defaults totrue
whenoptions.env
isproduction
, andfalse
whenoptions.env
isdevelopment
env
:String
. The environment that the application is running in. Defaults to theNODE_ENV
environment variable, ordevelopment
if it's not setlogger
:Object
. An object with log methods. Defaults toconsole
logger.info
:Function
. A function used to log information. Defaults toconsole.info
logger.error
:Function
. A function used to log errors. Defaults toconsole.error
logger.debug
:Function
. A function used to log debug messages. Defaults toconsole.debug
modelSubPath
:String
. The path to look for application models in. Will be prepended withoptions.basePath
. Defaults toserver/model
name
:String
. The name of the application. Used in logs. Defaults toApp
port
:Number
. The port that the application should run on. Defaults to thePORT
environment variable or8080
if 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/public
requestLogFormat
:String
. The request log format, see the Morgan documentation for more information. Defaults tocombined
whenoptions.env
isproduction
, anddev
whenoptions.env
isdevelopment
requestLogOutputStream
:Stream
. The stream to pipe request logs into. Defaults toprocess.stdout
securityConfig
: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.basePath
andoptions.sassSubPath
. Defaults to{'/main.css': 'main.scss'}
sassSubPath
: The path to look for Sass files in. Will be prepended withoptions.basePath
. Defaults toclient/sass
sessionSecret
: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 tonull
trustProxy
: Express trust proxy settings. This is only used ifoptions.env
is "production". Defaults totrue
useSecureCookies
:Boolean
. Whether to use secure cookies. Defaults totrue
whenoptions.env
isproduction
, andfalse
whenoptions.env
isdevelopment
viewSubPath
: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
. TheApp
instance.request
:Object
. The Expressrequest
object 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 thesetup
method 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:connected
eventsetupExpress
: Initialise express and an HTTP serversetupModels
: Load models from the file system and add them toapp.models
startServer
: 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-basic
to start the application and visit localhost:8080.TODO: a TODO-list application. Run
npm run example-todo
to 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
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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
5 years ago
5 years ago
5 years ago
5 years ago