Skip to content
This repository has been archived by the owner on Aug 4, 2023. It is now read-only.

IoC Support. #340

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions browser/swagger-tools-standalone-min.js

Large diffs are not rendered by default.

4,683 changes: 2,355 additions & 2,328 deletions browser/swagger-tools-standalone.js

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions docs/Middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@ object keys are the handler name _({ControllerName}_{HandlerFunctionName}) and t
found. When `true`, we will ignore the missing handler and send the request downstream.
* **options.useStubs:** `[boolean]` Whether or not stub handlers should be used for routes with no defined controller
or the controller could not be found.
* **options.injected:** `[object]` If the require() result of loading a module is a function itself, it is assumed
this function is a generator/construction helper and the options.injected property will be passed. This allows for
application level IoC to facilitate unit testing.

**Returns**

Expand Down
6 changes: 5 additions & 1 deletion docs/QuickStart.md
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,11 @@ var serverPort = 3000;
// swaggerRouter configuration
var options = {
controllers: './controllers',
useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode)
useStubs: process.env.NODE_ENV === 'development' ? true : false, // Conditionally turn on stubs (mock mode)
injected: {
// Optional - Set any values here that get passed
// to controllers that return a function from require().
}
};

// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
Expand Down
6 changes: 5 additions & 1 deletion examples/2.0/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ var serverPort = 3000;
// swaggerRouter configuration
var options = {
controllers: './controllers',
useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode)
useStubs: process.env.NODE_ENV === 'development' ? true : false, // Conditionally turn on stubs (mock mode)
injected: {
// Optional - Set any values here that get passed
// to controllers that return a function from require().
}
};

// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
Expand Down
12 changes: 10 additions & 2 deletions middleware/swagger-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ var getHandlerName = function (req) {

return handlerName;
};
var handlerCacheFromDir = function (dirOrDirs) {
var handlerCacheFromDir = function (dirOrDirs, injected) {
var handlerCache = {};
var jsFileRegex = /\.(coffee|js)$/;
var dirs = [];
Expand All @@ -79,6 +79,14 @@ var handlerCacheFromDir = function (dirOrDirs) {
if (file.match(jsFileRegex)) {
controller = require(path.resolve(path.join(dir, controllerName)));

// If controller require()'s as a function, then execute it.
// and pass in our options.dependencies
if (_.isFunction(controller)) {
debug(' %s - resolved as function, executing to obtain instance.:',
path.resolve(path.join(dir, file)));
controller = controller(injected);
}

debug(' %s%s:',
path.resolve(path.join(dir, file)),
(_.isPlainObject(controller) ? '' : ' (not an object, skipped)'));
Expand Down Expand Up @@ -374,7 +382,7 @@ exports = module.exports = function (options) {
handlerCache = options.controllers;
} else {
// Create the handler cache from the modules in the controllers directory
handlerCache = handlerCacheFromDir(options.controllers);
handlerCache = handlerCacheFromDir(options.controllers, options.injected);
}

return function swaggerRouter (req, res, next) {
Expand Down
8 changes: 5 additions & 3 deletions test/1.2/test-middleware-swagger-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ var petJson = _.cloneDeep(require('../../samples/1.2/pet.json'));
var storeJson = _.cloneDeep(require('../../samples/1.2/store.json'));
var userJson = _.cloneDeep(require('../../samples/1.2/user.json'));
var optionsWithControllersDir = {
controllers: path.join(__dirname, '..', 'controllers')
controllers: path.join(__dirname, '..', 'controllers'),
injected: { value: true }
};
var samplePet = {
category: {
Expand Down Expand Up @@ -109,7 +110,8 @@ describe('Swagger Router Middleware v1.2', function () {
controllers: [
path.join(__dirname, '..', 'controllers'),
path.join(__dirname, '..', 'controllers2')
]
],
injected: { value: true }
}
}, function (app) {
request(app)
Expand All @@ -120,7 +122,7 @@ describe('Swagger Router Middleware v1.2', function () {
});

it('should do routing when options.controllers is a valid controller map', function (done) {
var controller = require('../controllers/Users');
var controller = require('../controllers/Users')({ value: true });

helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: {
Expand Down
4 changes: 2 additions & 2 deletions test/1.2/test-middleware-swagger-ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ describe('Swagger UI Middleware v1.2', function () {
}, {});

async.map(Object.keys(pathMap), function (path, callback) {
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {}, function (app) {
helpers.createServer([rlJson, [petJson, storeJson, userJson]], { injected: { value: true }}, function (app) {
request(app)
.get(path)
.expect(200)
Expand Down Expand Up @@ -97,7 +97,7 @@ describe('Swagger UI Middleware v1.2', function () {
});

it('should serve Swagger UI at /docs by default', function (done) {
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {}, function (app) {
helpers.createServer([rlJson, [petJson, storeJson, userJson]], { injected: { value: true }}, function (app) {
request(app)
.get('/docs/') // Trailing slash to avoid a 303
.expect(200)
Expand Down
10 changes: 6 additions & 4 deletions test/2.0/test-middleware-swagger-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ var helpers = require('../helpers');

var petStoreJson = _.cloneDeep(require('../../samples/2.0/petstore.json'));
var optionsWithControllersDir = {
controllers: path.join(__dirname, '..', 'controllers')
controllers: path.join(__dirname, '..', 'controllers'),
injected: { value: true }
};
var samplePet = {
category: {
Expand Down Expand Up @@ -108,7 +109,8 @@ describe('Swagger Router Middleware v2.0', function () {
controllers: [
path.join(__dirname, '..', 'controllers'),
path.join(__dirname, '..', 'controllers2')
]
],
injected: { value: true }
}
}, function (app) {
request(app)
Expand All @@ -120,7 +122,7 @@ describe('Swagger Router Middleware v2.0', function () {

it('should do routing when options.controllers is a valid controller map', function (done) {
var cPetStoreJson = _.cloneDeep(petStoreJson);
var controller = require('../controllers/Users');
var controller = require('../controllers/Users')({ value: true });

// Use Users controller
cPetStoreJson.paths['/pets/{id}'].get['x-swagger-router-controller'] = 'Users';
Expand All @@ -142,7 +144,7 @@ describe('Swagger Router Middleware v2.0', function () {

it('should do routing when only operationId is given', function (done) {
var cPetStoreJson = _.cloneDeep(petStoreJson);
var controller = require('../controllers/Users');
var controller = require('../controllers/Users')({ value: true });

// Use Users controller
delete cPetStoreJson.paths['/pets/{id}'].get['x-swagger-router-controller'];
Expand Down
23 changes: 21 additions & 2 deletions test/controllers/Users.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,27 @@

'use strict';

var response = module.exports.response = 'controllers/Users swagger-router OK';
var response = 'controllers/Users swagger-router OK';

module.exports.getById = module.exports._getById = function getById (req, res) {
var getById = function getById (req, res) {
res.end(response);
};

module.exports = function generator(injected) {
if (!injected) {
throw new Error('injected should be set.');
} else if (!injected.value) {
throw new Error('injected should have a sub-value set');
}

return {
getById,
_getById: getById,
getInjected(req, res) {
res.end(injected.value);
},
response
};
};

module.exports.response = response;