Matteo Scandolo | 0e171f3 | 2017-09-26 17:21:41 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2017-present Open Networking Foundation |
| 3 | |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | import * as _ from 'lodash'; |
| 18 | import * as pluralize from 'pluralize'; |
| 19 | import {IXosModel} from './model-discoverer.service'; |
| 20 | |
| 21 | export interface IXosModeldefsCache { |
| 22 | cache(modelDef: IXosModel): void; |
| 23 | get(modelName: string): IXosModel; |
| 24 | getApiUrlFromModel(model: IXosModel): string; |
| 25 | serviceNameFromAppName(appName: string): string; |
| 26 | } |
| 27 | |
| 28 | export class XosModeldefsCache implements IXosModeldefsCache { |
| 29 | |
| 30 | private xosModelDefs: IXosModel[] = []; |
| 31 | |
| 32 | public cache(modelDef: IXosModel): void { |
| 33 | if (!_.find(this.xosModelDefs, m => m.name === modelDef.name)) { |
| 34 | this.xosModelDefs.push(modelDef); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | public get(modelName: string): IXosModel|null { |
| 39 | return _.find(this.xosModelDefs, m => m.name === modelName); |
| 40 | } |
| 41 | |
| 42 | public serviceNameFromAppName(appName: string): string { |
| 43 | return appName.replace('services.', ''); |
| 44 | } |
| 45 | |
| 46 | public getApiUrlFromModel(model: IXosModel): string { |
| 47 | // FIXME move pluralize from config to a separate service |
| 48 | if (model.app === 'core') { |
| 49 | return `/core/${pluralize(model.name.toLowerCase())}`; |
| 50 | } |
| 51 | else { |
| 52 | const serviceName = this.serviceNameFromAppName(model.app); |
| 53 | return `/${serviceName}/${pluralize(model.name.toLowerCase())}`; |
| 54 | } |
| 55 | } |
| 56 | } |