Skip to content

Commit

Permalink
fix: make operarions middleware proper express handler
Browse files Browse the repository at this point in the history
  • Loading branch information
tpluscode committed Nov 30, 2020
1 parent 95f617e commit ff22a44
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 22 deletions.
46 changes: 25 additions & 21 deletions lib/middleware/operation.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion test/operation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down

0 comments on commit ff22a44

Please sign in to comment.