-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
46 lines (38 loc) · 1.19 KB
/
index.ts
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
import path from 'path'
import type express from 'express'
import absoluteUrl from 'absolute-url'
import type { DataFactory, NamedNode } from '@rdfjs/types'
import isAbsoluteUrl from 'is-absolute-url'
import { Environment } from '@rdfjs/environment/Environment'
import D from '@rdfjs/environment/DataFactory.js'
import E from '@rdfjs/environment'
type Env = Environment<DataFactory>
declare module 'express-serve-static-core' {
export interface Request {
rdf: Env
}
}
export function attach(req: express.Request, factory: Env = new E([D])): void {
if (!req.rdf) {
absoluteUrl.attach(req)
const baseIri = new URL(req.absoluteUrl())
req.rdf = {
...factory,
namedNode<Iri extends string = string>(value: Iri): NamedNode<Iri> {
if (isAbsoluteUrl(value)) {
return factory.namedNode(value)
}
const uri = value.startsWith('/')
? new URL(path.join(req.baseUrl, value), baseIri)
: new URL(value, baseIri)
return factory.namedNode(uri.toString() as unknown as Iri)
},
}
}
}
export default function (factory?: Env): express.RequestHandler {
return (req, res, next) => {
attach(req, factory)
next()
}
}