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