Перейти к основному содержимому

ObservableServices

Сервисы, которые мы используем в веб-клиенте унаследованы от базового Observable сервиса BaseService.

export interface IBaseModel {
error?: string | null;
loading?: boolean | number;
}
export declare class BaseService<M extends IBaseModel> extends Observable {
protected _model: M;
protected _subscriptions: IDisposable[];
private _depsWatcher;
private _hDependenciesNames;
private _hDepsModels;
private _initializedInstance;
constructor(initialModel?: M);
protected _createInitialModel(): M;
protected _addDependency(depId: string, dep: BaseService<any>, doImmediateNotify?: boolean): void;
protected _addDependencies(deps: {
[id: string]: BaseService<any>;
}, doImmediateNotify?: boolean): void;
protected _removeDependency(depId: string, doImmediateNotify?: boolean): void;
protected _onDepsUpdated(newModels: IDepsModels, prevModels: IDepsModels): boolean;
protected _onDepsReadyAndUpdated(newModels: any, prevModels: any): void;
protected _getDependencyModel<T>(depId: string): T;
protected _updateWithLoading(): void;
protected _updateWithError(error: string): void;
protected _updateWithData(partialModel: Partial<M>): void;
protected _smartUpdate(newModel: M, prevModel: M): M;
protected _isModelChanged(nextModel: M, currentModel: M): boolean;
protected _isUpdatesFrozen: boolean;
protected _freezeUpdates(fn: () => any): any;
private _notifyUpdate;
protected _setModel(model: M): void;
protected _updateModel(partialModel: Partial<M>): void;
/**
* Returns if service is ready and has data
*
* @returns {boolean}
*/
isReady(): boolean;
/**
* Wait until service in state 'ready' (which means, no error and no loading)
* return Promise<MODEL>
*
* if model signal error, it rejects resulting promise
*
* @returns {Promise<MODEL>}
*/
whenReady(): Promise<M>;
subscribeAndNotify(event: string, listener: (model: M) => void): IDisposable;
subscribeUpdates(listener: (model: M) => void): IDisposable;
subscribeUpdatesAndNotify(listener: (model: M) => void): IDisposable;
getModel(): M;
protected _releaseChild(name: string): void;
protected _dispose(): void;
static dependency(target: BaseService<any>, key: string, descriptor?: TypedPropertyDescriptor<any>): any;

Его особенность состоит в реализации подхода классического Observable:
Есть поле хранящее информацию об ошибке инициализации (error), статус окончания процесса инициализации (loading), методы работы с моделью (полная установка и частичная, геттер), методы подписки на изменения модели сервиса и уведомления подписчиков (весь блок subscribes…).
Вы можете у класса-наследника такого сервиса вызвать метод subscribeUpdatesAndNotify передав этому методу аргументом функцию-колбек одного аргумента (этот аргумент есть будущая модель соответствующего сервиса) и тогда при любом изменении модели сервиса вы попадете в функцию-колбек, выполняющую ваше целевое дейтсвие.
Таким образом, мы можем использовать там, где это обусловлено, один и тот же экземаляр такого сервиса и уже меняя его модель - триггерить реакцию компонентов-подписчиков на это изменение (ререндер, перезапрос данных и т.д.).
Часть таких сервисов и моделей мы выносим в набор специальных пакетов на экспорт для использования внутри проекта luxmsbi-web-resources.

Пакет для импорта bi-internal/core
AppConfig

interface IAppConfig {
loading: boolean;
error: string;
requestUrls: any;
projectTitle: string;
locale: string;
language: 'en' | 'ru';
region: string;
features: string[];
plugins: string[];
entryPoint: any;
dataset: any;
map: any;
themes?: any;
}
export declare class AppConfig extends BaseService<IAppConfig> {
constructor();
protected _createInitialModel(): any;
private _loadSettingsJs;
hasFeature(featureName: string): boolean;
/**
* Replaces parts of URL according to settings
*
* @param url URL to proceed
* @returns {string} resulting URL
*/
fixRequestUrl(url: string): string;
static getInstance: () => AppConfig;
static getModel(): IAppConfig;
static fixRequestUrl(url: string): string;
static hasFeature(featureName: string): boolean;
static getProjectTitle(): string;
static getLocale(): string;
static getLanguage(): 'en' | 'ru';
static getPlugins(): string[];
}

Представляет собой сервис для получения объекта настроек веб-клиента из файла settings/settings.js на сервере.
Пример: AppConfig.getInstance().getModel() - отдаст модель настроек в соответствии с интерфейсом IAppConfig.

AuthenticationService

interface IAuthCheckData2 {
sessionId: string;
user: IRawUser;
authType?: string;
}
interface IAuthCheckData3 {
access_level: string;
id: string;
name: string;
authType?: string;
config: IRawUserConfig;
}
export interface IAuthentication extends IBaseModel {
error: string | null;
loading: boolean;
authenticating: boolean;
authenticated: boolean;
userId?: number;
access_level?: string;
username?: string;
name?: string;
userConfig?: {
[key: string]: string;
};
isNeed2FACode?: boolean;
isBlocked?: boolean;
errorKey?: string;
errorMessage?: string;
}
export declare class AuthenticationService extends BaseService<IAuthentication> {
private constructor();
private _init;
protected _setModel(m: IAuthentication): void;
isAuthenticated(): boolean;
private _check;
check(): Promise<IAuthCheckData2 | IAuthCheckData3>;
private _notifyLoggedOut;
signIn(username: string, password: string): Promise<IAuthentication>;
signOut(): Promise<any>;
resendCode(): Promise<any>;
signInWithCode(code: string): Promise<any>;
static readonly NOT_AUTHENTICATED: string;
static readonly FORCE_LOGIN_KEY = "loginme";
static getInstance: () => AuthenticationService;
static getModel(): IAuthentication;
static subscribeUpdatesAndNotify(listener: (model: IAuthentication) => void): IDisposable;
static subscribeUpdates(listener: (model: IAuthentication) => void): IDisposable;
static unsubscribe(listener: (...args: any[]) => any): boolean;
static signOut(): Promise<any>;
static signInWithCode(code: string): Promise<any>;
static signIn(username: string, password: string): Promise<IAuthentication>;
static resendCode(): Promise<any>;
}

Сервис и его интерфейсы нужны для авторизации пользователя и получения информации о нем
AuthenticationService.getInstance().getModel() - отдаст модель пользователя, который авторизовался.

AuthenticationService.signIn(‘adm’, ‘luxmsbi’) - авторизует пользователя c указанным логином и паролем в системе.

repo - объект, хранящий три типа наборов интерфейсов

Adm

 export declare type IRawUserConfig = {
[key: string]: string;
};
export interface IRawUser {
id: number;
name: string;
email: string;
username: string;
config?: IRawUserConfig;
}
export declare class UsersRepository extends BaseRepository<IRawUser> {
constructor();
protected _filter(e: IRawUser): boolean;
}
export interface IRawDataset {
id: number;
guid: string;
parent_guid: string | null;
version: string;
schema_name: string;
server_id: number;
owner_user_id: number | null;
head_dataset_id: number | null;
title: string;
description: string;
src_image_type: string;
images: {
source: string;
'15x15': string;
'130x130': string;
};
srt: number;
config: any;
serial: string;
sqlite_serial: null;
sqlite_snapshot_id: null;
logged_since: null;
sync_cfg: any;
is_archive: 0 | 1;
is_visible: 0 | 1;
is_db_ready: 0 | 1;
period_spans: any;
ui_cfg: {
[key: string]: string;
};
depends_on: [];
postprocess_sql: null;
}
export declare class DatasetsRepository extends BaseRepository<IRawDataset> {
constructor();
}
export interface IRawTopic {
id: number;
parent_id: number | null;
tree_level: number;
title: string;
srt: number;
dataset_id: number | null;
src_image_type: null;
images: {};
config: any;
}
export declare class TopicsRepository extends BaseRepository<IRawTopic> {
constructor();
}
export interface IRawTopicDatasetMap {
id: number;
topic_id: number;
dataset_id: number;
config: any;
srt: number;
}
export declare class TopicDatasetMapsRepository extends BaseRepository<IRawTopicDatasetMap> {
constructor();
}
export interface IRawUserGroup {
id: number;
title: string;
config?: IRawUserConfig;
}
export declare class UserGroupsRepository extends BaseRepository<IRawUserGroup> {
constructor();
}
export interface IRawDataSource {
id: number;
ident: string;
title?: string;
url?: string;
login?: string;
pass?: string;
config?: any;
}
export declare class DataSourceRepository extends BaseRepository<IRawDataSource> {
constructor();
}

Определяет интерфейсы для работы административного сервиса платформы

ds

 export interface IRawConfig {
id: number;
cfg_key: string;
cfg_val: string;
cfg_type: string | null;
updated: string;
created: string;
}
export declare class ConfigsRepository extends BaseRepository<IRawConfig> {
constructor(schemaName: string);
}
export interface IRawUnit {
id: number;
parent_id: number | null;
scale: number;
scale_op: '*';
value_prefix: string | null;
value_suffix: string | null;
title: string;
tiny_title: string;
axis_title: string;
config: any;
updated: string;
created: string;
}
export declare class UnitsRepository extends BaseRepository<IRawUnit> {
constructor(schemaName: string);
}
export interface IRawMetric {
id: number;
parent_id: number | null;
tree_level: number;
tree_path: string | null;
title: string;
unit_id: number | null;
is_text_val: 0 | 1;
is_norm: 0 | 1;
is_calc: 0 | 1;
formula: null;
is_hidden: 0 | 1;
srt: number;
tags: string[];
src_id: string | null;
alt_id: string | null;
config: any;
updated: string;
created: string;
}
export declare class MetricsRepository extends BaseRepository<IRawMetric> {
constructor(schemaName: string);
}
export interface IRawMetricSet {
id: number;
title: string;
can_be_pie: number;
config: any;
updated: string;
created: string;
}
export declare class MetricSetsRepository extends BaseRepository<IRawMetricSet> {
constructor(schemaName: string);
}
export interface IRawLocation {
id: number;
parent_id: number | null;
tree_level: number;
tree_path: string | null;
title: string;
latitude: number;
longitude: number;
is_hidden: 0 | 1;
srt: number;
tags: string[];
src_id: null;
alt_id: string | null;
config: any;
updated: string;
created: string;
}
export declare class LocationsRepository extends BaseRepository<IRawLocation> {
constructor(schemaName: string);
}
export interface IRawPeriod {
id: number;
parent_id: number | null;
tree_level: number;
period_type: number;
qty: number;
start_time: string;
title: string;
tags: string[];
src_id: null;
alt_id: string | null;
tree_path: string | null;
config: any;
updated: string;
created: string;
}
export declare class PeriodsRepository extends BaseRepository<IRawPeriod> {
constructor(schemaName: string);
protected _processTextResponse: (response: string) => string;
protected _sort(es: IRawPeriod[]): void;
}
export interface IRawDashboardTopic {
id: number;
parent_id: number | null;
icon_id: number;
title: string;
tree_level: number;
srt: number;
config: any;
updated: string;
created: string;
}
export declare class DashboardTopicsRepository extends BaseRepository<IRawDashboardTopic> {
constructor(schemaName: string);
}
export interface IRawDashboard {
id: number;
topic_id: number;
icon_id: number;
title: string;
srt: number;
config: any;
updated: string;
created: string;
}
export declare class DashboardsRepository extends BaseRepository<IRawDashboard> {
constructor(schemaName: string);
}
export interface IRawDashlet {
id: number;
parent_id: number | null;
dashboard_id: number;
view_class: string;
title: string;
description: string | null;
layout: '' | 'V' | 'H';
length: '';
idx: number;
config: any;
updated: string;
created: string;
}
export declare class DashletsRepository extends BaseRepository<IRawDashlet> {
constructor(schemaName: string);
protected _sort(es: IRawDashlet[]): void;
}
export interface IRawAttachment {
id: number;
config: any;
title: string;
attachment_type: 'vcp-lookup-table' | 'metric-values' | 'external-metric';
during?: string;
m_where?: string;
l_where?: string;
p_where?: string;
pt_where?: string;
u_where?: string;
data_source?: string;
norm_id?: number;
payload?: string;
alt_payload?: string;
}
export declare class AttachmentsRepository extends BaseRepository<IRawAttachment> {
constructor(schemaName: string);
}
export interface IRawResource {
id: number;
alt_id: string;
content_type: string;
content_length: number;
created: string;
updated: string;
config: any;
}
export declare class ResourcesRepository extends BaseRepository<IRawResource> {
constructor(schemaName: string);
}
export interface IRawTextData {
id: number;
metric_id: number;
loc_id: number;
period_id: number;
val: string;
}
export declare class TextDataRepository extends BaseRepository<IRawTextData> {
constructor(schemaName: string);
protected _processTextResponse: (response: string) => string;
}

описывает интерфейсы основных энтити датасета

koob

 export interface IRawCube {
id: string;
source_ident: string;
name: string;
title: string;
sql_query: string;
config: any;
}
export declare class CubesRepository extends BaseRepository<IRawCube> {
constructor();
}
export interface IRawDimension {
id: string;
source_ident: string;
cube_name: string;
name: string;
type: 'STRING' | 'NUMBER' | 'PERIOD' | 'SUM' | 'AGGFN';
title: string;
sql_query: string;
config: any;
}
export declare class DimensionsRepository extends BaseRepository<IRawDimension> {
source_ident?: string;
cube_name?: string;
constructor(source_ident?: string, cube_name?: string);
}

Описывает интерфейсы и классы для работы с koob (энтити OLAP кубов)

srv

Объект, описывающий в декларативном стиле основные сервисы тех же разделов adm, koob, ds. Каждый из них наследник сервиса BaseEntitiesService, который наследуется от BaseService и предоставляет методы получения объектов разного рода энтити платформы (датасеты, источники данных, дименшны, межи, юниты (ед.изм.) и т.д.).

adm

 export declare class UsersService extends BaseEntitiesService<IRawUser> {
protected _repo: UsersRepository;
static readonly MODEL: IBaseEntities<IRawUser>;
protected constructor();
static getInstance: () => UsersService;
}
export declare class DatasetsService extends BaseEntitiesService<IRawDataset> {
protected _repo: DatasetsRepository;
static readonly MODEL: IBaseEntities<IRawDataset>;
protected constructor();
static getInstance: () => DatasetsService;
}
export declare class TopicsService extends BaseEntitiesService<IRawTopic> {
protected _repo: TopicsRepository;
static readonly MODEL: IBaseEntities<IRawTopic>;
protected constructor();
static getInstance: () => TopicsService;
}
export declare class TopicDatasetMapsService extends BaseEntitiesService<IRawTopicDatasetMap> {
protected _repo: TopicDatasetMapsRepository;
static readonly MODEL: IBaseEntities<IRawTopicDatasetMap>;
protected constructor();
static getInstance: () => TopicDatasetMapsService;
}
export declare class UserGroupsService extends BaseEntitiesService<IRawUserGroup> {
protected _repo: UserGroupsRepository;
static readonly MODEL: IBaseEntities<IRawUserGroup>;
protected constructor();
static getInstance: () => UserGroupsService;
}
export declare class DataSourcesService extends BaseEntitiesService<IRawDataSource> {
protected _repo: DataSourceRepository;
static readonly MODEL: IBaseEntities<IRawDataSource>;
protected constructor();
static getInstance: () => DataSourcesService;
}

ds

 export declare class ConfigsService extends BaseEntitiesService<IRawConfig> {
protected _repo: ConfigsRepository;
static readonly MODEL: IBaseEntities<IRawConfig>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => ConfigsService;
}
export declare class UnitsService extends BaseEntitiesService<IRawUnit> {
protected _repo: UnitsRepository;
static readonly MODEL: IBaseEntities<IRawUnit>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => UnitsService;
}
export declare class MetricsService extends BaseEntitiesService<IRawMetric> {
protected _repo: MetricsRepository;
static readonly MODEL: IBaseEntities<IRawMetric>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => MetricsService;
}
export declare class MetricSetsService extends BaseEntitiesService<IRawMetricSet> {
protected _repo: MetricSetsRepository;
static readonly MODEL: IBaseEntities<IRawMetricSet>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => MetricSetsService;
}
export declare class LocationsService extends BaseEntitiesService<IRawLocation> {
protected _repo: LocationsRepository;
static readonly MODEL: IBaseEntities<IRawLocation>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => LocationsService;
}
export declare class PeriodsService extends BaseEntitiesService<IRawPeriod> {
protected _repo: PeriodsRepository;
static readonly MODEL: IBaseEntities<IRawPeriod>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => PeriodsService;
}
export declare class DashboardTopicsService extends BaseEntitiesService<IRawDashboardTopic> {
protected _repo: DashboardTopicsRepository;
static readonly MODEL: IBaseEntities<IRawDashboardTopic>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => DashboardTopicsService;
}
export declare class DashboardsService extends BaseEntitiesService<IRawDashboard> {
protected _repo: DashboardsRepository;
static readonly MODEL: IBaseEntities<IRawDashboard>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => DashboardsService;
}
export declare class DashletsService extends BaseEntitiesService<IRawDashlet> {
protected _repo: DashletsRepository;
static readonly MODEL: IBaseEntities<IRawDashlet>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => DashletsService;
}
export declare class ResourcesService extends BaseEntitiesService<IRawResource> {
protected _schemaName: string;
protected _repo: ResourcesRepository;
private _resources;
static readonly MODEL: IBaseEntities<IRawResource>;
static readonly RECYCLE_BIN: string;
protected constructor(schemaName: string);
updateContentType(id: number, content_type: string): Promise<IRawResource>;
updateAltId(id: number, alt_id: string): Promise<IRawResource>;
private _uploadFile;
updateContent(id: number, file: any): Promise<boolean\>;
createContent(file: any): Promise<IRawResource>;
protected _isEntitiesEquals(newEntities: IRawResource[], prevEntities: IRawResource[]): boolean;
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => ResourcesService;
}
export declare class TextDataService extends BaseEntitiesService<IRawTextData> {
protected _repo: TextDataRepository;
static readonly MODEL: IBaseEntities<IRawTextData>;
protected constructor(schemaName: string);
protected _dispose(): void;
private static _cache;
static createInstance: (id: number | string) => TextDataService;
}

koob

 export declare class CubesService extends BaseEntitiesService<IRawCube> {
static readonly MODEL: IBaseEntities<IRawCube>;
protected constructor();
static getInstance: () => CubesService;
}
export declare class DimensionsService extends BaseEntitiesService<IRawDimension> {
private source_ident?;
private cube_name?;
static readonly MODEL: IBaseEntities<IRawDimension>;
protected constructor(source_ident?: string, cube_name?: string);
protected _dispose(): void;
private static _cache;
static createInstance: (source_ident: string, cube_name: string) => DimensionsService;
}