diff --git a/lib/middleware/operation.js b/lib/middleware/operation.js index 36d086f..ab73aab 100644 --- a/lib/middleware/operation.js +++ b/lib/middleware/operation.js @@ -54,31 +54,29 @@ function mapOperations ({ api, res, method }) { }) } -function findOperation (operationMiddleware) { - return async function (req, res, next) { - const method = req.method === 'HEAD' ? 'GET' : req.method +function findOperations (req, res, next) { + const method = req.method === 'HEAD' ? 'GET' : req.method - let operations = mapOperations({ api: req.hydra.api, res, method }) - .filter(({ operation }) => operation) - - if (operationMiddleware) { - operations = operationMiddleware(operations, { req, res }) - } + req.hydra.operations = mapOperations({ api: req.hydra.api, res, method }) + .filter(({ operation }) => operation) - if (!operations.length) { - return next() - } - - if (operations.length > 1) { - error('Multiple operations found') - return next(new Error('Ambiguous operation')) - } + return next() +} - const [{ resource, operation }] = operations - req.hydra.resource = resource - req.hydra.operation = operation +function prepareOperation (req, res, next) { + if (!req.hydra.operations.length) { return next() } + + if (req.hydra.operations.length > 1) { + error('Multiple operations found') + return next(new Error('Ambiguous operation')) + } + + const [{ resource, operation }] = req.hydra.operations + req.hydra.resource = resource + req.hydra.operation = operation + return next() } async function invokeOperation (req, res, next) { @@ -117,7 +115,13 @@ async function invokeOperation (req, res, next) { function factory (middleware = {}) { const router = Router() - router.use(findOperation(middleware.operations)) + router.use(findOperations) + + if (middleware.operations) { + router.use(middleware.operations) + } + + router.use(prepareOperation) if (middleware.resource) { router.use(middleware.resource) diff --git a/test/operation.test.js b/test/operation.test.js index c645ddc..bba670b 100644 --- a/test/operation.test.js +++ b/test/operation.test.js @@ -94,7 +94,7 @@ describe('middleware/operation', () => { term: RDF.namedNode('/') }))) const hooks = { - operations: sinon.stub().callsFake(operations => operations) + operations: sinon.stub().callsFake((req, res, next) => next()) } app.use(middleware(hooks))