我必须从第三方API提取一些数据。数据格式如下:
,依此类推。我正在使用的模型类如下:
export class Asset {
assetId: string = "";
name: string = "";
children: Array<Asset>;
}
我首先必须获取根资产,然后以深度优先的方式递归获取所有子级。
assetService.ts
import * as request from "request";
import { AuthTokenService } from "./tokenService";
import {constant as CONSTANTS} from "../shared/constants"
import { Asset } from "../models/asset";
import {JsonConvert, ValueCheckingMode} from "json2typescript"
export class AssetService {
private authTokenService: AuthTokenService;
constructor() {
this.authTokenService = new AuthTokenService();
}
public getRootAssetDetails() {
const self = this;
return self.getDataFromAssetManagementService(CONSTANTS.root_asset_url, null).then(function (responseData: any) {
let jsonObj: object = JSON.parse(responseData);
let jsonConvert: JsonConvert = new JsonConvert();
jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL;
let rootAsset = jsonConvert.deserializeObject(jsonObj, Asset);
return rootAsset;
});
}
public async getAssetHierarchy(asset: Asset) {
const self = this;
let filter = "{\"parentId\":\"" + asset.assetId + "\"}";
const response = await self.getDataFromAssetManagementService(CONSTANTS.asset_url, filter);
let jsonObj: object[] = JSON.parse(<string>response);
let jsonConvert: JsonConvert = new JsonConvert();
jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL;
asset.children = jsonConvert.deserializeArray(jsonObj['assets'], Asset);
asset.children.forEach(childAsset => {
self.getAssetHierarchy(childAsset);
});
}
private getDataFromAssetManagementService(url: string, filter: string) {
const self = this;
return new Promise(function (resolve, reject) {
self.authTokenService.getMdspAccessToken().then(function (accessToken) {
var options = {
method: 'GET',
url: url,
qs: {
access_token: accessToken['access_token'],
size: '50'
}
};
if (filter !== null) {
options.qs['filter'] = filter;
}
request(options, function (error: any, response: any, body: {} | PromiseLike < {} > ) {
if (error) reject(error);
else {
resolve(body);
}
});
});
})
}
public async getAssets() {
let rootAsset: Asset = <Asset> await this.getRootAssetDetails();
await this.getAssetHierarchy(rootAsset);
return rootAsset;
}
}
appRoutes.ts
import {Request, Response} from "express";
import { AssetService } from "../services/assetService";
import { ResponseModel, StatusCode } from "../models/response";
export class AssetRoutes {
private assetService: AssetService;
constructor() {
this.assetService = new AssetService();
}
public routes(app): void {
const self = this;
app.route('/v1/asset')
.get((req: Request, res: Response) => {
self.assetService.getAssets().then((data) => {
var responseData : ResponseModel = new ResponseModel();
responseData.Data = data;
responseData.StatusCode = StatusCode.Ok;
responseData.StatusMessage = 'GET request successfulll!!!!';
res.status(200).send(responseData);
});
});
}
}
当我致电http://localhost/v1/assets时,它仅返回初始的根Asset值。我没有从getChildAssets获得结果。
任何帮助将不胜感激!