Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Enterprise Usage Reports): regen service to get Pager #170

Merged
merged 2 commits into from
Oct 26, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 114 additions & 4 deletions enterprise-usage-reports/v1.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* (C) Copyright IBM Corp. 2020.
* (C) Copyright IBM Corp. 2022.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,22 +15,28 @@
*/

/**
* IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-629bbb97-20201207-171303
* IBM OpenAPI SDK Code Generator Version: 3.60.0-13f6e1ba-20221019-164457
*/

/* eslint-disable max-classes-per-file */
/* eslint-disable no-await-in-loop */

import * as extend from 'extend';
import { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http';
import {
Authenticator,
BaseService,
getAuthenticatorFromEnvironment,
getMissingParams,
validateParams,
UserOptions,
getQueryParam,
} from 'ibm-cloud-sdk-core';
import { getSdkHeaders } from '../lib/common';

/**
* Usage reports for IBM Cloud enterprise entities
*
* API Version: 1.0.0-beta.1
*/

class EnterpriseUsageReportsV1 extends BaseService {
Expand Down Expand Up @@ -124,6 +130,22 @@ class EnterpriseUsageReportsV1 extends BaseService {
params?: EnterpriseUsageReportsV1.GetResourceUsageReportParams
): Promise<EnterpriseUsageReportsV1.Response<EnterpriseUsageReportsV1.Reports>> {
const _params = { ...params };
const _requiredParams = [];
const _validParams = [
'enterpriseId',
'accountGroupId',
'accountId',
'children',
'month',
'billingUnitId',
'limit',
'offset',
'headers',
];
const _validationErrors = validateParams(_params, _requiredParams, _validParams);
if (_validationErrors) {
return Promise.reject(_validationErrors);
}

const query = {
'enterprise_id': _params.enterpriseId,
Expand Down Expand Up @@ -181,7 +203,7 @@ namespace EnterpriseUsageReportsV1 {
export type Callback<T> = (error: any, response?: Response<T>) => void;

/** The body of a service request that returns no response data. */
export interface Empty {}
export interface EmptyObject {}

/** A standard JS object, defined to avoid the limitations of `Object` and `object` */
export interface JsonObject {
Expand Down Expand Up @@ -333,6 +355,94 @@ namespace EnterpriseUsageReportsV1 {
/** Details about all the resources that are included in the aggregated charges. */
resources: ResourceUsage[];
}

/*************************
* pager classes
************************/

/**
* GetResourceUsageReportPager can be used to simplify the use of getResourceUsageReport().
*/
export class GetResourceUsageReportPager {
protected _hasNext: boolean;

protected pageContext: any;

protected client: EnterpriseUsageReportsV1;

protected params: EnterpriseUsageReportsV1.GetResourceUsageReportParams;

/**
* Construct a GetResourceUsageReportPager object.
*
* @param {EnterpriseUsageReportsV1} client - The service client instance used to invoke getResourceUsageReport()
* @param {Object} [params] - The parameters to be passed to getResourceUsageReport()
* @constructor
* @returns {GetResourceUsageReportPager}
*/
constructor(
client: EnterpriseUsageReportsV1,
params?: EnterpriseUsageReportsV1.GetResourceUsageReportParams
) {
if (params && params.offset) {
throw new Error(`the params.offset field should not be set`);
}

this._hasNext = true;
this.pageContext = { next: undefined };
this.client = client;
this.params = JSON.parse(JSON.stringify(params || {}));
}

/**
* Returns true if there are potentially more results to be retrieved by invoking getNext().
* @returns {boolean}
*/
public hasNext(): boolean {
return this._hasNext;
}

/**
* Returns the next page of results by invoking getResourceUsageReport().
* @returns {Promise<EnterpriseUsageReportsV1.ResourceUsageReport[]>}
*/
public async getNext(): Promise<EnterpriseUsageReportsV1.ResourceUsageReport[]> {
if (!this.hasNext()) {
throw new Error('No more results available');
}

if (this.pageContext.next) {
this.params.offset = this.pageContext.next;
}
const response = await this.client.getResourceUsageReport(this.params);
const { result } = response;

let next = null;
if (result && result.next) {
if (result.next.href) {
next = getQueryParam(result.next.href, 'offset');
}
}
this.pageContext.next = next;
if (!this.pageContext.next) {
this._hasNext = false;
}
return result.reports;
}

/**
* Returns all results by invoking getResourceUsageReport() repeatedly until all pages of results have been retrieved.
* @returns {Promise<EnterpriseUsageReportsV1.ResourceUsageReport[]>}
*/
public async getAll(): Promise<EnterpriseUsageReportsV1.ResourceUsageReport[]> {
const results: ResourceUsageReport[] = [];
while (this.hasNext()) {
const nextPage = await this.getNext();
results.push(...nextPage);
}
return results;
}
}
}

export = EnterpriseUsageReportsV1;
22 changes: 13 additions & 9 deletions examples/enterprise-usage-reports.v1.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @jest-environment node
*/
/**
* (C) Copyright IBM Corp. 2020.
* (C) Copyright IBM Corp. 2020, 2022.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -56,7 +56,7 @@ describe('EnterpriseUsageReportsV1', () => {

// begin-common

const enterpriseUsageReportsService = EnterpriseUsageReportsV1.newInstance({});
const enterpriseUsageReportsService = EnterpriseUsageReportsV1.newInstance();

// end-common

Expand All @@ -65,13 +65,12 @@ describe('EnterpriseUsageReportsV1', () => {
let billingMonth = config.billingMonth;

test('getResourceUsageReport request example', async () => {

consoleLogMock.mockImplementation(output => {
consoleLogMock.mockImplementation((output) => {
originalLog(output);
});
consoleWarnMock.mockImplementation(output => {
consoleWarnMock.mockImplementation((output) => {
// if an error occurs, display the message and then fail the test
originalWarn(output);
// when the test fails we need to print out the error message and stop execution right after it
expect(true).toBeFalsy();
});

Expand All @@ -81,12 +80,17 @@ describe('EnterpriseUsageReportsV1', () => {
const params = {
enterpriseId: enterpriseId,
month: billingMonth,
limit: 10,
};

const allResults = [];
try {
const res = await enterpriseUsageReportsService.getResourceUsageReport(params);
console.log(JSON.stringify(res.result, null, 2));
const pager = new EnterpriseUsageReportsV1.GetResourceUsageReportPager(enterpriseUsageReportsService, params);
while (pager.hasNext()) {
const nextPage = await pager.getNext();
expect(nextPage).not.toBeNull();
allResults.push(...nextPage);
}
console.log(JSON.stringify(allResults, null, 2));
} catch (err) {
console.warn(err);
}
Expand Down
73 changes: 46 additions & 27 deletions test/integration/enterprise-usage-reports.v1.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-console */
/**
* (C) Copyright IBM Corp. 2020.
* (C) Copyright IBM Corp. 2020, 2022.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,7 +15,7 @@
* limitations under the License.
*/

const { readExternalSources } = require('ibm-cloud-sdk-core');
const { readExternalSources, getQueryParam } = require('ibm-cloud-sdk-core');
const EnterpriseUsageReportsV1 = require('../../dist/enterprise-usage-reports/v1');
const authHelper = require('../resources/auth-helper.js');

Expand All @@ -27,19 +27,19 @@ const configFile = 'enterprise_usage_reports.env';

const describe = authHelper.prepareTests(configFile);

let service;
let accountId;
let accountGroupId;
let enterpriseId;
let billingMonth;

describe('EnterpriseUsageReportsV1_integration', () => {
let enterpriseUsageReportsService;
let accountId;
let accountGroupId;
let enterpriseId;
let billingMonth;

test('Init', async () => {
service = EnterpriseUsageReportsV1.newInstance({});
enterpriseUsageReportsService = EnterpriseUsageReportsV1.newInstance();

const config = readExternalSources(EnterpriseUsageReportsV1.DEFAULT_SERVICE_NAME);

expect(service).not.toBeNull();
expect(enterpriseUsageReportsService).not.toBeNull();
expect(config).not.toBeNull();

accountId = config.accountId;
Expand Down Expand Up @@ -67,7 +67,7 @@ describe('EnterpriseUsageReportsV1_integration', () => {
offset,
};

const res = await service.getResourceUsageReport(params);
const res = await enterpriseUsageReportsService.getResourceUsageReport(params);
expect(res.status).toEqual(200);

const { result } = res;
Expand All @@ -79,7 +79,7 @@ describe('EnterpriseUsageReportsV1_integration', () => {

// Determine the offset to use to get the next page.
if (result.next) {
offset = getOffsetFromURL(result.next.href);
offset = getQueryParam(result.next.href, 'offset');
} else {
offset = null;
}
Expand Down Expand Up @@ -108,7 +108,7 @@ describe('EnterpriseUsageReportsV1_integration', () => {
offset,
};

const res = await service.getResourceUsageReport(params);
const res = await enterpriseUsageReportsService.getResourceUsageReport(params);
expect(res.status).toEqual(200);

const { result } = res;
Expand All @@ -120,7 +120,7 @@ describe('EnterpriseUsageReportsV1_integration', () => {

// Determine the offset to use to get the next page.
if (result.next) {
offset = getOffsetFromURL(result.next.href);
offset = getQueryParam(result.next.href, 'offset');
} else {
offset = null;
}
Expand Down Expand Up @@ -149,7 +149,7 @@ describe('EnterpriseUsageReportsV1_integration', () => {
offset,
};

const res = await service.getResourceUsageReport(params);
const res = await enterpriseUsageReportsService.getResourceUsageReport(params);
expect(res.status).toEqual(200);

const { result } = res;
Expand All @@ -161,7 +161,7 @@ describe('EnterpriseUsageReportsV1_integration', () => {

// Determine the offset to use to get the next page.
if (result.next) {
offset = getOffsetFromURL(result.next.href);
offset = getQueryParam(result.next.href, 'offset');
} else {
offset = null;
}
Expand All @@ -176,15 +176,34 @@ describe('EnterpriseUsageReportsV1_integration', () => {
// console.log(`getResourceUsageReport() response contained ${numReports} total reports`);
expect(numReports).toBeGreaterThan(0);
});
});

function getOffsetFromURL(urlstring) {
let offset = null;
if (urlstring) {
// We use a bogus "baseurl" in case "urlstring" is a relative url.
// This is fine since we're only trying to retrieve the "offset" query parameter.
const url = new URL(urlstring, 'https://fakehost.com');
offset = url.searchParams.get('offset');
}
return offset;
}
test('getResourceUsageReport() via GetResourceUsageReportPager', async () => {
const params = {
accountGroupId,
month: billingMonth,
};

const allResults = [];

// Test getNext().
let pager = new EnterpriseUsageReportsV1.GetResourceUsageReportPager(
enterpriseUsageReportsService,
params
);
while (pager.hasNext()) {
const nextPage = await pager.getNext();
expect(nextPage).not.toBeNull();
allResults.push(...nextPage);
}

// Test getAll().
pager = new EnterpriseUsageReportsV1.GetResourceUsageReportPager(
enterpriseUsageReportsService,
params
);
const allItems = await pager.getAll();
expect(allItems).not.toBeNull();
expect(allItems).toHaveLength(allResults.length);
console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`);
});
});
Loading