-
Notifications
You must be signed in to change notification settings - Fork 121
/
SparqlUpdateBodyParser.ts
47 lines (44 loc) · 1.9 KB
/
SparqlUpdateBodyParser.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
47
import type { Algebra } from 'sparqlalgebrajs';
import { translate } from 'sparqlalgebrajs';
import { getLoggerFor } from '../../logging/LogUtil';
import { APPLICATION_SPARQL_UPDATE } from '../../util/ContentTypes';
import { BadRequestHttpError } from '../../util/errors/BadRequestHttpError';
import { isNativeError } from '../../util/errors/ErrorUtil';
import { UnsupportedMediaTypeHttpError } from '../../util/errors/UnsupportedMediaTypeHttpError';
import { guardedStreamFrom, readableToString } from '../../util/StreamUtil';
import type { BodyParserArgs } from './BodyParser';
import { BodyParser } from './BodyParser';
import type { SparqlUpdatePatch } from './SparqlUpdatePatch';
/**
* {@link BodyParser} that supports `application/sparql-update` content.
* Will convert the incoming update string to algebra in a {@link SparqlUpdatePatch}.
*/
export class SparqlUpdateBodyParser extends BodyParser {
protected readonly logger = getLoggerFor(this);
public async canHandle({ request }: BodyParserArgs): Promise<void> {
const contentType = request.headers['content-type'];
if (contentType !== APPLICATION_SPARQL_UPDATE) {
throw new UnsupportedMediaTypeHttpError('This parser only supports SPARQL UPDATE data.');
}
}
public async handle({ request, metadata }: BodyParserArgs): Promise<SparqlUpdatePatch> {
const sparql = await readableToString(request);
let algebra: Algebra.Operation;
try {
algebra = translate(sparql, { quads: true, baseIRI: metadata.identifier.value });
} catch (error: unknown) {
this.logger.warn('Could not translate SPARQL query to SPARQL algebra', { error });
if (isNativeError(error)) {
throw new BadRequestHttpError(error.message);
}
throw new BadRequestHttpError();
}
// Prevent body from being requested again
return {
algebra,
binary: true,
data: guardedStreamFrom(sparql),
metadata,
};
}
}