-
Notifications
You must be signed in to change notification settings - Fork 40
/
InvenioSearchApi.js
99 lines (90 loc) · 2.81 KB
/
InvenioSearchApi.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* This file is part of React-SearchKit.
* Copyright (C) 2018-2019 CERN.
*
* React-SearchKit is free software; you can redistribute it and/or modify it
* under the terms of the MIT License; see LICENSE file for more details.
*/
import axios from 'axios';
import _get from 'lodash/get';
import _hasIn from 'lodash/hasIn';
import _isEmpty from 'lodash/isEmpty';
import { updateQueryState } from '../../../state/selectors';
import { INITIAL_QUERY_STATE } from '../../../storeConfig';
import { InvenioRequestSerializer } from './InvenioRequestSerializer';
import { InvenioResponseSerializer } from './InvenioResponseSerializer';
export class InvenioSearchApi {
constructor(config) {
this.axiosConfig = _get(config, 'axios', {});
this.validateAxiosConfig();
this.initSerializers(config);
this.initInterceptors(config);
this.initAxios();
this.search = this.search.bind(this);
}
validateAxiosConfig() {
if (!_hasIn(this.axiosConfig, 'url')) {
throw new Error('InvenioSearchApi config: `url` field is required.');
}
}
initInterceptors(config) {
this.requestInterceptor = _get(config, 'interceptors.request', undefined);
this.responseInterceptor = _get(config, 'interceptors.response', undefined);
}
initSerializers(config) {
const requestSerializerCls = _get(
config,
'invenio.requestSerializer',
InvenioRequestSerializer
);
const responseSerializerCls = _get(
config,
'invenio.responseSerializer',
InvenioResponseSerializer
);
this.requestSerializer = new requestSerializerCls();
this.responseSerializer = new responseSerializerCls();
}
initAxios() {
const axiosConfig = {
paramsSerializer: this.requestSerializer.serialize,
...this.axiosConfig,
};
this.http = axios.create(axiosConfig);
this.addInterceptors();
}
addInterceptors() {
if (this.requestInterceptor) {
this.http.interceptors.request.use(
this.requestInterceptor.resolve,
this.requestInterceptor.reject
);
}
if (this.responseInterceptor) {
this.http.interceptors.request.use(
this.responseInterceptor.resolve,
this.responseInterceptor.reject
);
}
}
/**
* Perform the backend request to search and return the serialized list of results for the app state `results`.
* @param {string} stateQuery the `query` state with the user input
*/
async search(stateQuery) {
let response = await this.http.request({
params: stateQuery,
});
response = this.responseSerializer.serialize(response.data);
const newQueryState = updateQueryState(
stateQuery,
response.extras,
INITIAL_QUERY_STATE
);
if (!_isEmpty(newQueryState)) {
response.newQueryState = newQueryState;
}
delete response.extras;
return response;
}
}