Create wt-odlux directory
[ccsdk/features.git] / sdnr / wt-odlux / odlux / framework / src / services / restAccessorService.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 * as $ from 'jquery'; 
19 import { Action, IActionHandler } from '../flux/action';
20 import { MiddlewareArg } from '../flux/middleware';
21 import { Dispatch } from '../flux/store';
22
23 import { IApplicationStoreState } from '../store/applicationStore';
24 import { AddErrorInfoAction, ErrorInfo } from '../actions/errorActions';
25 import { PlainObject, AjaxParameter } from 'models/restService';
26
27 export const absoluteUri = /^(https?:\/\/|blob:)/i;
28 export const baseUrl = `${ window.location.origin }${ window.location.pathname }`;
29
30 class RestBaseAction extends Action { }
31
32 export const createRestApiAccessor = <TResult extends PlainObject>(urlOrPath: string, initialValue: TResult) => {
33   const isLocalRequest = !absoluteUri.test(urlOrPath);
34   const uri = isLocalRequest ? `${ baseUrl }/${ urlOrPath }`.replace(/\/{2,}/, '/') : urlOrPath ;
35  
36   class RestRequestAction extends RestBaseAction { constructor(public settings?: AjaxParameter) { super(); } }
37
38   class RestResponseAction extends RestBaseAction { constructor(public result: TResult) { super(); } }
39
40   class RestErrorAction extends RestBaseAction { constructor(public error?: Error | string) { super(); } }
41   
42   type RestAction = RestRequestAction | RestResponseAction | RestErrorAction;
43
44   /** Represents our middleware to handle rest backend requests */
45   const restMiddleware = (api: MiddlewareArg<IApplicationStoreState>) =>
46     (next: Dispatch) => (action: RestAction): RestAction => {
47       
48       // pass all actions through by default
49       next(action);
50       // handle the RestRequestAction
51       if (action instanceof RestRequestAction) {
52         const state = api.getState();
53         const authHeader = isLocalRequest && state && state.framework.authenticationState.user && state.framework.authenticationState.user.token
54           ? { "Authentication": "Bearer " + state.framework.authenticationState.user.token } : { };
55         $.ajax({
56           url: uri,
57           method: (action.settings && action.settings.method) || "GET",
58           headers: { ...authHeader, ...(action.settings && action.settings.headers ? action.settings.headers : { }) },
59         }).then((data: TResult) => {
60            next(new RestResponseAction(data));
61         }).catch((err: any) => {
62           next(new RestErrorAction());
63           next(new AddErrorInfoAction((err instanceof Error) ? { error: err } : { message: err.toString() }));
64         });
65       }
66       // allways return action
67       return action;
68   };
69   
70   /** Represents our action handler to handle our actions */
71   const restActionHandler: IActionHandler<TResult> = (state = initialValue, action) => {
72     if (action instanceof RestRequestAction) {
73       return {
74         ...(state as any),
75         busy: true
76       };
77     } else if (action instanceof RestResponseAction) {
78       return action.result;
79     } else if (action instanceof RestErrorAction) {
80       return initialValue;
81     }
82     return state;
83   };
84
85   return {
86     requestAction: RestRequestAction,
87     actionHandler: restActionHandler,
88     middleware: restMiddleware,
89   };
90 }
91
92
93