-
Notifications
You must be signed in to change notification settings - Fork 1
/
AxiosSpecialPageEntityRepo.ts
78 lines (70 loc) · 2.49 KB
/
AxiosSpecialPageEntityRepo.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import EntityRepository from '@/common/data-access/EntityRepository';
import TechnicalProblem from '@/common/data-access/error/TechnicalProblem';
import EntityNotFound from '@/common/data-access/error/EntityNotFound';
import FingerprintableEntity from '@/datamodel/FingerprintableEntity';
import EntityInitializerInterface from '@/common/EntityInitializerInterface';
import { AxiosInstance, AxiosResponse, AxiosError } from 'axios';
import { MEDIAWIKI_INDEX_SCRIPT } from '@/common/constants';
import { StatusCodes } from 'http-status-codes';
import AxiosTechnicalProblem from '@/common/data-access/error/AxiosTechnicalProblem';
export default class AxiosSpecialPageEntityRepo implements EntityRepository {
public static readonly SPECIAL_PAGE = 'Special:EntityData';
private axios: AxiosInstance;
private entityInitializer: EntityInitializerInterface;
public constructor(
axios: AxiosInstance,
entityInitializer: EntityInitializerInterface,
) {
this.axios = axios;
this.entityInitializer = entityInitializer;
}
public getFingerprintableEntity( id: string, revision: number ): Promise<FingerprintableEntity> {
return new Promise( ( resolve, reject ) => {
this.getEntity( id, revision )
.then( ( entity ) => {
try {
resolve( this.entityInitializer.newFromSerialization( entity ) );
} catch ( e ) {
reject( new TechnicalProblem( ( e as Error ).message ) );
}
} )
.catch( ( reason ) => {
reject( reason );
} );
} );
}
private getEntity( id: string, revision: number ): Promise<unknown> {
return new Promise( ( resolve, reject ) => {
this.axios.get( MEDIAWIKI_INDEX_SCRIPT, { params: {
title: AxiosSpecialPageEntityRepo.SPECIAL_PAGE,
id,
revision,
} } )
.then( ( response: AxiosResponse ) => {
const data = response.data;
if ( typeof data !== 'object' || !( 'entities' in data ) ) {
reject( new TechnicalProblem( 'result not well formed.' ) );
return;
}
if ( !( id in data.entities ) ) {
reject( new EntityNotFound( 'result does not contain relevant entity.', {
entity: id,
revision,
} ) );
return;
}
resolve( data.entities[ id ] );
} )
.catch( ( error: AxiosError ) => {
if ( error.response && error.response.status === StatusCodes.NOT_FOUND ) {
reject( new EntityNotFound( 'Entity flagged missing in response.', {
entity: id,
revision,
} ) );
return;
}
reject( new AxiosTechnicalProblem( error ) );
} );
} );
}
}