Create wt-odlux directory
[ccsdk/features.git] / sdnr / wt-odlux / odlux / framework / src / middleware / api.ts
1 /**
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
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
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
15  * the License.
16  * ============LICENSE_END==========================================================================
17  */
18 import { Action, IActionHandler } from '../flux/action';
19 import { MiddlewareArg } from '../flux/middleware';
20 import { Dispatch } from '../flux/store';
21
22 import { IApplicationStoreState } from '../store/applicationStore';
23 import { AddErrorInfoAction, ErrorInfo } from '../actions/errorActions';
24
25 const baseUrl = `${ window.location.origin }${ window.location.pathname }`;
26
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) {
29     super();
30   }
31 }
32
33 export const apiMiddleware = (store: MiddlewareArg<IApplicationStoreState>) => (next: Dispatch) => <A extends Action>(action: A) => {
34
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: {} };
40
41     if (action.authenticate) {
42       if (token) {
43         config = {
44           ...config,
45           headers: {
46             ...config.headers,
47             // 'Authorization': `Bearer ${ token }`
48             authorization: "Basic YWRtaW46YWRtaW4="
49           }
50         }
51       } else {
52         return next(new AddErrorInfoAction({ message: 'Please login to continue.' }));
53       }
54     }
55
56     fetch(baseUrl + action.endpoint.replace(/\/{2,}/, '/'), config)
57       .then(response =>
58         response.json().then(data => ({ data, response }))
59       )
60       .then(result => {
61         next(new action.successAction(result.data));
62       })
63       .catch((error: any) => {
64         next(new AddErrorInfoAction((error instanceof Error) ? { error: error } : { message: error.toString() }));
65       });
66   }
67
68   // let all actions pass
69   return next(action);
70 }
71
72 export default apiMiddleware;