1/** 2 * Copyright (c) 2024-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { BaseState } from './BaseState'; 17import { BaseIntent } from './BaseIntent'; 18import { BaseModel } from './BaseModel'; 19import Logger from '../utils/Logger'; 20 21const TAG = 'BaseViewModel'; 22 23/** 24 * results of enforcement 25 */ 26export enum ProcessResult { 27 FAIL = 0, 28 SUCCESS = 1 29} 30 31export abstract class BaseViewModel<M extends BaseModel, S extends BaseState> { 32 private _model?: M; 33 private _viewState?: S; 34 35 public getViewState(): S { 36 if (this._viewState === null || this._viewState === undefined) { 37 this._viewState = this.initViewState(); 38 } 39 return this._viewState; 40 } 41 42 public async processIntent(intents: BaseIntent): Promise<ProcessResult> { 43 Logger.info(TAG, 'start processIntent: ' + intents.getIntentTag()); 44 if (this._model === null || this._model === undefined) { 45 this._model = this.initModel(); 46 } 47 if (this._viewState === null || this._viewState === undefined) { 48 this._viewState = this.initViewState(); 49 } 50 if (this._model !== null && this._viewState !== null) { 51 try { 52 return await this.processIntentWithModel(intents, this._model, this._viewState); 53 } catch (err) { 54 Logger.error(TAG, 'error when process intents.' + intents.getIntentTag()); 55 } 56 } 57 return ProcessResult.FAIL; 58 } 59 60 protected abstract initModel(): M; 61 62 protected abstract initViewState(): S; 63 64 protected abstract processIntentWithModel(intents: BaseIntent, model: M, viewState: S): Promise<ProcessResult>; 65}