2018-03-31 13:55:00 +03:00
|
|
|
const request = require('request-promise-native');
|
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
export default class Resolver {
|
|
|
|
private requesting: Set<string>;
|
|
|
|
|
|
|
|
constructor(iterable?: Iterable<string>) {
|
|
|
|
this.requesting = new Set(iterable);
|
2018-03-31 13:55:00 +03:00
|
|
|
}
|
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
private async resolveUnrequestedOne(value) {
|
|
|
|
if (typeof value !== 'string') {
|
|
|
|
return { resolver: this, object: value };
|
|
|
|
}
|
2018-03-31 13:55:00 +03:00
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
const resolver = new Resolver(this.requesting);
|
2018-03-31 13:55:00 +03:00
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
resolver.requesting.add(value);
|
2018-03-31 13:55:00 +03:00
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
const object = await request({
|
|
|
|
url: value,
|
|
|
|
headers: {
|
|
|
|
Accept: 'application/activity+json, application/ld+json'
|
|
|
|
},
|
|
|
|
json: true
|
|
|
|
});
|
2018-03-31 13:55:00 +03:00
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
if (object === null || (
|
|
|
|
Array.isArray(object['@context']) ?
|
|
|
|
!object['@context'].includes('https://www.w3.org/ns/activitystreams') :
|
|
|
|
object['@context'] !== 'https://www.w3.org/ns/activitystreams'
|
|
|
|
)) {
|
|
|
|
throw new Error();
|
|
|
|
}
|
2018-03-31 13:55:00 +03:00
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
return { resolver, object };
|
2018-03-31 13:55:00 +03:00
|
|
|
}
|
|
|
|
|
2018-04-03 14:39:27 +03:00
|
|
|
public async resolveCollection(value) {
|
2018-04-01 15:56:11 +03:00
|
|
|
const resolved = typeof value === 'string' ?
|
|
|
|
await this.resolveUnrequestedOne(value) :
|
2018-04-03 10:32:54 +03:00
|
|
|
{ resolver: this, object: value };
|
2018-03-31 13:55:00 +03:00
|
|
|
|
2018-04-03 10:32:54 +03:00
|
|
|
switch (resolved.object.type) {
|
2018-04-01 15:56:11 +03:00
|
|
|
case 'Collection':
|
2018-04-03 10:32:54 +03:00
|
|
|
resolved.object = resolved.object.items;
|
|
|
|
break;
|
2018-03-31 13:55:00 +03:00
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
case 'OrderedCollection':
|
2018-04-03 10:32:54 +03:00
|
|
|
resolved.object = resolved.object.orderedItems;
|
|
|
|
break;
|
2018-03-31 13:55:00 +03:00
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
default:
|
2018-04-03 10:32:54 +03:00
|
|
|
if (!Array.isArray(value)) {
|
|
|
|
resolved.object = [resolved.object];
|
|
|
|
}
|
|
|
|
break;
|
2018-04-01 15:56:11 +03:00
|
|
|
}
|
2018-04-03 10:32:54 +03:00
|
|
|
|
|
|
|
return resolved;
|
2018-03-31 13:55:00 +03:00
|
|
|
}
|
|
|
|
|
2018-04-01 15:24:25 +03:00
|
|
|
public resolveOne(value) {
|
2018-03-31 13:55:00 +03:00
|
|
|
if (this.requesting.has(value)) {
|
2018-04-01 15:24:25 +03:00
|
|
|
throw new Error();
|
2018-03-31 13:55:00 +03:00
|
|
|
}
|
|
|
|
|
2018-04-01 15:56:11 +03:00
|
|
|
return this.resolveUnrequestedOne(value);
|
2018-03-31 13:55:00 +03:00
|
|
|
}
|
|
|
|
}
|