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