2014-01-06 23:52:08 +00:00
|
|
|
/*!
|
2013-05-01 19:11:43 +00:00
|
|
|
* Module dependencies.
|
|
|
|
*/
|
|
|
|
|
2013-07-30 21:26:49 +00:00
|
|
|
var DataSource = require('loopback-datasource-juggler').DataSource
|
2014-06-06 09:47:25 +00:00
|
|
|
, registry = require('./registry')
|
2014-01-22 10:22:23 +00:00
|
|
|
, compat = require('./compat')
|
2013-05-23 16:53:42 +00:00
|
|
|
, assert = require('assert')
|
2013-10-29 21:12:23 +00:00
|
|
|
, fs = require('fs')
|
2014-05-25 14:27:45 +00:00
|
|
|
, extend = require('util')._extend
|
2014-02-18 19:20:23 +00:00
|
|
|
, _ = require('underscore')
|
2013-07-25 23:24:00 +00:00
|
|
|
, RemoteObjects = require('strong-remoting')
|
2013-10-29 21:12:23 +00:00
|
|
|
, swagger = require('strong-remoting/ext/swagger')
|
|
|
|
, stringUtils = require('underscore.string')
|
|
|
|
, path = require('path');
|
2013-05-01 19:11:43 +00:00
|
|
|
|
|
|
|
/**
|
2014-01-06 23:52:08 +00:00
|
|
|
* The `App` object represents a Loopback application.
|
|
|
|
*
|
|
|
|
* The App object extends [Express](http://expressjs.com/api.html#express) and
|
|
|
|
* supports
|
|
|
|
* [Express / Connect middleware](http://expressjs.com/api.html#middleware). See
|
|
|
|
* [Express documentation](http://expressjs.com/api.html) for details.
|
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* var loopback = require('loopback');
|
|
|
|
* var app = loopback();
|
|
|
|
*
|
|
|
|
* app.get('/', function(req, res){
|
|
|
|
* res.send('hello world');
|
|
|
|
* });
|
|
|
|
*
|
|
|
|
* app.listen(3000);
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @class LoopBackApplication
|
2014-01-13 16:02:32 +00:00
|
|
|
* @header var app = loopback()
|
2014-01-06 23:52:08 +00:00
|
|
|
*/
|
|
|
|
function App() {
|
2014-01-13 16:02:32 +00:00
|
|
|
// this is a dummy placeholder for jsdox
|
2014-01-06 23:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*!
|
2013-05-01 19:11:43 +00:00
|
|
|
* Export the app prototype.
|
|
|
|
*/
|
|
|
|
|
|
|
|
var app = exports = module.exports = {};
|
|
|
|
|
|
|
|
/**
|
2014-01-06 23:52:08 +00:00
|
|
|
* Lazily load a set of [remote objects](http://apidocs.strongloop.com/strong-remoting/#remoteobjectsoptions).
|
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* **NOTE:** Calling `app.remotes()` more than once returns only a single set of remote objects.
|
2014-01-06 23:52:08 +00:00
|
|
|
* @returns {RemoteObjects}
|
2013-05-23 16:53:42 +00:00
|
|
|
*/
|
2013-06-17 15:01:22 +00:00
|
|
|
|
2013-05-23 16:53:42 +00:00
|
|
|
app.remotes = function () {
|
|
|
|
if(this._remotes) {
|
|
|
|
return this._remotes;
|
|
|
|
} else {
|
2014-04-14 19:25:41 +00:00
|
|
|
var options = {};
|
|
|
|
|
|
|
|
if(this.get) {
|
|
|
|
options = this.get('remoting');
|
|
|
|
}
|
|
|
|
|
2014-02-19 23:14:31 +00:00
|
|
|
return (this._remotes = RemoteObjects.create(options));
|
2013-05-23 16:53:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-06 23:52:08 +00:00
|
|
|
/*!
|
2013-05-23 16:53:42 +00:00
|
|
|
* Remove a route by reference.
|
2013-05-01 19:11:43 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
app.disuse = function (route) {
|
|
|
|
if(this.stack) {
|
|
|
|
for (var i = 0; i < this.stack.length; i++) {
|
|
|
|
if(this.stack[i].route === route) {
|
|
|
|
this.stack.splice(i, 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-05-24 14:59:23 +00:00
|
|
|
/**
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
* Attach a model to the app. The `Model` will be available on the
|
2014-01-06 23:52:08 +00:00
|
|
|
* `app.models` object.
|
2013-05-01 19:11:43 +00:00
|
|
|
*
|
2014-01-06 23:52:08 +00:00
|
|
|
* ```js
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
* // Attach an existing model
|
|
|
|
* var User = loopback.User;
|
|
|
|
* app.model(User);
|
|
|
|
*
|
|
|
|
* // Attach an existing model, alter some aspects of the model
|
|
|
|
* var User = loopback.User;
|
|
|
|
* app.model(User, { dataSource: 'db' });
|
|
|
|
*
|
|
|
|
* // The old way: create and attach a new model (deprecated)
|
|
|
|
* var Widget = app.model('Widget', {
|
|
|
|
* dataSource: 'db',
|
|
|
|
* properties: {
|
|
|
|
* name: 'string'
|
|
|
|
* }
|
2014-01-06 23:52:08 +00:00
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
*
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
* @param {Object|String} Model The model to attach.
|
2014-04-02 22:15:21 +00:00
|
|
|
* @options {Object} config The model's configuration.
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
* @property {String|DataSource} dataSource The `DataSource` to which to
|
|
|
|
* attach the model.
|
|
|
|
* @property {Boolean} [public] whether the model should be exposed via REST API
|
|
|
|
* @property {Object} [relations] relations to add/update
|
2014-01-06 23:52:08 +00:00
|
|
|
* @end
|
|
|
|
* @returns {ModelConstructor} the model class
|
2013-05-01 19:11:43 +00:00
|
|
|
*/
|
2013-05-24 14:59:23 +00:00
|
|
|
|
2013-10-29 21:12:23 +00:00
|
|
|
app.model = function (Model, config) {
|
2014-06-10 06:53:01 +00:00
|
|
|
var isPublic = true;
|
|
|
|
if (arguments.length > 1) {
|
|
|
|
config = config || {};
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
if (typeof Model === 'string') {
|
|
|
|
// create & attach the model - backwards compatibility
|
|
|
|
|
|
|
|
// create config for loopback.modelFromConfig
|
|
|
|
var modelConfig = extend({}, config);
|
|
|
|
modelConfig.options = extend({}, config.options);
|
|
|
|
modelConfig.name = Model;
|
|
|
|
|
|
|
|
// modeller does not understand `dataSource` option
|
|
|
|
delete modelConfig.dataSource;
|
|
|
|
|
2014-06-09 09:18:52 +00:00
|
|
|
Model = registry.createModel(modelConfig);
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
|
|
|
|
// delete config options already applied
|
|
|
|
['relations', 'base', 'acls', 'hidden'].forEach(function(prop) {
|
|
|
|
delete config[prop];
|
|
|
|
if (config.options) delete config.options[prop];
|
|
|
|
});
|
|
|
|
delete config.properties;
|
|
|
|
}
|
|
|
|
|
|
|
|
configureModel(Model, config, this);
|
2014-06-10 06:53:01 +00:00
|
|
|
isPublic = config.public !== false;
|
|
|
|
} else {
|
2014-06-16 07:52:11 +00:00
|
|
|
assert(Model.prototype instanceof registry.Model,
|
2014-06-06 08:30:03 +00:00
|
|
|
'Model must be a descendant of loopback.Model');
|
2013-10-29 21:12:23 +00:00
|
|
|
}
|
|
|
|
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
var modelName = Model.modelName;
|
2013-10-29 21:12:23 +00:00
|
|
|
this.models[modelName] =
|
2014-06-10 06:53:01 +00:00
|
|
|
this.models[classify(modelName)] =
|
|
|
|
this.models[camelize(modelName)] = Model;
|
2013-10-29 21:12:23 +00:00
|
|
|
|
2014-06-10 06:53:01 +00:00
|
|
|
this.models().push(Model);
|
|
|
|
|
|
|
|
if (isPublic) {
|
|
|
|
var remotingClassName = compat.getClassNameForRemoting(Model);
|
|
|
|
this.remotes().exports[remotingClassName] = Model;
|
|
|
|
clearHandlerCache(this);
|
2013-11-18 20:52:00 +00:00
|
|
|
}
|
2013-11-01 19:53:30 +00:00
|
|
|
|
2014-06-10 06:53:01 +00:00
|
|
|
Model.shared = isPublic; // The base Model has shared = true
|
|
|
|
Model.app = this;
|
|
|
|
Model.emit('attached', this);
|
2013-10-29 21:12:23 +00:00
|
|
|
return Model;
|
2014-06-10 06:53:01 +00:00
|
|
|
};
|
2013-05-24 14:59:23 +00:00
|
|
|
|
|
|
|
/**
|
2014-04-02 22:15:21 +00:00
|
|
|
* Get the models exported by the app. Returns only models defined using `app.model()`
|
2014-01-13 16:02:32 +00:00
|
|
|
*
|
2014-06-25 11:44:07 +00:00
|
|
|
* **Deprecated. Use the package
|
|
|
|
* [loopback-boot](https://github.com/strongloop/loopback-boot) instead.**
|
|
|
|
|
2014-04-02 22:15:21 +00:00
|
|
|
* There are two ways to access models:
|
2014-01-13 16:02:32 +00:00
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* 1. Call `app.models()` to get a list of all models.
|
2014-01-13 16:02:32 +00:00
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* var models = app.models();
|
|
|
|
*
|
|
|
|
* models.forEach(function (Model) {
|
|
|
|
* console.log(Model.modelName); // color
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* **2. Use `app.model` to access a model by name.
|
2014-01-13 16:02:32 +00:00
|
|
|
* `app.model` has properties for all defined models.
|
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* The following example illustrates accessing the `Product` and `CustomerReceipt` models
|
|
|
|
* using the `models` object.
|
2014-01-13 16:02:32 +00:00
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* var loopback = require('loopback');
|
|
|
|
* var app = loopback();
|
|
|
|
* app.boot({
|
|
|
|
* dataSources: {
|
|
|
|
* db: {connector: 'memory'}
|
|
|
|
* }
|
|
|
|
* });
|
|
|
|
*
|
|
|
|
* app.model('product', {dataSource: 'db'});
|
|
|
|
* app.model('customer-receipt', {dataSource: 'db'});
|
|
|
|
*
|
|
|
|
* // available based on the given name
|
|
|
|
* var Product = app.models.Product;
|
|
|
|
*
|
|
|
|
* // also available as camelCase
|
|
|
|
* var product = app.models.product;
|
|
|
|
*
|
|
|
|
* // multi-word models are avaiable as pascal cased
|
|
|
|
* var CustomerReceipt = app.models.CustomerReceipt;
|
|
|
|
*
|
|
|
|
* // also available as camelCase
|
|
|
|
* var customerReceipt = app.models.customerReceipt;
|
|
|
|
* ```
|
2014-01-06 23:52:08 +00:00
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* @returns {Array} Array of model classes.
|
2013-05-24 14:59:23 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
app.models = function () {
|
2013-11-15 04:19:46 +00:00
|
|
|
return this._models || (this._models = []);
|
2013-05-01 19:11:43 +00:00
|
|
|
}
|
|
|
|
|
2013-10-31 17:06:43 +00:00
|
|
|
/**
|
|
|
|
* Define a DataSource.
|
2014-01-06 23:52:08 +00:00
|
|
|
*
|
|
|
|
* @param {String} name The data source name
|
|
|
|
* @param {Object} config The data source config
|
2013-10-31 17:06:43 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
app.dataSource = function (name, config) {
|
|
|
|
this.dataSources[name] =
|
|
|
|
this.dataSources[classify(name)] =
|
2014-05-28 13:02:55 +00:00
|
|
|
this.dataSources[camelize(name)] =
|
|
|
|
dataSourcesFromConfig(config, this.connectors);
|
2013-10-31 17:06:43 +00:00
|
|
|
}
|
|
|
|
|
2014-05-28 13:02:55 +00:00
|
|
|
/**
|
|
|
|
* Register a connector.
|
|
|
|
*
|
|
|
|
* When a new data-source is being added via `app.dataSource`, the connector
|
|
|
|
* name is looked up in the registered connectors first.
|
|
|
|
*
|
|
|
|
* Connectors are required to be explicitly registered only for applications
|
|
|
|
* using browserify, because browserify does not support dynamic require,
|
|
|
|
* which is used by LoopBack to automatically load the connector module.
|
|
|
|
*
|
|
|
|
* @param {String} name Name of the connector, e.g. 'mysql'.
|
|
|
|
* @param {Object} connector Connector object as returned
|
|
|
|
* by `require('loopback-connector-{name}')`.
|
|
|
|
*/
|
|
|
|
app.connector = function(name, connector) {
|
|
|
|
this.connectors[name] =
|
|
|
|
this.connectors[classify(name)] =
|
|
|
|
this.connectors[camelize(name)] = connector;
|
|
|
|
};
|
|
|
|
|
2013-05-24 22:08:23 +00:00
|
|
|
/**
|
2013-07-17 21:30:38 +00:00
|
|
|
* Get all remote objects.
|
2014-04-02 22:15:21 +00:00
|
|
|
* @returns {Object} [Remote objects](http://apidocs.strongloop.com/strong-remoting/#remoteobjectsoptions).
|
2013-05-24 22:08:23 +00:00
|
|
|
*/
|
|
|
|
|
2013-07-17 21:30:38 +00:00
|
|
|
app.remoteObjects = function () {
|
|
|
|
var result = {};
|
|
|
|
var models = this.models();
|
2013-05-24 22:08:23 +00:00
|
|
|
|
2013-07-17 21:30:38 +00:00
|
|
|
// add in models
|
|
|
|
models.forEach(function (ModelCtor) {
|
|
|
|
// only add shared models
|
|
|
|
if(ModelCtor.shared && typeof ModelCtor.sharedCtor === 'function') {
|
2014-01-22 10:22:23 +00:00
|
|
|
result[compat.getClassNameForRemoting(ModelCtor)] = ModelCtor;
|
2013-07-17 21:30:38 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return result;
|
2013-05-24 22:08:23 +00:00
|
|
|
}
|
|
|
|
|
2014-01-13 16:02:32 +00:00
|
|
|
/**
|
|
|
|
* Enable swagger REST API documentation.
|
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* **Note**: This method is deprecated. Use [loopback-explorer](http://npmjs.org/package/loopback-explorer) instead.
|
2014-01-13 16:02:32 +00:00
|
|
|
*
|
|
|
|
* **Options**
|
|
|
|
*
|
|
|
|
* - `basePath` The basepath for your API - eg. 'http://localhost:3000'.
|
|
|
|
*
|
|
|
|
* **Example**
|
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* // enable docs
|
|
|
|
* app.docs({basePath: 'http://localhost:3000'});
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* Run your app then navigate to
|
|
|
|
* [the API explorer](http://petstore.swagger.wordnik.com/).
|
|
|
|
* Enter your API basepath to view your generated docs.
|
|
|
|
*
|
|
|
|
* @deprecated
|
2013-07-25 23:24:00 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
app.docs = function (options) {
|
|
|
|
var remotes = this.remotes();
|
|
|
|
swagger(remotes, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* Get a handler of the specified type from the handler cache.
|
|
|
|
*/
|
|
|
|
|
|
|
|
app.handler = function (type) {
|
|
|
|
var handlers = this._handlers || (this._handlers = {});
|
|
|
|
if(handlers[type]) {
|
|
|
|
return handlers[type];
|
|
|
|
}
|
|
|
|
|
|
|
|
var remotes = this.remotes();
|
|
|
|
var handler = this._handlers[type] = remotes.handler(type);
|
|
|
|
return handler;
|
|
|
|
}
|
|
|
|
|
2013-10-29 21:12:23 +00:00
|
|
|
/**
|
|
|
|
* An object to store dataSource instances.
|
|
|
|
*/
|
|
|
|
|
|
|
|
app.dataSources = app.datasources = {};
|
|
|
|
|
2013-11-15 04:19:46 +00:00
|
|
|
/**
|
|
|
|
* Enable app wide authentication.
|
|
|
|
*/
|
|
|
|
|
|
|
|
app.enableAuth = function() {
|
|
|
|
var remotes = this.remotes();
|
2014-06-06 01:53:30 +00:00
|
|
|
var app = this;
|
2013-11-15 04:19:46 +00:00
|
|
|
|
|
|
|
remotes.before('**', function(ctx, next, method) {
|
|
|
|
var req = ctx.req;
|
|
|
|
var Model = method.ctor;
|
|
|
|
var modelInstance = ctx.instance;
|
2013-12-11 05:49:18 +00:00
|
|
|
var modelId = modelInstance && modelInstance.id || req.param('id');
|
2013-11-15 04:19:46 +00:00
|
|
|
|
2014-06-06 01:53:30 +00:00
|
|
|
var modelSettings = Model.settings || {};
|
|
|
|
var errStatusCode = modelSettings.aclErrorStatus || app.get('aclErrorStatus') || 401;
|
|
|
|
if(!req.accessToken){
|
|
|
|
errStatusCode = 401;
|
|
|
|
}
|
|
|
|
|
2013-12-12 03:46:56 +00:00
|
|
|
if(Model.checkAccess) {
|
2014-03-17 21:40:05 +00:00
|
|
|
// Pause the request before checking access
|
|
|
|
// See https://github.com/strongloop/loopback-storage-service/issues/7
|
|
|
|
req.pause();
|
2013-12-12 03:46:56 +00:00
|
|
|
Model.checkAccess(
|
|
|
|
req.accessToken,
|
|
|
|
modelId,
|
2014-05-31 02:29:30 +00:00
|
|
|
method,
|
2013-12-12 03:46:56 +00:00
|
|
|
function(err, allowed) {
|
2014-03-17 21:40:05 +00:00
|
|
|
// Emit any cached data events that fired while checking access.
|
|
|
|
req.resume();
|
2013-12-12 03:46:56 +00:00
|
|
|
if(err) {
|
|
|
|
console.log(err);
|
|
|
|
next(err);
|
|
|
|
} else if(allowed) {
|
|
|
|
next();
|
|
|
|
} else {
|
2014-06-06 01:53:30 +00:00
|
|
|
|
|
|
|
var messages = {
|
|
|
|
403:'Access Denied',
|
|
|
|
404: ('could not find a model with id ' + modelId),
|
|
|
|
401:'Authorization Required'
|
|
|
|
};
|
|
|
|
|
|
|
|
var e = new Error(messages[errStatusCode] || messages[403]);
|
|
|
|
e.statusCode = errStatusCode;
|
2013-12-12 03:46:56 +00:00
|
|
|
next(e);
|
|
|
|
}
|
2013-11-15 04:19:46 +00:00
|
|
|
}
|
2013-12-12 03:46:56 +00:00
|
|
|
);
|
|
|
|
} else {
|
|
|
|
next();
|
|
|
|
}
|
2013-11-15 04:19:46 +00:00
|
|
|
});
|
2014-02-05 17:46:22 +00:00
|
|
|
|
|
|
|
this.isAuthEnabled = true;
|
|
|
|
};
|
2013-11-15 04:19:46 +00:00
|
|
|
|
2013-10-29 21:12:23 +00:00
|
|
|
/**
|
2014-01-06 23:52:08 +00:00
|
|
|
* Initialize an application from an options object or a set of JSON and JavaScript files.
|
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* This function takes an optional argument that is either a string or an object.
|
2014-01-06 23:52:08 +00:00
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* If the argument is a string, then it sets the application root directory based on the string value. Then it:
|
|
|
|
* 1. Creates DataSources from the `datasources.json` file in the application root directory.
|
|
|
|
* 2. Creates Models from the `models.json` file in the application root directory.
|
2014-01-06 23:52:08 +00:00
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* If the argument is an object, then it looks for `model`, `dataSources`, and `appRootDir` properties of the object.
|
|
|
|
* If the object has no `appRootDir` property then it sets the current working directory as the application root directory.
|
|
|
|
* Then it:
|
|
|
|
* 1. Creates DataSources from the `options.dataSources` object.
|
|
|
|
* 2. Creates Models from the `options.models` object.
|
|
|
|
*
|
|
|
|
* In both cases, the function loads JavaScript files in the `/models` and `/boot` subdirectories of the application root directory with `require()`.
|
2014-01-06 23:52:08 +00:00
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* **NOTE:** mixing `app.boot()` and `app.model(name, config)` in multiple
|
|
|
|
* files may result in models being **undefined** due to race conditions.
|
|
|
|
* To avoid this when using `app.boot()` make sure all models are passed as part of the `models` definition.
|
2014-01-13 16:02:32 +00:00
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* Throws an error if the config object is not valid or if boot fails.
|
2014-01-13 16:02:32 +00:00
|
|
|
*
|
2014-01-06 23:52:08 +00:00
|
|
|
* <a name="model-definition"></a>
|
|
|
|
* **Model Definitions**
|
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* The following is example JSON for two `Model` definitions: "dealership" and "location".
|
2014-01-06 23:52:08 +00:00
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* {
|
|
|
|
* "dealership": {
|
|
|
|
* // a reference, by name, to a dataSource definition
|
|
|
|
* "dataSource": "my-db",
|
|
|
|
* // the options passed to Model.extend(name, properties, options)
|
|
|
|
* "options": {
|
|
|
|
* "relations": {
|
|
|
|
* "cars": {
|
|
|
|
* "type": "hasMany",
|
|
|
|
* "model": "Car",
|
|
|
|
* "foreignKey": "dealerId"
|
|
|
|
* }
|
|
|
|
* }
|
|
|
|
* },
|
|
|
|
* // the properties passed to Model.extend(name, properties, options)
|
|
|
|
* "properties": {
|
|
|
|
* "id": {"id": true},
|
|
|
|
* "name": "String",
|
|
|
|
* "zip": "Number",
|
|
|
|
* "address": "String"
|
|
|
|
* }
|
|
|
|
* },
|
|
|
|
* "car": {
|
|
|
|
* "dataSource": "my-db"
|
|
|
|
* "properties": {
|
|
|
|
* "id": {
|
|
|
|
* "type": "String",
|
|
|
|
* "required": true,
|
|
|
|
* "id": true
|
|
|
|
* },
|
|
|
|
* "make": {
|
|
|
|
* "type": "String",
|
|
|
|
* "required": true
|
|
|
|
* },
|
|
|
|
* "model": {
|
|
|
|
* "type": "String",
|
|
|
|
* "required": true
|
|
|
|
* }
|
|
|
|
* }
|
|
|
|
* }
|
|
|
|
* }
|
|
|
|
* ```
|
2014-04-02 22:15:21 +00:00
|
|
|
* @options {String|Object} options Boot options; If String, this is the application root directory; if object, has below properties.
|
|
|
|
* @property {String} appRootDir Directory to use when loading JSON and JavaScript files (optional). Defaults to the current directory (`process.cwd()`).
|
|
|
|
* @property {Object} models Object containing `Model` definitions (optional).
|
|
|
|
* @property {Object} dataSources Object containing `DataSource` definitions (optional).
|
|
|
|
* @end
|
2014-01-06 23:52:08 +00:00
|
|
|
*
|
2014-01-13 16:02:32 +00:00
|
|
|
* @header app.boot([options])
|
2013-10-29 21:12:23 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
app.boot = function(options) {
|
|
|
|
options = options || {};
|
2013-11-04 22:07:26 +00:00
|
|
|
|
|
|
|
if(typeof options === 'string') {
|
|
|
|
options = {appRootDir: options};
|
|
|
|
}
|
|
|
|
var app = this;
|
|
|
|
var appRootDir = options.appRootDir = options.appRootDir || process.cwd();
|
2013-10-29 21:12:23 +00:00
|
|
|
var ctx = {};
|
|
|
|
var appConfig = options.app;
|
|
|
|
var modelConfig = options.models;
|
|
|
|
var dataSourceConfig = options.dataSources;
|
|
|
|
|
|
|
|
if(!appConfig) {
|
2013-11-04 22:07:26 +00:00
|
|
|
appConfig = tryReadConfig(appRootDir, 'app') || {};
|
2013-10-29 21:12:23 +00:00
|
|
|
}
|
|
|
|
if(!modelConfig) {
|
2013-11-04 22:07:26 +00:00
|
|
|
modelConfig = tryReadConfig(appRootDir, 'models') || {};
|
2013-10-29 21:12:23 +00:00
|
|
|
}
|
|
|
|
if(!dataSourceConfig) {
|
2013-11-04 22:07:26 +00:00
|
|
|
dataSourceConfig = tryReadConfig(appRootDir, 'datasources') || {};
|
2013-10-29 21:12:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
assertIsValidConfig('app', appConfig);
|
|
|
|
assertIsValidConfig('model', modelConfig);
|
|
|
|
assertIsValidConfig('data source', dataSourceConfig);
|
|
|
|
|
2013-12-06 01:42:06 +00:00
|
|
|
appConfig.host =
|
|
|
|
process.env.npm_config_host ||
|
|
|
|
process.env.OPENSHIFT_SLS_IP ||
|
|
|
|
process.env.OPENSHIFT_NODEJS_IP ||
|
|
|
|
process.env.HOST ||
|
|
|
|
appConfig.host ||
|
|
|
|
process.env.npm_package_config_host ||
|
|
|
|
app.get('host');
|
|
|
|
|
2014-02-18 19:20:23 +00:00
|
|
|
appConfig.port = _.find([
|
|
|
|
process.env.npm_config_port,
|
|
|
|
process.env.OPENSHIFT_SLS_PORT,
|
|
|
|
process.env.OPENSHIFT_NODEJS_PORT,
|
|
|
|
process.env.PORT,
|
|
|
|
appConfig.port,
|
|
|
|
process.env.npm_package_config_port,
|
|
|
|
app.get('port'),
|
|
|
|
3000
|
|
|
|
], _.isFinite);
|
2013-12-06 01:42:06 +00:00
|
|
|
|
2014-01-07 15:05:48 +00:00
|
|
|
appConfig.restApiRoot =
|
|
|
|
appConfig.restApiRoot ||
|
|
|
|
app.get('restApiRoot') ||
|
|
|
|
'/api';
|
|
|
|
|
2013-10-29 21:12:23 +00:00
|
|
|
if(appConfig.host !== undefined) {
|
|
|
|
assert(typeof appConfig.host === 'string', 'app.host must be a string');
|
|
|
|
app.set('host', appConfig.host);
|
|
|
|
}
|
|
|
|
|
|
|
|
if(appConfig.port !== undefined) {
|
|
|
|
var portType = typeof appConfig.port;
|
|
|
|
assert(portType === 'string' || portType === 'number', 'app.port must be a string or number');
|
|
|
|
app.set('port', appConfig.port);
|
|
|
|
}
|
|
|
|
|
2014-05-27 10:10:04 +00:00
|
|
|
assert(appConfig.restApiRoot !== undefined, 'app.restApiRoot is required');
|
|
|
|
assert(typeof appConfig.restApiRoot === 'string', 'app.restApiRoot must be a string');
|
|
|
|
assert(/^\//.test(appConfig.restApiRoot), 'app.restApiRoot must start with "/"');
|
|
|
|
app.set('restApiRoot', appConfig.restApiRoot);
|
2014-01-07 15:05:48 +00:00
|
|
|
|
2013-12-12 03:31:16 +00:00
|
|
|
for(var configKey in appConfig) {
|
|
|
|
var cur = app.get(configKey);
|
|
|
|
if(cur === undefined || cur === null) {
|
|
|
|
app.set(configKey, appConfig[configKey]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-10-29 21:12:23 +00:00
|
|
|
// instantiate data sources
|
|
|
|
forEachKeyedObject(dataSourceConfig, function(key, obj) {
|
2013-10-31 17:06:43 +00:00
|
|
|
app.dataSource(key, obj);
|
2013-10-29 21:12:23 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// instantiate models
|
|
|
|
forEachKeyedObject(modelConfig, function(key, obj) {
|
|
|
|
app.model(key, obj);
|
|
|
|
});
|
|
|
|
|
2013-11-20 22:18:54 +00:00
|
|
|
// try to attach models to dataSources by type
|
|
|
|
try {
|
2014-06-06 09:47:25 +00:00
|
|
|
registry.autoAttach();
|
2013-11-20 22:18:54 +00:00
|
|
|
} catch(e) {
|
|
|
|
if(e.name === 'AssertionError') {
|
|
|
|
console.warn(e);
|
|
|
|
} else {
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
2013-11-19 20:23:02 +00:00
|
|
|
|
2013-12-06 20:00:18 +00:00
|
|
|
// disable token requirement for swagger, if available
|
|
|
|
var swagger = app.remotes().exports.swagger;
|
|
|
|
var requireTokenForSwagger = appConfig.swagger
|
|
|
|
&& appConfig.swagger.requireToken;
|
|
|
|
if(swagger) {
|
|
|
|
swagger.requireToken = requireTokenForSwagger || false;
|
|
|
|
}
|
|
|
|
|
2013-10-29 21:12:23 +00:00
|
|
|
// require directories
|
2013-11-04 22:07:26 +00:00
|
|
|
var requiredModels = requireDir(path.join(appRootDir, 'models'));
|
2013-12-18 03:15:48 +00:00
|
|
|
var requiredBootScripts = requireDir(path.join(appRootDir, 'boot'));
|
2013-10-29 21:12:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function assertIsValidConfig(name, config) {
|
|
|
|
if(config) {
|
|
|
|
assert(typeof config === 'object', name + ' config must be a valid JSON object');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function forEachKeyedObject(obj, fn) {
|
|
|
|
if(typeof obj !== 'object') return;
|
|
|
|
|
|
|
|
Object.keys(obj).forEach(function(key) {
|
|
|
|
fn(key, obj[key]);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function classify(str) {
|
|
|
|
return stringUtils.classify(str);
|
|
|
|
}
|
|
|
|
|
|
|
|
function camelize(str) {
|
|
|
|
return stringUtils.camelize(str);
|
|
|
|
}
|
|
|
|
|
2014-05-28 13:02:55 +00:00
|
|
|
function dataSourcesFromConfig(config, connectorRegistry) {
|
2013-11-01 19:53:30 +00:00
|
|
|
var connectorPath;
|
|
|
|
|
|
|
|
assert(typeof config === 'object',
|
|
|
|
'cannont create data source without config object');
|
|
|
|
|
|
|
|
if(typeof config.connector === 'string') {
|
2014-05-28 13:02:55 +00:00
|
|
|
var name = config.connector;
|
|
|
|
if (connectorRegistry[name]) {
|
|
|
|
config.connector = connectorRegistry[name];
|
|
|
|
} else {
|
|
|
|
connectorPath = path.join(__dirname, 'connectors', name + '.js');
|
2013-11-01 19:53:30 +00:00
|
|
|
|
2014-05-28 13:02:55 +00:00
|
|
|
if (fs.existsSync(connectorPath)) {
|
|
|
|
config.connector = require(connectorPath);
|
|
|
|
}
|
2013-11-01 19:53:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-06-06 09:47:25 +00:00
|
|
|
return registry.createDataSource(config);
|
2013-10-29 21:12:23 +00:00
|
|
|
}
|
|
|
|
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
function configureModel(ModelCtor, config, app) {
|
2014-06-06 09:47:25 +00:00
|
|
|
assert(ModelCtor.prototype instanceof registry.Model,
|
2014-06-06 08:30:03 +00:00
|
|
|
'Model must be a descendant of loopback.Model');
|
2014-05-25 14:27:45 +00:00
|
|
|
|
2014-03-21 19:18:00 +00:00
|
|
|
var dataSource = config.dataSource;
|
|
|
|
|
|
|
|
if(typeof dataSource === 'string') {
|
|
|
|
dataSource = app.dataSources[dataSource];
|
|
|
|
}
|
2013-10-29 21:12:23 +00:00
|
|
|
|
2014-06-06 08:30:03 +00:00
|
|
|
assert(dataSource instanceof DataSource,
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
ModelCtor.modelName + ' is referencing a dataSource that does not exist: "' +
|
|
|
|
config.dataSource +'"');
|
2013-10-29 21:12:23 +00:00
|
|
|
|
Add createModelFromConfig and configureModel()
Add new API allowing developers to split the model definition and
configuration into two steps:
1. Build models from JSON config, export them for re-use:
```js
var Customer = loopback.createModelFromConfig({
name: 'Customer',
base: 'User',
properties: {
address: 'string'
}
});
```
2. Attach existing models to a dataSource and a loopback app,
modify certain model aspects like relations:
```js
loopback.configureModel(Customer, {
dataSource: db,
relations: { /* ... */ }
});
```
Rework `app.model` to use `loopback.configureModel` under the hood.
Here is the new usage:
```js
var Customer = require('./models').Customer;
app.model(Customer, {
dataSource: 'db',
relations: { /* ... */ }
});
```
In order to preserve backwards compatibility,
`app.model(name, config)` calls both `createModelFromConfig`
and `configureModel`.
2014-06-05 15:41:12 +00:00
|
|
|
config = extend({}, config);
|
|
|
|
config.dataSource = dataSource;
|
2014-05-25 14:27:45 +00:00
|
|
|
|
2014-06-06 09:47:25 +00:00
|
|
|
registry.configureModel(ModelCtor, config);
|
2014-05-25 14:27:45 +00:00
|
|
|
}
|
|
|
|
|
2013-10-29 21:12:23 +00:00
|
|
|
function requireDir(dir, basenames) {
|
|
|
|
assert(dir, 'cannot require directory contents without directory name');
|
|
|
|
|
|
|
|
var requires = {};
|
|
|
|
|
|
|
|
if (arguments.length === 2) {
|
|
|
|
// if basenames argument is passed, explicitly include those files
|
|
|
|
basenames.forEach(function (basename) {
|
|
|
|
var filepath = Path.resolve(Path.join(dir, basename));
|
|
|
|
requires[basename] = tryRequire(filepath);
|
|
|
|
});
|
|
|
|
} else if (arguments.length === 1) {
|
|
|
|
// if basenames arguments isn't passed, require all javascript
|
|
|
|
// files (except for those prefixed with _) and all directories
|
|
|
|
|
|
|
|
var files = tryReadDir(dir);
|
|
|
|
|
|
|
|
// sort files in lowercase alpha for linux
|
|
|
|
files.sort(function (a,b) {
|
|
|
|
a = a.toLowerCase();
|
|
|
|
b = b.toLowerCase();
|
|
|
|
|
|
|
|
if (a < b) {
|
|
|
|
return -1;
|
|
|
|
} else if (b < a) {
|
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
files.forEach(function (filename) {
|
|
|
|
// ignore index.js and files prefixed with underscore
|
|
|
|
if ((filename === 'index.js') || (filename[0] === '_')) { return; }
|
|
|
|
|
|
|
|
var filepath = path.resolve(path.join(dir, filename));
|
|
|
|
var ext = path.extname(filename);
|
|
|
|
var stats = fs.statSync(filepath);
|
|
|
|
|
|
|
|
// only require files supported by require.extensions (.txt .md etc.)
|
|
|
|
if (stats.isFile() && !(ext in require.extensions)) { return; }
|
|
|
|
|
|
|
|
var basename = path.basename(filename, ext);
|
|
|
|
|
|
|
|
requires[basename] = tryRequire(filepath);
|
|
|
|
});
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
return requires;
|
|
|
|
};
|
|
|
|
|
|
|
|
function tryRequire(modulePath) {
|
|
|
|
try {
|
|
|
|
return require.apply(this, arguments);
|
|
|
|
} catch(e) {
|
|
|
|
console.error('failed to require "%s"', modulePath);
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function tryReadDir() {
|
|
|
|
try {
|
|
|
|
return fs.readdirSync.apply(fs, arguments);
|
|
|
|
} catch(e) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function tryReadConfig(cwd, fileName) {
|
|
|
|
try {
|
|
|
|
return require(path.join(cwd, fileName + '.json'));
|
|
|
|
} catch(e) {
|
|
|
|
if(e.code !== "MODULE_NOT_FOUND") {
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-18 20:40:35 +00:00
|
|
|
function clearHandlerCache(app) {
|
|
|
|
app._handlers = undefined;
|
|
|
|
}
|
|
|
|
|
2014-04-03 18:29:00 +00:00
|
|
|
/*!
|
|
|
|
* This function is now deprecated.
|
2014-01-13 14:24:52 +00:00
|
|
|
* Install all express middleware required by LoopBack.
|
|
|
|
*
|
|
|
|
* It is possible to inject your own middleware by listening on one of the
|
|
|
|
* following events:
|
|
|
|
*
|
|
|
|
* - `middleware:preprocessors` is emitted after all other
|
|
|
|
* request-preprocessing middleware was installed, but before any
|
|
|
|
* request-handling middleware is configured.
|
|
|
|
*
|
|
|
|
* Usage:
|
|
|
|
* ```js
|
2014-01-14 07:07:47 +00:00
|
|
|
* app.once('middleware:preprocessors', function() {
|
2014-01-13 14:24:52 +00:00
|
|
|
* app.use(loopback.limit('5.5mb'))
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
* - `middleware:handlers` is emitted when it's time to add your custom
|
|
|
|
* request-handling middleware. Note that you should not install any
|
|
|
|
* express routes at this point (express routes are discussed later).
|
|
|
|
*
|
|
|
|
* Usage:
|
|
|
|
* ```js
|
2014-01-14 07:07:47 +00:00
|
|
|
* app.once('middleware:handlers', function() {
|
2014-01-13 14:24:52 +00:00
|
|
|
* app.use('/admin', adminExpressApp);
|
|
|
|
* app.use('/custom', function(req, res, next) {
|
|
|
|
* res.send(200, { url: req.url });
|
|
|
|
* });
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
* - `middleware:error-loggers` is emitted at the end, before the loopback
|
|
|
|
* error handling middleware is installed. This is the point where you
|
|
|
|
* can install your own middleware to log errors.
|
|
|
|
*
|
|
|
|
* Notes:
|
|
|
|
* - The middleware function must take four parameters, otherwise it won't
|
|
|
|
* be called by express.
|
|
|
|
*
|
|
|
|
* - It should also call `next(err)` to let the loopback error handler convert
|
|
|
|
* the error to an HTTP error response.
|
|
|
|
*
|
|
|
|
* Usage:
|
|
|
|
* ```js
|
|
|
|
* var bunyan = require('bunyan');
|
|
|
|
* var log = bunyan.createLogger({name: "myapp"});
|
2014-01-14 07:07:47 +00:00
|
|
|
* app.once('middleware:error-loggers', function() {
|
2014-01-13 14:24:52 +00:00
|
|
|
* app.use(function(err, req, res, next) {
|
|
|
|
* log.error(err);
|
|
|
|
* next(err);
|
|
|
|
* });
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* Express routes should be added after `installMiddleware` was called.
|
|
|
|
* This way the express router middleware is injected at the right place in the
|
|
|
|
* middleware chain. If you add an express route before calling this function,
|
|
|
|
* bad things will happen: Express will automatically add the router
|
|
|
|
* middleware and since we haven't added request-preprocessing middleware like
|
|
|
|
* cookie & body parser yet, your route handlers will receive raw unprocessed
|
|
|
|
* requests.
|
|
|
|
*
|
|
|
|
* This is the correct order in which to call `app` methods:
|
|
|
|
* ```js
|
|
|
|
* app.boot(__dirname); // optional
|
|
|
|
*
|
|
|
|
* app.installMiddleware();
|
|
|
|
*
|
|
|
|
* // [register your express routes here]
|
|
|
|
*
|
|
|
|
* app.listen();
|
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
app.installMiddleware = function() {
|
|
|
|
var loopback = require('../');
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Request pre-processing
|
|
|
|
*/
|
|
|
|
this.use(loopback.favicon());
|
|
|
|
// TODO(bajtos) refactor to app.get('loggerFormat')
|
|
|
|
var loggerFormat = this.get('env') === 'development' ? 'dev' : 'default';
|
|
|
|
this.use(loopback.logger(loggerFormat));
|
|
|
|
this.use(loopback.cookieParser(this.get('cookieSecret')));
|
|
|
|
this.use(loopback.token({ model: this.models.accessToken }));
|
|
|
|
this.use(loopback.bodyParser());
|
|
|
|
this.use(loopback.methodOverride());
|
|
|
|
|
|
|
|
// Allow the app to install custom preprocessing middleware
|
|
|
|
this.emit('middleware:preprocessors');
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Request handling
|
|
|
|
*/
|
|
|
|
|
|
|
|
// LoopBack REST transport
|
|
|
|
this.use(this.get('restApiRoot') || '/api', loopback.rest());
|
|
|
|
|
|
|
|
// Allow the app to install custom request handling middleware
|
|
|
|
this.emit('middleware:handlers');
|
|
|
|
|
|
|
|
// Let express routes handle requests that were not handled
|
|
|
|
// by any of the middleware registered above.
|
|
|
|
// This way LoopBack REST and API Explorer take precedence over
|
|
|
|
// express routes.
|
|
|
|
this.use(this.router);
|
|
|
|
|
|
|
|
// The static file server should come after all other routes
|
|
|
|
// Every request that goes through the static middleware hits
|
|
|
|
// the file system to check if a file exists.
|
|
|
|
this.use(loopback.static(path.join(__dirname, 'public')));
|
|
|
|
|
|
|
|
// Requests that get this far won't be handled
|
|
|
|
// by any middleware. Convert them into a 404 error
|
|
|
|
// that will be handled later down the chain.
|
|
|
|
this.use(loopback.urlNotFound());
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Error handling
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Allow the app to install custom error logging middleware
|
|
|
|
this.emit('middleware:error-handlers');
|
|
|
|
|
|
|
|
// The ultimate error handler.
|
|
|
|
this.use(loopback.errorHandler());
|
|
|
|
};
|
2014-01-08 14:20:17 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Listen for connections and update the configured port.
|
|
|
|
*
|
|
|
|
* When there are no parameters or there is only one callback parameter,
|
|
|
|
* the server will listen on `app.get('host')` and `app.get('port')`.
|
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* // listen on host/port configured in app config
|
|
|
|
* app.listen();
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* Otherwise all arguments are forwarded to `http.Server.listen`.
|
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* // listen on the specified port and all hosts, ignore app config
|
|
|
|
* app.listen(80);
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* The function also installs a `listening` callback that calls
|
|
|
|
* `app.set('port')` with the value returned by `server.address().port`.
|
|
|
|
* This way the port param contains always the real port number, even when
|
|
|
|
* listen was called with port number 0.
|
|
|
|
*
|
2014-04-02 22:15:21 +00:00
|
|
|
* @param {Function} cb If specified, the callback is added as a listener
|
2014-01-08 14:20:17 +00:00
|
|
|
* for the server's "listening" event.
|
|
|
|
* @returns {http.Server} A node `http.Server` with this application configured
|
|
|
|
* as the request handler.
|
|
|
|
*/
|
|
|
|
app.listen = function(cb) {
|
|
|
|
var self = this;
|
|
|
|
|
|
|
|
var server = require('http').createServer(this);
|
|
|
|
|
|
|
|
server.on('listening', function() {
|
|
|
|
self.set('port', this.address().port);
|
2014-07-01 12:27:02 +00:00
|
|
|
if (!self.get('url')) {
|
|
|
|
// A better default host would be `0.0.0.0`,
|
|
|
|
// but such URL is not supported by Windows
|
|
|
|
var host = self.get('host') || '127.0.0.1';
|
|
|
|
var url = 'http://' + host + ':' + self.get('port') + '/';
|
|
|
|
self.set('url', url);
|
|
|
|
}
|
2014-01-08 14:20:17 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
var useAppConfig =
|
|
|
|
arguments.length == 0 ||
|
|
|
|
(arguments.length == 1 && typeof arguments[0] == 'function');
|
|
|
|
|
|
|
|
if (useAppConfig) {
|
|
|
|
server.listen(this.get('port'), this.get('host'), cb);
|
|
|
|
} else {
|
|
|
|
server.listen.apply(server, arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
return server;
|
|
|
|
}
|