forked from HydraCG/Heracles.ts
/
BodyResourceBoundIriTemplateExpansionStrategy.ts
32 lines (29 loc) · 1.47 KB
/
BodyResourceBoundIriTemplateExpansionStrategy.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
import { IOperation } from "./DataModel/IOperation";
import { IResource } from "./DataModel/IResource";
import { ITemplatedOperation } from "./DataModel/ITemplatedOperation";
import MappingsBuilder from "./DataModel/MappingsBuilder";
import { IIriTemplateExpansionStrategy } from "./IIriTemplateExpansionStrategy";
/**
* Provides a simple implementation of the {@link IIriTemplateExpansionStrategy} interface where an input resource
* is used to fill the possible {@link IIriTemplate} with values.
*/
export default class BodyResourceBoundIriTemplateExpansionStrategy implements IIriTemplateExpansionStrategy {
/** @inheritDoc */
public createRequest(operation: IOperation, body?: IResource, auxResource?: any): IOperation {
const templatedOperation = operation as ITemplatedOperation;
if (typeof templatedOperation.expandTarget === "function") {
return templatedOperation.expandTarget(builder =>
this.withResourceVariables(builder, body || {}, auxResource || {})
);
}
return operation;
}
private withResourceVariables(builder: MappingsBuilder, body: object, auxResource: object): void {
const variableMappings = builder.variableMappings;
for (const variableName of Object.keys(variableMappings)) {
const property = variableMappings[variableName];
const literal = typeof body[property] !== "undefined" ? body[property].toString() : auxResource[property] || null;
builder.withVariable(variableName).havingValueOf(literal);
}
}
}