-
Notifications
You must be signed in to change notification settings - Fork 4
/
operation.js
49 lines (38 loc) · 1.17 KB
/
operation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
var attachBodyParser = require('./lib/attach-body-parser')
var trim = require('lodash/trim')
function middleware (attachBodyParser, req, res, next) {
var method = req.method.toLowerCase()
var target = req.hydra ? req.hydra.object : null
// hydra object attached to request?
if (!target) {
return next()
}
attachBodyParser(req, res).then(function () {
var property = trim(req.absoluteUrl().slice(target.iri().toString().length), '/')
if (property) {
if (!(property in target)) {
return next()
}
target = target[property]
}
// method supported?
if (!(method in target)) {
return res.status(405).end() // Method Not Allowed
}
return Promise.resolve().then(function () {
return target[method](req.simple)
}).then(function (result) {
if (!result) {
return res.status(204).end() // No Content
}
if (result.iri().interfaceName === 'NamedNode') {
res.setHeader('Content-Location', result.iri().toString())
}
return res.sendSimple(result)
})
}).catch(next)
}
function init () {
return middleware.bind(null, attachBodyParser())
}
module.exports = init