-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpreprocessor.js
48 lines (45 loc) · 1.64 KB
/
preprocessor.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
/**
* Middleware for preprocessing documents to contain the expected format.
* @author cubap
*/
// expressjs middleware for preprocessing documents. Use the jsonld library to make sure the "@id" and "@type" fields are included on the JSON object in the request.body
import LD from 'jsonld'
const rerumPropertiesWasher = async (req, res, next) => {
if (typeof req.body !== 'object' || req.body === null) {
// if the request body is not an object, return an error
return res.status(400).json({ error: 'Invalid request body' })
}
// check if the JSON object has an "@id" field
if (req.body.hasOwnProperty('@id')) {
next()
return
}
let missingProps = ['@id']
// Without @context, we've no idea how to proceed
if (!req.body.hasOwnProperty('@context')) {
return res.status(400).json({ error: `Missing required properties: @context, ${missingProps.join(', ')}` })
}
// check if the JSON object has an "@type" field
if (!req.body.hasOwnProperty('@type')) {
missingProps.push('@type')
req.body['@type'] = ''
}
// look for aliases in the @context
return LD.expand(req.body)
.then(expanse => {
const expanded = expanse[0]
for (const prop of missingProps) {
if (expanded.hasOwnProperty(prop)) {
req.body[prop] = expanded[prop]
}
}
if(Array.isArray(req.body['@type'])) {
req.body['@type'] = expanded['@type'].pop()
}
next()
})
.catch(err => {
next(err)
})
}
export default rerumPropertiesWasher