向远程监视解决方案加速器 Web UI 添加自定义服务

本文介绍如何在远程监视解决方案加速器 Web UI 中添加新服务。 本文介绍:

  • 如何准备本地开发环境。
  • 如何向 Web UI 添加新服务。

本文中的示例服务为网格提供数据,若要了解如何添加网格,请参阅向远程监视解决方案加速器 Web UI 添加自定义网格操作指南。

在 React 应用程序中,服务通常与后端服务交互。 远程监视解决方案加速器中的示例包括与 IoT 中心管理器和配置微服务交互的服务。

先决条件

要完成本操作指南中的步骤,需要在本地开发计算机上安装以下软件:

开始之前

应先完成向远程监视解决方案加速器 Web UI 添加自定义页面操作指南中的步骤,然后再继续操作。

添加服务

若要向 Web UI 添加服务,需要添加定义服务的源文件,然后修改部分现有文件,从而让 Web UI 识别新服务。

添加定义服务的新文件

为了帮助你入门,src/walkthrough/services 文件夹包含定义简单服务的文件:

exampleService.js


import { Observable } from 'rxjs';
import { toExampleItemModel, toExampleItemsModel } from './models';

/** Normally, you'll need to define the endpoint URL.
 * See app.config.js to add a new service URL.
 *
 * For this example, we'll just hardcode sample data to be returned instead
 * of making an actual service call. See the other service files for examples.
 */
//const ENDPOINT = Config.serviceUrls.example;

/** Contains methods for calling the example service */
export class ExampleService {

  /** Returns an example item */
  static getExampleItem(id) {
    return Observable.of(
      { ID: id, Description: "This is an example item." },
    )
      .map(toExampleItemModel);
  }

  /** Returns a list of example items */
  static getExampleItems() {
    return Observable.of(
      {
        items: [
          { ID: "123", Description: "This is item 123." },
          { ID: "188", Description: "This is item ONE-DOUBLE-EIGHT." },
          { ID: "210", Description: "This is item TWO-TEN." },
          { ID: "277", Description: "This is item 277." },
          { ID: "413", Description: "This is item FOUR-THIRTEEN." },
          { ID: "789", Description: "This is item 789." },
        ]
      }
    ).map(toExampleItemsModel);
  }

  /** Mimics a server call by adding a delay */
  static updateExampleItems() {
    return this.getExampleItems().delay(2000);
  }
}

若要详细了解如何实现服务,请参阅 The introduction to Reactive Programming you've been missing(你一直错过的反应式编程简介)。

model/exampleModels.js

import { camelCaseReshape, getItems } from 'utilities';

/**
 * Reshape the server side model to match what the UI wants.
 *
 * Left side is the name on the client side.
 * Right side is the name as it comes from the server (dot notation is supported).
 */
export const toExampleItemModel = (data = {}) => camelCaseReshape(data, {
  'id': 'id',
  'description': 'descr'
});

export const toExampleItemsModel = (response = {}) => getItems(response)
  .map(toExampleItemModel);

exampleService.js 复制到 src/services 文件夹,将 exampleModels.js 复制到 src/services/models 文件夹。

更新 src/services 文件夹中的 index.js 文件以导出新服务:

export * from './exampleService';

更新 src/services/models 文件夹中的 index.js 文件以导出新模型:

export * from './exampleModels';

从存储中设置对服务的调用

为了帮助你入门,src/walkthrough/store/reducers 文件夹包含一个示例化简器:

exampleReducer.js

import 'rxjs';
import { Observable } from 'rxjs';
import moment from 'moment';
import { schema, normalize } from 'normalizr';
import update from 'immutability-helper';
import { createSelector } from 'reselect';
import { ExampleService } from 'walkthrough/services';
import {
  createReducerScenario,
  createEpicScenario,
  errorPendingInitialState,
  pendingReducer,
  errorReducer,
  setPending,
  toActionCreator,
  getPending,
  getError
} from 'store/utilities';

// ========================= Epics - START
const handleError = fromAction => error =>
  Observable.of(redux.actions.registerError(fromAction.type, { error, fromAction }));

export const epics = createEpicScenario({
  /** Loads the example items */
  fetchExamples: {
    type: 'EXAMPLES_FETCH',
    epic: fromAction =>
      ExampleService.getExampleItems()
        .map(toActionCreator(redux.actions.updateExamples, fromAction))
        .catch(handleError(fromAction))
  }
});
// ========================= Epics - END

// ========================= Schemas - START
const itemSchema = new schema.Entity('examples');
const itemListSchema = new schema.Array(itemSchema);
// ========================= Schemas - END

// ========================= Reducers - START
const initialState = { ...errorPendingInitialState, entities: {}, items: [], lastUpdated: '' };

const updateExamplesReducer = (state, { payload, fromAction }) => {
  const { entities: { examples }, result } = normalize(payload, itemListSchema);
  return update(state, {
    entities: { $set: examples },
    items: { $set: result },
    lastUpdated: { $set: moment() },
    ...setPending(fromAction.type, false)
  });
};

/* Action types that cause a pending flag */
const fetchableTypes = [
  epics.actionTypes.fetchExamples
];

export const redux = createReducerScenario({
  updateExamples: { type: 'EXAMPLES_UPDATE', reducer: updateExamplesReducer },
  registerError: { type: 'EXAMPLE_REDUCER_ERROR', reducer: errorReducer },
  isFetching: { multiType: fetchableTypes, reducer: pendingReducer }
});

export const reducer = { examples: redux.getReducer(initialState) };
// ========================= Reducers - END

// ========================= Selectors - START
export const getExamplesReducer = state => state.examples;
export const getEntities = state => getExamplesReducer(state).entities || {};
export const getItems = state => getExamplesReducer(state).items || [];
export const getExamplesLastUpdated = state => getExamplesReducer(state).lastUpdated;
export const getExamplesError = state =>
  getError(getExamplesReducer(state), epics.actionTypes.fetchExamples);
export const getExamplesPendingStatus = state =>
  getPending(getExamplesReducer(state), epics.actionTypes.fetchExamples);
export const getExamples = createSelector(
  getEntities, getItems,
  (entities, items) => items.map(id => entities[id])
);
// ========================= Selectors - END

exampleReducer.js 复制到 src/store/reducers 文件夹。

若要详细了解化简器和 Epics,请参阅 redux-observable

配置中间件

若要配置中间件,请将化简器添加到 src/store 文件夹中的 rootReducer.js 文件:

import { reducer as exampleReducer } from './reducers/exampleReducer';

const rootReducer = combineReducers({
  ...appReducer,
  ...devicesReducer,
  ...rulesReducer,
  ...simulationReducer,
  ...exampleReducer
});

将 epics 添加到 src/store 文件夹中的 rootEpics.js 文件:

import { epics as exampleEpics } from './reducers/exampleReducer';

// Extract the epic function from each property object
const epics = [
  ...appEpics.getEpics(),
  ...devicesEpics.getEpics(),
  ...rulesEpics.getEpics(),
  ...simulationEpics.getEpics(),
  ...exampleEpics.getEpics()
];

后续步骤

本文介绍了可以帮助你在远程监视解决方案加速器 Web UI 中添加或自定义服务的资源。

现在已定义了服务,下一步是向远程监视解决方案加速器 Web UI 添加自定义网格,该网格将显示服务返回的数据。

有关远程监视解决方案加速器的更多概念信息,请参阅 远程监视体系结构