2 * ============LICENSE_START========================================================================
3 * ONAP : ccsdk feature sdnr wt odlux
4 * =================================================================================================
5 * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6 * =================================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8 * in compliance with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software distributed under the License
13 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14 * or implied. See the License for the specific language governing permissions and limitations under
16 * ============LICENSE_END==========================================================================
18 import { Action, IActionHandler } from '../flux/action';
19 import { MiddlewareArg } from '../flux/middleware';
20 import { Dispatch } from '../flux/store';
22 import { IApplicationStoreState } from '../store/applicationStore';
23 import { AddErrorInfoAction, ErrorInfo } from '../actions/errorActions';
25 const baseUrl = `${ window.location.origin }${ window.location.pathname }`;
27 export class ApiAction<TResult, TSuccessAction extends Action & { result: TResult }> extends Action {
28 constructor(public endpoint: string, public successAction: { new(result: TResult): TSuccessAction }, public authenticate: boolean = false) {
33 export const apiMiddleware = (store: MiddlewareArg<IApplicationStoreState>) => (next: Dispatch) => <A extends Action>(action: A) => {
35 // So the middleware doesn't get applied to every single action
36 if (action instanceof ApiAction) {
37 const user = store && store.getState().framework.authenticationState.user;
38 const token = user && user.token || null;
39 let config = { headers: {} };
41 if (action.authenticate) {
47 // 'Authorization': `Bearer ${ token }`
48 authorization: "Basic YWRtaW46YWRtaW4="
52 return next(new AddErrorInfoAction({ message: 'Please login to continue.' }));
56 fetch(baseUrl + action.endpoint.replace(/\/{2,}/, '/'), config)
58 response.json().then(data => ({ data, response }))
61 next(new action.successAction(result.data));
63 .catch((error: any) => {
64 next(new AddErrorInfoAction((error instanceof Error) ? { error: error } : { message: error.toString() }));
68 // let all actions pass
72 export default apiMiddleware;