-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonld.js
62 lines (55 loc) · 1.88 KB
/
jsonld.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
50
51
52
53
54
55
56
57
58
59
60
61
62
import { SpanStatusCode } from '@opentelemetry/api'
import Parser from '@rdfjs/parser-jsonld'
import FsDocumentLoader from '@rdfjs/parser-jsonld/FsDocumentLoader.js'
import Serializer from '@rdfjs/serializer-jsonld'
import sinkToDuplex from '@rdfjs/sink-to-duplex'
import { combine, jsonStringify } from 'barnard59-base'
import tracer from './lib/tracer.js'
/**
* @this {import('barnard59-core').Context}
* @param {Object} [options]
* @param {string | Record<string, string>} [options.localContext]
*/
function parse({ localContext } = {}) {
/**
* @type {import('@rdfjs/parser-jsonld').DocumentLoader | undefined}
*/
let documentLoader
if (localContext) {
if (typeof localContext === 'string') {
documentLoader = new FsDocumentLoader(JSON.parse(localContext))
} else {
documentLoader = new FsDocumentLoader(localContext)
}
}
return tracer.startActiveSpan('jsonld:parse', span => {
const stream = sinkToDuplex(new Parser({ factory: this.env, documentLoader }), { objectMode: true })
stream.on('error', /** @type {any} */ err => {
span.recordException(err)
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message })
span.end()
})
stream.on('finish', () => span.end())
return stream
})
}
/**
* @this {import('barnard59-core').Context}
*/
const parseObject = function () {
return tracer.startActiveSpan('jsonld:parse.object', span => {
const stream = combine([jsonStringify(), parse.call(this)], { objectMode: true })
stream.on('error', (/** @type Error */ err) => {
span.recordException(err)
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message })
span.end()
})
stream.on('finish', () => span.end())
return stream
})
}
parse.object = parseObject
function serialize() {
return sinkToDuplex(new Serializer(), { objectMode: true })
}
export { parse, parseObject, serialize }