diff --git a/.secrets.baseline b/.secrets.baseline index bafd908..e92c055 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "package-lock.json|go.sum|^.secrets.baseline$", "lines": null }, - "generated_at": "2025-10-31T17:17:55Z", + "generated_at": "2026-05-07T07:39:50Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -109,12 +109,30 @@ "verified_result": null } ], + "examples/platform-notifications.v1.test.js": [ + { + "hashed_secret": "5febf2fb64d0707173c6ff00a670175ea946da23", + "is_secret": false, + "is_verified": false, + "line_number": 398, + "type": "Hex High Entropy String", + "verified_result": null + }, + { + "hashed_secret": "ca15d23a2ccdee96d9e8e0ea5041e091d352266d", + "is_secret": false, + "is_verified": false, + "line_number": 452, + "type": "Base64 High Entropy String", + "verified_result": null + } + ], "iam-identity/v1.ts": [ { "hashed_secret": "0a49d517da94f14c36ac92806c1d15cf95fbca67", "is_secret": false, "is_verified": false, - "line_number": 1031, + "line_number": 1036, "type": "Secret Keyword", "verified_result": null }, @@ -122,7 +140,7 @@ "hashed_secret": "aa4ad361672f4c98fd64bf0db80127dd79be59d0", "is_secret": false, "is_verified": false, - "line_number": 1109, + "line_number": 1115, "type": "Secret Keyword", "verified_result": null }, @@ -130,7 +148,7 @@ "hashed_secret": "835e124f126ae02c1c18b3c992a28dde441f5e04", "is_secret": false, "is_verified": false, - "line_number": 3057, + "line_number": 3080, "type": "Secret Keyword", "verified_result": null }, @@ -138,7 +156,7 @@ "hashed_secret": "e058a1c493ad749bd67d368340e9056ed1c2f3ed", "is_secret": false, "is_verified": false, - "line_number": 7687, + "line_number": 8010, "type": "Secret Keyword", "verified_result": null } @@ -158,7 +176,7 @@ "hashed_secret": "a2190c299b60e882d9fb33736d5e6ab6ffe42708", "is_secret": false, "is_verified": false, - "line_number": 1656, + "line_number": 1662, "type": "Secret Keyword", "verified_result": null }, @@ -166,7 +184,7 @@ "hashed_secret": "cf4d2385b84329a52ca542285b93d9c4618420df", "is_secret": false, "is_verified": false, - "line_number": 2387, + "line_number": 2393, "type": "Secret Keyword", "verified_result": null }, @@ -174,7 +192,7 @@ "hashed_secret": "469f62fa9e1c6afe62e8808180668934ee548e8f", "is_secret": false, "is_verified": false, - "line_number": 2484, + "line_number": 2490, "type": "Secret Keyword", "verified_result": null } @@ -272,7 +290,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 1400, + "line_number": 1405, "type": "Secret Keyword", "verified_result": null }, @@ -280,11 +298,37 @@ "hashed_secret": "469f62fa9e1c6afe62e8808180668934ee548e8f", "is_secret": false, "is_verified": false, - "line_number": 7467, + "line_number": 7478, "type": "Secret Keyword", "verified_result": null } ], + "test/unit/platform-notifications.v1.test.js": [ + { + "hashed_secret": "61bd9cf7208f6ac60767238bddf6275d8b5e0470", + "is_secret": false, + "is_verified": false, + "line_number": 1107, + "type": "Hex High Entropy String", + "verified_result": null + }, + { + "hashed_secret": "ca15d23a2ccdee96d9e8e0ea5041e091d352266d", + "is_secret": false, + "is_verified": false, + "line_number": 1211, + "type": "Base64 High Entropy String", + "verified_result": null + }, + { + "hashed_secret": "5febf2fb64d0707173c6ff00a670175ea946da23", + "is_secret": false, + "is_verified": false, + "line_number": 1291, + "type": "Hex High Entropy String", + "verified_result": null + } + ], "test/unit/resource-controller.v2.test.js": [ { "hashed_secret": "0f97a4e707b7424540793cb2078919ee6770e07f", diff --git a/README.md b/README.md index 1020990..1f38ee2 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ Service Name | Import Path [IBM Cloud Shell](https://cloud.ibm.com/apidocs/cloudshell?code=node) | @ibm-cloud/platform-services/ibm-cloud-shell/v1 [Open Service Broker](https://cloud.ibm.com/apidocs/resource-controller/ibm-cloud-osb-api?code=node) | @ibm-cloud/platform-services/open-service-broker/v1 [Partner Management APIs](https://cloud.ibm.com/apidocs/partner-apis/partner?code=node) | @ibm-cloud/platform-services/partner-management/v1 +[Platform Notifications](https://cloud.ibm.com/apidocs/platform-notifications?code=node) | @ibm-cloud/platform-services/platform-notifications/v1 [Resource Controller](https://cloud.ibm.com/apidocs/resource-controller/resource-controller?code=node) | @ibm-cloud/platform-services/resource-controller/v2 [Resource Manager](https://cloud.ibm.com/apidocs/resource-controller/resource-manager?code=node) | @ibm-cloud/platform-services/resource-manager/v2 [Usage Metering](https://cloud.ibm.com/apidocs/usage-metering?code=node) | @ibm-cloud/platform-services/usage-metering/v4 diff --git a/examples/platform-notifications.v1.test.js b/examples/platform-notifications.v1.test.js new file mode 100644 index 0000000..2ac5eb2 --- /dev/null +++ b/examples/platform-notifications.v1.test.js @@ -0,0 +1,472 @@ +/** + * @jest-environment node + */ +/** + * (C) Copyright IBM Corp. 2026. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-disable no-console */ +/* eslint-disable no-await-in-loop */ + +const PlatformNotificationsV1 = require('../dist/platform-notifications/v1'); +// eslint-disable-next-line node/no-unpublished-require +const authHelper = require('../test/resources/auth-helper.js'); +// You can use the readExternalSources method to access additional configuration values +const { readExternalSources } = require('ibm-cloud-sdk-core'); + +// +// This file provides an example of how to use the Platform Notifications service. +// +// The following configuration properties are assumed to be defined: +// PLATFORM_NOTIFICATIONS_URL= +// PLATFORM_NOTIFICATIONS_AUTH_TYPE=iam +// PLATFORM_NOTIFICATIONS_APIKEY= +// PLATFORM_NOTIFICATIONS_AUTH_URL= +// +// These configuration properties can be exported as environment variables, or stored +// in a configuration file and then: +// export IBM_CREDENTIALS_FILE= +// +const configFile = 'platform_notifications_v1.env'; + +const describe = authHelper.prepareTests(configFile); + +// Save original console.log +const originalLog = console.log; +const originalWarn = console.warn; + +// Mocks for console.log and console.warn +const consoleLogMock = jest.spyOn(console, 'log'); +const consoleWarnMock = jest.spyOn(console, 'warn'); + +describe('PlatformNotificationsV1', () => { + // Service instance + let platformNotificationsService; + + let accountId; + let destinationId; + let iamId; + + beforeAll(() => { + const config = readExternalSources(PlatformNotificationsV1.DEFAULT_SERVICE_NAME); + + platformNotificationsService = PlatformNotificationsV1.newInstance({ + serviceUrl: config.serviceUrl, + }); + accountId = config.accountId; + destinationId = config.destinationId; + iamId = config.iamId; + platformNotificationsService.enableRetries(); + }); + + test('Initialize service', async () => { + expect(platformNotificationsService).not.toBeNull(); + }); + + test('listDistributionListDestinations request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('listDistributionListDestinations() result:'); + // begin-list_distribution_list_destinations + + const params = { + accountId, + }; + + let res; + try { + res = await platformNotificationsService.listDistributionListDestinations(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-list_distribution_list_destinations + }); + + test('createDistributionListDestination request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('createDistributionListDestination() result:'); + // begin-create_distribution_list_destination + + // Request models needed by this operation. + + // AddDestinationPrototypeEventNotificationDestinationPrototype + const addDestinationPrototypeModel = { + destination_id: destinationId, + destination_type: 'event_notifications', + }; + + const params = { + accountId, + addDestinationPrototype: addDestinationPrototypeModel, + }; + + let res; + try { + res = await platformNotificationsService.createDistributionListDestination(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-create_distribution_list_destination + }); + + test('getDistributionListDestination request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('getDistributionListDestination() result:'); + // begin-get_distribution_list_destination + + const params = { + accountId, + destinationId, + }; + + let res; + try { + res = await platformNotificationsService.getDistributionListDestination(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-get_distribution_list_destination + }); + + test('testDistributionListDestination request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('testDistributionListDestination() result:'); + // begin-test_distribution_list_destination + + // Request models needed by this operation. + + // TestDestinationRequestBodyPrototypeTestEventNotificationDestinationRequestBodyPrototype + const testDestinationRequestBodyPrototypeModel = { + destination_type: 'event_notifications', + notification_type: 'incident', + }; + + const params = { + accountId, + destinationId, + testDestinationRequestBodyPrototype: testDestinationRequestBodyPrototypeModel, + }; + + let res; + try { + res = await platformNotificationsService.testDistributionListDestination(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-test_distribution_list_destination + }); + + test('createPreferences request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('createPreferences() result:'); + // begin-create_preferences + + // Request models needed by this operation. + + // PreferenceValueWithUpdates + const preferenceValueWithUpdatesModel = { + channels: ['email'], + updates: true, + }; + + // PreferenceValueWithoutUpdates + const preferenceValueWithoutUpdatesModel = { + channels: ['email'], + }; + + const params = { + iamId, + incidentSeverity1: preferenceValueWithUpdatesModel, + orderingReview: preferenceValueWithoutUpdatesModel, + accountId, + }; + + let res; + try { + res = await platformNotificationsService.createPreferences(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-create_preferences + }); + + test('getPreferences request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('getPreferences() result:'); + // begin-get_preferences + + const params = { + iamId, + accountId, + }; + + let res; + try { + res = await platformNotificationsService.getPreferences(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-get_preferences + }); + + test('replaceNotificationPreferences request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('replaceNotificationPreferences() result:'); + // begin-replace_notification_preferences + + // Request models needed by this operation. + + // PreferenceValueWithUpdates + const preferenceValueWithUpdatesModel = { + channels: ['email'], + updates: true, + }; + + // PreferenceValueWithoutUpdates + const preferenceValueWithoutUpdatesModel = { + channels: ['email'], + }; + + const params = { + iamId, + incidentSeverity1: preferenceValueWithUpdatesModel, + orderingReview: preferenceValueWithoutUpdatesModel, + accountId, + }; + + let res; + try { + res = await platformNotificationsService.replaceNotificationPreferences(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-replace_notification_preferences + }); + + test('listNotifications request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('listNotifications() result:'); + // begin-list_notifications + + const params = { + accountId, + limit: 50, + }; + + const allResults = []; + try { + const pager = new PlatformNotificationsV1.NotificationsPager( + platformNotificationsService, + 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); + } + + // end-list_notifications + }); + + test('getAcknowledgement request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('getAcknowledgement() result:'); + // begin-get_acknowledgement + + const params = { + accountId, + }; + + let res; + try { + res = await platformNotificationsService.getAcknowledgement(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-get_acknowledgement + }); + + test('replaceNotificationAcknowledgement request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('replaceNotificationAcknowledgement() result:'); + // begin-replace_notification_acknowledgement + + const params = { + lastAcknowledgedId: '1772804159452', + accountId, + }; + + let res; + try { + res = await platformNotificationsService.replaceNotificationAcknowledgement(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-replace_notification_acknowledgement + }); + + test('deleteDistributionListDestination request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + // begin-delete_distribution_list_destination + + const params = { + accountId, + destinationId, + }; + + try { + await platformNotificationsService.deleteDistributionListDestination(params); + } catch (err) { + console.warn(err); + } + + // end-delete_distribution_list_destination + }); + + test('deleteNotificationPreferences request example', async () => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + }); + consoleWarnMock.mockImplementation((output) => { + // if an error occurs, display the message and then fail the test + originalWarn(output); + expect(true).toBeFalsy(); + }); + + // begin-delete_notification_preferences + + const params = { + iamId, + accountId, + }; + + try { + await platformNotificationsService.deleteNotificationPreferences(params); + } catch (err) { + console.warn(err); + } + + // end-delete_notification_preferences + }); +}); diff --git a/platform-notifications/v1.ts b/platform-notifications/v1.ts new file mode 100644 index 0000000..9a2c0b4 --- /dev/null +++ b/platform-notifications/v1.ts @@ -0,0 +1,1699 @@ +/** + * (C) Copyright IBM Corp. 2026. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * IBM OpenAPI SDK Code Generator Version: 3.108.0-56772134-20251111-102802 + */ + +/* eslint-disable max-classes-per-file */ +/* eslint-disable no-await-in-loop */ + +import * as extend from 'extend'; +import { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'; +import { + AbortSignal, + Authenticator, + BaseService, + UserOptions, + getAuthenticatorFromEnvironment, + validateParams, +} from 'ibm-cloud-sdk-core'; +import { getSdkHeaders } from '../lib/common'; + +/** + * **This API is currently in beta and subject to change.** + * + * API for managing notification distribution lists for IBM Cloud accounts. + * + * API Version: 1.0.0 + */ + +class PlatformNotificationsV1 extends BaseService { + static DEFAULT_SERVICE_URL: string = 'https://notifications.cloud.ibm.com/api'; + + static DEFAULT_SERVICE_NAME: string = 'platform_notifications'; + + /************************* + * Factory method + ************************/ + + /** + * Constructs an instance of PlatformNotificationsV1 with passed in options and external configuration. + * + * @param {UserOptions} [options] - The parameters to send to the service. + * @param {string} [options.serviceName] - The name of the service to configure + * @param {Authenticator} [options.authenticator] - The Authenticator object used to authenticate requests to the service + * @param {string} [options.serviceUrl] - The base URL for the service + * @returns {PlatformNotificationsV1} + */ + + public static newInstance(options: UserOptions): PlatformNotificationsV1 { + options = options || {}; + + if (!options.serviceName) { + options.serviceName = this.DEFAULT_SERVICE_NAME; + } + if (!options.authenticator) { + options.authenticator = getAuthenticatorFromEnvironment(options.serviceName); + } + const service = new PlatformNotificationsV1(options); + service.configureService(options.serviceName); + if (options.serviceUrl) { + service.setServiceUrl(options.serviceUrl); + } + return service; + } + + /** + * Construct a PlatformNotificationsV1 object. + * + * @param {Object} options - Options for the service. + * @param {string} [options.serviceUrl] - The base URL for the service + * @param {OutgoingHttpHeaders} [options.headers] - Default headers that shall be included with every request to the service. + * @param {Authenticator} options.authenticator - The Authenticator object used to authenticate requests to the service + * @constructor + * @returns {PlatformNotificationsV1} + */ + constructor(options: UserOptions) { + options = options || {}; + + super(options); + if (options.serviceUrl) { + this.setServiceUrl(options.serviceUrl); + } else { + this.setServiceUrl(PlatformNotificationsV1.DEFAULT_SERVICE_URL); + } + } + + /************************* + * distributionLists + ************************/ + + /** + * Get all destination entries. + * + * Retrieve all destinations in the distribution list for the specified account. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.accountId - The IBM Cloud account ID. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public listDistributionListDestinations( + params: PlatformNotificationsV1.ListDistributionListDestinationsParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['accountId']; + const _validParams = ['accountId', 'signal', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const path = { + 'account_id': _params.accountId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'listDistributionListDestinations' + ); + + const parameters = { + options: { + url: '/v1/distribution_lists/{account_id}/destinations', + method: 'GET', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + + /** + * Add a destination entry. + * + * Add a destination entry to the distribution list. A maximum of 10 destination entries per destination type. In + * terms of enterprise accounts, you can provide an Event Notifications destination that is from a different account + * than the distribution list account, provided these two accounts are from the same enterprise and the user has + * permission to manage the Event Notifications destinations on both accounts. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.accountId - The IBM Cloud account ID. + * @param {AddDestinationPrototype} params.addDestinationPrototype - + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public createDistributionListDestination( + params: PlatformNotificationsV1.CreateDistributionListDestinationParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['accountId', 'addDestinationPrototype']; + const _validParams = ['accountId', 'addDestinationPrototype', 'signal', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const body = _params.addDestinationPrototype; + const path = { + 'account_id': _params.accountId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'createDistributionListDestination' + ); + + const parameters = { + options: { + url: '/v1/distribution_lists/{account_id}/destinations', + method: 'POST', + body, + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + + /** + * Get a destination entry. + * + * Retrieve a specific destination from the distribution list of the account. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.accountId - The IBM Cloud account ID. + * @param {string} params.destinationId - The ID of the destination. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public getDistributionListDestination( + params: PlatformNotificationsV1.GetDistributionListDestinationParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['accountId', 'destinationId']; + const _validParams = ['accountId', 'destinationId', 'signal', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const path = { + 'account_id': _params.accountId, + 'destination_id': _params.destinationId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'getDistributionListDestination' + ); + + const parameters = { + options: { + url: '/v1/distribution_lists/{account_id}/destinations/{destination_id}', + method: 'GET', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + + /** + * Delete destination entry. + * + * Remove a destination entry. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.accountId - The IBM Cloud account ID. + * @param {string} params.destinationId - The ID of the destination. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public deleteDistributionListDestination( + params: PlatformNotificationsV1.DeleteDistributionListDestinationParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['accountId', 'destinationId']; + const _validParams = ['accountId', 'destinationId', 'signal', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const path = { + 'account_id': _params.accountId, + 'destination_id': _params.destinationId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'deleteDistributionListDestination' + ); + + const parameters = { + options: { + url: '/v1/distribution_lists/{account_id}/destinations/{destination_id}', + method: 'DELETE', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend(true, sdkHeaders, this.baseOptions.headers, {}, _params.headers), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + + /** + * Test destination entry. + * + * Send a test notification to a destination in the distribution list. This allows you to verify that the destination + * is properly configured and can receive notifications. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.accountId - The IBM Cloud account ID. + * @param {string} params.destinationId - The ID of the destination. + * @param {TestDestinationRequestBodyPrototype} params.testDestinationRequestBodyPrototype - + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public testDistributionListDestination( + params: PlatformNotificationsV1.TestDistributionListDestinationParams + ): Promise< + PlatformNotificationsV1.Response + > { + const _params = { ...params }; + const _requiredParams = ['accountId', 'destinationId', 'testDestinationRequestBodyPrototype']; + const _validParams = [ + 'accountId', + 'destinationId', + 'testDestinationRequestBodyPrototype', + 'signal', + 'headers', + ]; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const body = _params.testDestinationRequestBodyPrototype; + const path = { + 'account_id': _params.accountId, + 'destination_id': _params.destinationId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'testDistributionListDestination' + ); + + const parameters = { + options: { + url: '/v1/distribution_lists/{account_id}/destinations/{destination_id}/test', + method: 'POST', + body, + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + /************************* + * userPreferences + ************************/ + + /** + * Create communication preferences. + * + * Create communication preferences for the specified account. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.iamId - The IAM ID of the user. Must match the IAM ID in the bearer token. + * @param {PreferenceValueWithUpdates} [params.incidentSeverity1] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.incidentSeverity2] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.incidentSeverity3] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.incidentSeverity4] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.maintenanceHigh] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.maintenanceMedium] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.maintenanceLow] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithoutUpdates} [params.announcementsMajor] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.announcementsMinor] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.securityNormal] - Preference settings for notification types that do + * not support updates. + * @param {PreferenceValueWithoutUpdates} [params.accountNormal] - Preference settings for notification types that do + * not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsageOrder] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsageInvoices] - Preference settings for notification + * types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsagePayments] - Preference settings for notification + * types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsageSubscriptionsAndPromoCodes] - Preference settings for + * notification types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsageSpendingAlerts] - Preference settings for + * notification types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.resourceactivityNormal] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.orderingReview] - Preference settings for notification types that do + * not support updates. + * @param {PreferenceValueWithoutUpdates} [params.orderingApproved] - Preference settings for notification types that + * do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.orderingApprovedVsi] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.orderingApprovedServer] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.provisioningReloadComplete] - Preference settings for notification + * types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.provisioningCompleteVsi] - Preference settings for notification + * types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.provisioningCompleteServer] - Preference settings for notification + * types that do not support updates. + * @param {string} [params.accountId] - The IBM Cloud account ID. If not provided, the account ID from the bearer + * token will be used. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public createPreferences( + params: PlatformNotificationsV1.CreatePreferencesParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['iamId']; + const _validParams = [ + 'iamId', + 'incidentSeverity1', + 'incidentSeverity2', + 'incidentSeverity3', + 'incidentSeverity4', + 'maintenanceHigh', + 'maintenanceMedium', + 'maintenanceLow', + 'announcementsMajor', + 'announcementsMinor', + 'securityNormal', + 'accountNormal', + 'billingAndUsageOrder', + 'billingAndUsageInvoices', + 'billingAndUsagePayments', + 'billingAndUsageSubscriptionsAndPromoCodes', + 'billingAndUsageSpendingAlerts', + 'resourceactivityNormal', + 'orderingReview', + 'orderingApproved', + 'orderingApprovedVsi', + 'orderingApprovedServer', + 'provisioningReloadComplete', + 'provisioningCompleteVsi', + 'provisioningCompleteServer', + 'accountId', + 'signal', + 'headers', + ]; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const body = { + 'incident_severity1': _params.incidentSeverity1, + 'incident_severity2': _params.incidentSeverity2, + 'incident_severity3': _params.incidentSeverity3, + 'incident_severity4': _params.incidentSeverity4, + 'maintenance_high': _params.maintenanceHigh, + 'maintenance_medium': _params.maintenanceMedium, + 'maintenance_low': _params.maintenanceLow, + 'announcements_major': _params.announcementsMajor, + 'announcements_minor': _params.announcementsMinor, + 'security_normal': _params.securityNormal, + 'account_normal': _params.accountNormal, + 'billing_and_usage_order': _params.billingAndUsageOrder, + 'billing_and_usage_invoices': _params.billingAndUsageInvoices, + 'billing_and_usage_payments': _params.billingAndUsagePayments, + 'billing_and_usage_subscriptions_and_promo_codes': + _params.billingAndUsageSubscriptionsAndPromoCodes, + 'billing_and_usage_spending_alerts': _params.billingAndUsageSpendingAlerts, + 'resourceactivity_normal': _params.resourceactivityNormal, + 'ordering_review': _params.orderingReview, + 'ordering_approved': _params.orderingApproved, + 'ordering_approved_vsi': _params.orderingApprovedVsi, + 'ordering_approved_server': _params.orderingApprovedServer, + 'provisioning_reload_complete': _params.provisioningReloadComplete, + 'provisioning_complete_vsi': _params.provisioningCompleteVsi, + 'provisioning_complete_server': _params.provisioningCompleteServer, + }; + + const query = { + 'account_id': _params.accountId, + }; + + const path = { + 'iam_id': _params.iamId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'createPreferences' + ); + + const parameters = { + options: { + url: '/v1/notifications/{iam_id}/preferences', + method: 'POST', + body, + qs: query, + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + + /** + * Get all communication preferences for a user in an account. + * + * Retrieve all communication preferences of a user in an account. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.iamId - The IAM ID of the user. Must match the IAM ID in the bearer token. + * @param {string} [params.accountId] - The IBM Cloud account ID. If not provided, the account ID from the bearer + * token will be used. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public getPreferences( + params: PlatformNotificationsV1.GetPreferencesParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['iamId']; + const _validParams = ['iamId', 'accountId', 'signal', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const query = { + 'account_id': _params.accountId, + }; + + const path = { + 'iam_id': _params.iamId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'getPreferences' + ); + + const parameters = { + options: { + url: '/v1/notifications/{iam_id}/preferences', + method: 'GET', + qs: query, + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + + /** + * Update communication preferences. + * + * Update communication preferences for the specified account. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.iamId - The IAM ID of the user. Must match the IAM ID in the bearer token. + * @param {PreferenceValueWithUpdates} [params.incidentSeverity1] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.incidentSeverity2] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.incidentSeverity3] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.incidentSeverity4] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.maintenanceHigh] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.maintenanceMedium] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithUpdates} [params.maintenanceLow] - Preference settings for notification types that + * support updates. + * @param {PreferenceValueWithoutUpdates} [params.announcementsMajor] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.announcementsMinor] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.securityNormal] - Preference settings for notification types that do + * not support updates. + * @param {PreferenceValueWithoutUpdates} [params.accountNormal] - Preference settings for notification types that do + * not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsageOrder] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsageInvoices] - Preference settings for notification + * types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsagePayments] - Preference settings for notification + * types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsageSubscriptionsAndPromoCodes] - Preference settings for + * notification types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.billingAndUsageSpendingAlerts] - Preference settings for + * notification types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.resourceactivityNormal] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.orderingReview] - Preference settings for notification types that do + * not support updates. + * @param {PreferenceValueWithoutUpdates} [params.orderingApproved] - Preference settings for notification types that + * do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.orderingApprovedVsi] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.orderingApprovedServer] - Preference settings for notification types + * that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.provisioningReloadComplete] - Preference settings for notification + * types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.provisioningCompleteVsi] - Preference settings for notification + * types that do not support updates. + * @param {PreferenceValueWithoutUpdates} [params.provisioningCompleteServer] - Preference settings for notification + * types that do not support updates. + * @param {string} [params.accountId] - The IBM Cloud account ID. If not provided, the account ID from the bearer + * token will be used. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public replaceNotificationPreferences( + params: PlatformNotificationsV1.ReplaceNotificationPreferencesParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['iamId']; + const _validParams = [ + 'iamId', + 'incidentSeverity1', + 'incidentSeverity2', + 'incidentSeverity3', + 'incidentSeverity4', + 'maintenanceHigh', + 'maintenanceMedium', + 'maintenanceLow', + 'announcementsMajor', + 'announcementsMinor', + 'securityNormal', + 'accountNormal', + 'billingAndUsageOrder', + 'billingAndUsageInvoices', + 'billingAndUsagePayments', + 'billingAndUsageSubscriptionsAndPromoCodes', + 'billingAndUsageSpendingAlerts', + 'resourceactivityNormal', + 'orderingReview', + 'orderingApproved', + 'orderingApprovedVsi', + 'orderingApprovedServer', + 'provisioningReloadComplete', + 'provisioningCompleteVsi', + 'provisioningCompleteServer', + 'accountId', + 'signal', + 'headers', + ]; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const body = { + 'incident_severity1': _params.incidentSeverity1, + 'incident_severity2': _params.incidentSeverity2, + 'incident_severity3': _params.incidentSeverity3, + 'incident_severity4': _params.incidentSeverity4, + 'maintenance_high': _params.maintenanceHigh, + 'maintenance_medium': _params.maintenanceMedium, + 'maintenance_low': _params.maintenanceLow, + 'announcements_major': _params.announcementsMajor, + 'announcements_minor': _params.announcementsMinor, + 'security_normal': _params.securityNormal, + 'account_normal': _params.accountNormal, + 'billing_and_usage_order': _params.billingAndUsageOrder, + 'billing_and_usage_invoices': _params.billingAndUsageInvoices, + 'billing_and_usage_payments': _params.billingAndUsagePayments, + 'billing_and_usage_subscriptions_and_promo_codes': + _params.billingAndUsageSubscriptionsAndPromoCodes, + 'billing_and_usage_spending_alerts': _params.billingAndUsageSpendingAlerts, + 'resourceactivity_normal': _params.resourceactivityNormal, + 'ordering_review': _params.orderingReview, + 'ordering_approved': _params.orderingApproved, + 'ordering_approved_vsi': _params.orderingApprovedVsi, + 'ordering_approved_server': _params.orderingApprovedServer, + 'provisioning_reload_complete': _params.provisioningReloadComplete, + 'provisioning_complete_vsi': _params.provisioningCompleteVsi, + 'provisioning_complete_server': _params.provisioningCompleteServer, + }; + + const query = { + 'account_id': _params.accountId, + }; + + const path = { + 'iam_id': _params.iamId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'replaceNotificationPreferences' + ); + + const parameters = { + options: { + url: '/v1/notifications/{iam_id}/preferences', + method: 'PUT', + body, + qs: query, + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + + /** + * Resets all preferences to their default values. + * + * Delete all communication preferences for the specified account, and resets all preferences to their default values. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.iamId - The IAM ID of the user. Must match the IAM ID in the bearer token. + * @param {string} [params.accountId] - The IBM Cloud account ID. If not provided, the account ID from the bearer + * token will be used. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public deleteNotificationPreferences( + params: PlatformNotificationsV1.DeleteNotificationPreferencesParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['iamId']; + const _validParams = ['iamId', 'accountId', 'signal', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const query = { + 'account_id': _params.accountId, + }; + + const path = { + 'iam_id': _params.iamId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'deleteNotificationPreferences' + ); + + const parameters = { + options: { + url: '/v1/notifications/{iam_id}/preferences', + method: 'DELETE', + qs: query, + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend(true, sdkHeaders, this.baseOptions.headers, {}, _params.headers), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + /************************* + * notifications + ************************/ + + /** + * Get user notifications. + * + * Retrieve all notifications for the requested user. + * + * @param {Object} [params] - The parameters to send to the service. + * @param {string} [params.accountId] - The IBM Cloud account ID. If not provided, the account ID from the bearer + * token will be used. + * @param {string} [params.start] - An opaque page token that specifies the resource to start the page on or after. If + * unspecified, the first page of results is returned. + * @param {number} [params.limit] - The maximum number of items to return per page. If unspecified, a default limit of + * 50 is used. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public listNotifications( + params?: PlatformNotificationsV1.ListNotificationsParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = []; + const _validParams = ['accountId', 'start', 'limit', 'signal', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const query = { + 'account_id': _params.accountId, + 'start': _params.start, + 'limit': _params.limit, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'listNotifications' + ); + + const parameters = { + options: { + url: '/v1/notifications', + method: 'GET', + qs: query, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + + /** + * Get user's last acknowledged notification Id. + * + * Retrieve the ID of the last notification acknowledged by the user for a specific account. + * + * @param {Object} [params] - The parameters to send to the service. + * @param {string} [params.accountId] - The account ID to retrieve acknowledgement for. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public getAcknowledgement( + params?: PlatformNotificationsV1.GetAcknowledgementParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = []; + const _validParams = ['accountId', 'signal', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const query = { + 'account_id': _params.accountId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'getAcknowledgement' + ); + + const parameters = { + options: { + url: '/v1/notifications/acknowledgement', + method: 'GET', + qs: query, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } + + /** + * Update user's last acknowledged notification. + * + * Update the ID of the last notification acknowledged by the user for a specific account. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.lastAcknowledgedId - The ID of a notification. + * @param {string} [params.accountId] - The account ID to update acknowledgement for. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public replaceNotificationAcknowledgement( + params: PlatformNotificationsV1.ReplaceNotificationAcknowledgementParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['lastAcknowledgedId']; + const _validParams = ['lastAcknowledgedId', 'accountId', 'signal', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const body = { + 'last_acknowledged_id': _params.lastAcknowledgedId, + }; + + const query = { + 'account_id': _params.accountId, + }; + + const sdkHeaders = getSdkHeaders( + PlatformNotificationsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'replaceNotificationAcknowledgement' + ); + + const parameters = { + options: { + url: '/v1/notifications/acknowledgement', + method: 'PUT', + body, + qs: query, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + this.baseOptions.headers, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + _params.headers + ), + axiosOptions: { + signal: _params.signal, + }, + }), + }; + + return this.createRequest(parameters); + } +} + +/************************* + * interfaces + ************************/ + +namespace PlatformNotificationsV1 { + /** An operation response. */ + export interface Response { + result: T; + status: number; + statusText: string; + headers: IncomingHttpHeaders; + } + + /** The callback for a service request. */ + export type Callback = (error: any, response?: Response) => void; + + /** The body of a service request that returns no response data. */ + export interface EmptyObject {} + + /** A standard JS object, defined to avoid the limitations of `Object` and `object` */ + export interface JsonObject { + [key: string]: any; + } + + /************************* + * request interfaces + ************************/ + + interface DefaultParams { + headers?: OutgoingHttpHeaders; + signal?: AbortSignal; + } + + /** Parameters for the `listDistributionListDestinations` operation. */ + export interface ListDistributionListDestinationsParams extends DefaultParams { + /** The IBM Cloud account ID. */ + accountId: string; + } + + /** Parameters for the `createDistributionListDestination` operation. */ + export interface CreateDistributionListDestinationParams extends DefaultParams { + /** The IBM Cloud account ID. */ + accountId: string; + addDestinationPrototype: AddDestinationPrototype; + } + + /** Parameters for the `getDistributionListDestination` operation. */ + export interface GetDistributionListDestinationParams extends DefaultParams { + /** The IBM Cloud account ID. */ + accountId: string; + /** The ID of the destination. */ + destinationId: string; + } + + /** Parameters for the `deleteDistributionListDestination` operation. */ + export interface DeleteDistributionListDestinationParams extends DefaultParams { + /** The IBM Cloud account ID. */ + accountId: string; + /** The ID of the destination. */ + destinationId: string; + } + + /** Parameters for the `testDistributionListDestination` operation. */ + export interface TestDistributionListDestinationParams extends DefaultParams { + /** The IBM Cloud account ID. */ + accountId: string; + /** The ID of the destination. */ + destinationId: string; + testDestinationRequestBodyPrototype: TestDestinationRequestBodyPrototype; + } + + /** Parameters for the `createPreferences` operation. */ + export interface CreatePreferencesParams extends DefaultParams { + /** The IAM ID of the user. Must match the IAM ID in the bearer token. */ + iamId: string; + /** Preference settings for notification types that support updates. */ + incidentSeverity1?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + incidentSeverity2?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + incidentSeverity3?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + incidentSeverity4?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + maintenanceHigh?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + maintenanceMedium?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + maintenanceLow?: PreferenceValueWithUpdates; + /** Preference settings for notification types that do not support updates. */ + announcementsMajor?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + announcementsMinor?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + securityNormal?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + accountNormal?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsageOrder?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsageInvoices?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsagePayments?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsageSubscriptionsAndPromoCodes?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsageSpendingAlerts?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + resourceactivityNormal?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + orderingReview?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + orderingApproved?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + orderingApprovedVsi?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + orderingApprovedServer?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + provisioningReloadComplete?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + provisioningCompleteVsi?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + provisioningCompleteServer?: PreferenceValueWithoutUpdates; + /** The IBM Cloud account ID. If not provided, the account ID from the bearer token will be used. */ + accountId?: string; + } + + /** Parameters for the `getPreferences` operation. */ + export interface GetPreferencesParams extends DefaultParams { + /** The IAM ID of the user. Must match the IAM ID in the bearer token. */ + iamId: string; + /** The IBM Cloud account ID. If not provided, the account ID from the bearer token will be used. */ + accountId?: string; + } + + /** Parameters for the `replaceNotificationPreferences` operation. */ + export interface ReplaceNotificationPreferencesParams extends DefaultParams { + /** The IAM ID of the user. Must match the IAM ID in the bearer token. */ + iamId: string; + /** Preference settings for notification types that support updates. */ + incidentSeverity1?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + incidentSeverity2?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + incidentSeverity3?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + incidentSeverity4?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + maintenanceHigh?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + maintenanceMedium?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + maintenanceLow?: PreferenceValueWithUpdates; + /** Preference settings for notification types that do not support updates. */ + announcementsMajor?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + announcementsMinor?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + securityNormal?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + accountNormal?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsageOrder?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsageInvoices?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsagePayments?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsageSubscriptionsAndPromoCodes?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billingAndUsageSpendingAlerts?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + resourceactivityNormal?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + orderingReview?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + orderingApproved?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + orderingApprovedVsi?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + orderingApprovedServer?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + provisioningReloadComplete?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + provisioningCompleteVsi?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + provisioningCompleteServer?: PreferenceValueWithoutUpdates; + /** The IBM Cloud account ID. If not provided, the account ID from the bearer token will be used. */ + accountId?: string; + } + + /** Parameters for the `deleteNotificationPreferences` operation. */ + export interface DeleteNotificationPreferencesParams extends DefaultParams { + /** The IAM ID of the user. Must match the IAM ID in the bearer token. */ + iamId: string; + /** The IBM Cloud account ID. If not provided, the account ID from the bearer token will be used. */ + accountId?: string; + } + + /** Parameters for the `listNotifications` operation. */ + export interface ListNotificationsParams extends DefaultParams { + /** The IBM Cloud account ID. If not provided, the account ID from the bearer token will be used. */ + accountId?: string; + /** An opaque page token that specifies the resource to start the page on or after. If unspecified, the first + * page of results is returned. + */ + start?: string; + /** The maximum number of items to return per page. If unspecified, a default limit of 50 is used. */ + limit?: number; + } + + /** Parameters for the `getAcknowledgement` operation. */ + export interface GetAcknowledgementParams extends DefaultParams { + /** The account ID to retrieve acknowledgement for. */ + accountId?: string; + } + + /** Parameters for the `replaceNotificationAcknowledgement` operation. */ + export interface ReplaceNotificationAcknowledgementParams extends DefaultParams { + /** The ID of a notification. */ + lastAcknowledgedId: string; + /** The account ID to update acknowledgement for. */ + accountId?: string; + } + + /************************* + * model interfaces + ************************/ + + /** + * AddDestination. + */ + export interface AddDestination {} + + /** + * List of destinations in the distribution list. + */ + export interface AddDestinationCollection { + /** Array of destination entries. */ + destinations: AddDestination[]; + } + + /** + * AddDestinationPrototype. + */ + export interface AddDestinationPrototype {} + + /** + * A notification entry. + */ + export interface Notification { + /** The title of the notification. */ + title: string; + /** The body content of the notification. */ + body: string; + /** The unique identifier for the notification. */ + id: string; + /** The category of the notification. */ + category: Notification.Constants.Category | string; + /** Array of component/service names affected by this notification. */ + component_names: string[]; + /** The start time of the notification in Unix timestamp (milliseconds). */ + start_time: number; + /** Indicates if the notification is global. */ + is_global: boolean; + /** The current state of the notification. */ + state: Notification.Constants.State | string; + /** Array of region identifiers affected by this notification. */ + regions: string[]; + /** Array of CRN masks that define the scope of affected resources. */ + crn_masks: string[]; + /** The record identifier for tracking purposes. */ + record_id?: string; + /** The source identifier of the notification. */ + source_id?: string; + /** The completion code of the notification. */ + completion_code: Notification.Constants.CompletionCode | string; + /** The end time of the notification in Unix timestamp (milliseconds). */ + end_time?: number; + /** The last update time of the notification in Unix timestamp (milliseconds). */ + update_time: number; + /** The severity level of the notification (0-3). The display value depends on the notification type: + * + * **Incidents:** + * - 1 = Severity 1 + * - 2 = Severity 2 + * - 3 = Severity 3 + * - 0 = Severity 4 + * + * **Maintenance:** + * - 1 = High + * - 2 = Medium + * - 3 = Low + * + * **Announcements:** + * - 1 = Major + * - 0 = Minor. + */ + severity: number; + /** Lucene query string for filtering affected resources. Only present when instance targets are specified and + * resource_link is not available. Mutually exclusive with resource_link. + */ + lucene_query?: string; + /** Link to additional resource information or documentation. Takes precedence over lucene_query when both are + * available. Mutually exclusive with lucene_query. + */ + resource_link?: string; + } + export namespace Notification { + export namespace Constants { + /** The category of the notification. */ + export enum Category { + INCIDENT = 'incident', + MAINTENANCE = 'maintenance', + ANNOUNCEMENTS = 'announcements', + SECURITY_BULLETINS = 'security_bulletins', + SECURITY = 'security', + RESOURCE = 'resource', + BILLING_AND_USAGE = 'billing_and_usage', + ORDERING = 'ordering', + PROVISIONING = 'provisioning', + ACCOUNT = 'account', + } + /** The current state of the notification. */ + export enum State { + NEW = 'new', + IN_PROGRESS = 'in-progress', + COMPLETE = 'complete', + RESOLVED = 'resolved', + } + /** The completion code of the notification. */ + export enum CompletionCode { + SUCCESSFUL = 'successful', + FAILED = 'failed', + CANCELLED = 'cancelled', + } + } + } + + /** + * Collection of user notifications with token-based pagination metadata. + */ + export interface NotificationCollection { + /** The maximum number of items returned in this response. */ + limit: number; + /** The total number of notifications in the collection. */ + total_count: number; + /** A pagination link object containing the URL to a page. */ + first: PaginationLink; + /** A pagination link object with a page token. Used for next, previous, and last page links. */ + previous?: PaginationLinkWithToken; + /** A pagination link object with a page token. Used for next, previous, and last page links. */ + next?: PaginationLinkWithToken; + /** A pagination link object with a page token. Used for next, previous, and last page links. */ + last?: PaginationLinkWithToken; + /** Array of notification entries. */ + notifications: Notification[]; + } + + /** + * A pagination link object containing the URL to a page. + */ + export interface PaginationLink { + /** Complete URL to the page. */ + href: string; + } + + /** + * A pagination link object with a page token. Used for next, previous, and last page links. + */ + export interface PaginationLinkWithToken { + /** Complete URL to the page. */ + href: string; + /** Opaque page token that can be used to retrieve the page. */ + start: string; + } + + /** + * Preference settings for notification types that support updates. + */ + export interface PreferenceValueWithUpdates { + /** Array of communication channels for this preference. */ + channels: PreferenceValueWithUpdates.Constants.Channels[] | string[]; + /** Whether to receive updates for this preference. Optional, defaults to false if not provided. */ + updates?: boolean; + } + export namespace PreferenceValueWithUpdates { + export namespace Constants { + /** Array of communication channels for this preference. */ + export enum Channels { + EMAIL = 'email', + } + } + } + + /** + * Preference settings for notification types that do not support updates. + */ + export interface PreferenceValueWithoutUpdates { + /** Array of communication channels for this preference. */ + channels: PreferenceValueWithoutUpdates.Constants.Channels[] | string[]; + } + export namespace PreferenceValueWithoutUpdates { + export namespace Constants { + /** Array of communication channels for this preference. */ + export enum Channels { + EMAIL = 'email', + } + } + } + + /** + * User communication preferences object. Only include preferences where communication is desired; absence of a key + * means no communication for that preference type. + */ + export interface PreferencesObject { + /** Preference settings for notification types that support updates. */ + incident_severity1?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + incident_severity2?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + incident_severity3?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + incident_severity4?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + maintenance_high?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + maintenance_medium?: PreferenceValueWithUpdates; + /** Preference settings for notification types that support updates. */ + maintenance_low?: PreferenceValueWithUpdates; + /** Preference settings for notification types that do not support updates. */ + announcements_major?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + announcements_minor?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + security_normal?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + account_normal?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billing_and_usage_order?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billing_and_usage_invoices?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billing_and_usage_payments?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billing_and_usage_subscriptions_and_promo_codes?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + billing_and_usage_spending_alerts?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + resourceactivity_normal?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + ordering_review?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + ordering_approved?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + ordering_approved_vsi?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + ordering_approved_server?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + provisioning_reload_complete?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + provisioning_complete_vsi?: PreferenceValueWithoutUpdates; + /** Preference settings for notification types that do not support updates. */ + provisioning_complete_server?: PreferenceValueWithoutUpdates; + } + + /** + * TestDestinationRequestBodyPrototype. + */ + export interface TestDestinationRequestBodyPrototype {} + + /** + * Response from the test notification endpoint. + */ + export interface TestDestinationResponseBody { + /** The status message that indicates the test result. */ + message: string; + } + + /** + * Status indicating whether the user has unread notifications. + */ + export interface Acknowledgement { + /** Indicates whether the user has unread notifications. */ + has_unread: boolean; + /** The ID of the most recent notification available to the user. */ + latest_notification_id: string; + /** The ID of the last notification acknowledged by the user. */ + last_acknowledged_id: string; + } + + /** + * Prototype for creating an Event Notifications destination entry. + */ + export interface AddDestinationPrototypeEventNotificationDestinationPrototype + extends AddDestinationPrototype { + /** The GUID of the Event Notifications instance. */ + destination_id: string; + /** The type of the destination. */ + destination_type: + | AddDestinationPrototypeEventNotificationDestinationPrototype.Constants.DestinationType + | string; + } + export namespace AddDestinationPrototypeEventNotificationDestinationPrototype { + export namespace Constants { + /** The type of the destination. */ + export enum DestinationType { + EVENT_NOTIFICATIONS = 'event_notifications', + } + } + } + + /** + * An Event Notifications destination entry in the distribution list. + */ + export interface AddDestinationEventNotificationDestination extends AddDestination { + /** The GUID of the Event Notifications instance. */ + destination_id: string; + /** The type of the destination. */ + destination_type: AddDestinationEventNotificationDestination.Constants.DestinationType | string; + } + export namespace AddDestinationEventNotificationDestination { + export namespace Constants { + /** The type of the destination. */ + export enum DestinationType { + EVENT_NOTIFICATIONS = 'event_notifications', + } + } + } + + /** + * Request body for testing an Event Notifications destination. + */ + export interface TestDestinationRequestBodyPrototypeTestEventNotificationDestinationRequestBodyPrototype + extends TestDestinationRequestBodyPrototype { + /** The type of the destination. */ + destination_type: + | TestDestinationRequestBodyPrototypeTestEventNotificationDestinationRequestBodyPrototype.Constants.DestinationType + | string; + /** The type of the notification to test. */ + notification_type: + | TestDestinationRequestBodyPrototypeTestEventNotificationDestinationRequestBodyPrototype.Constants.NotificationType + | string; + } + export namespace TestDestinationRequestBodyPrototypeTestEventNotificationDestinationRequestBodyPrototype { + export namespace Constants { + /** The type of the destination. */ + export enum DestinationType { + EVENT_NOTIFICATIONS = 'event_notifications', + } + /** The type of the notification to test. */ + export enum NotificationType { + INCIDENT = 'incident', + ANNOUNCEMENTS = 'announcements', + MAINTENANCE = 'maintenance', + SECURITY_BULLETINS = 'security_bulletins', + RESOURCE = 'resource', + BILLING_AND_USAGE = 'billing_and_usage', + } + } + } + + /************************* + * pager classes + ************************/ + + /** + * NotificationsPager can be used to simplify the use of listNotifications(). + */ + export class NotificationsPager { + protected _hasNext: boolean; + + protected pageContext: any; + + protected client: PlatformNotificationsV1; + + protected params: PlatformNotificationsV1.ListNotificationsParams; + + /** + * Construct a NotificationsPager object. + * + * @param {PlatformNotificationsV1} client - The service client instance used to invoke listNotifications() + * @param {Object} [params] - The parameters to be passed to listNotifications() + * @constructor + * @returns {NotificationsPager} + */ + constructor( + client: PlatformNotificationsV1, + params?: PlatformNotificationsV1.ListNotificationsParams + ) { + if (params && params.start) { + throw new Error(`the params.start 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 listNotifications(). + * @returns {Promise} + */ + public async getNext(): Promise { + if (!this.hasNext()) { + throw new Error('No more results available'); + } + + if (this.pageContext.next) { + this.params.start = this.pageContext.next; + } + const response = await this.client.listNotifications(this.params); + const { result } = response; + + let next; + if (result && result.next) { + next = result.next.start; + } + this.pageContext.next = next; + if (!this.pageContext.next) { + this._hasNext = false; + } + return result.notifications; + } + + /** + * Returns all results by invoking listNotifications() repeatedly until all pages of results have been retrieved. + * @returns {Promise} + */ + public async getAll(): Promise { + const results: Notification[] = []; + while (this.hasNext()) { + const nextPage = await this.getNext(); + results.push(...nextPage); + } + return results; + } + } +} + +export = PlatformNotificationsV1; diff --git a/test/integration/platform-notifications.v1.test.js b/test/integration/platform-notifications.v1.test.js new file mode 100644 index 0000000..d99f0c7 --- /dev/null +++ b/test/integration/platform-notifications.v1.test.js @@ -0,0 +1,321 @@ +/** + * (C) Copyright IBM Corp. 2026. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-disable no-console */ +/* eslint-disable no-await-in-loop */ + +const { readExternalSources } = require('ibm-cloud-sdk-core'); +const PlatformNotificationsV1 = require('../../dist/platform-notifications/v1'); +const authHelper = require('../resources/auth-helper.js'); + +// testcase timeout value (200s). +const timeout = 200000; + +// Location of our config file. +/** + * required variables in platform_notifications_v1.env + * PLATFORM_NOTIFICATIONS_URL + * PLATFORM_NOTIFICATIONS_AUTH_TYPE + * PLATFORM_NOTIFICATIONS_AUTH_URL + * PLATFORM_NOTIFICATIONS_APIKEY + * PLATFORM_NOTIFICATIONS_ACCOUNT_ID + * PLATFORM_NOTIFICATIONS_DESTINATION_ID + * PLATFORM_NOTIFICATIONS_IAM_ID + */ +const configFile = 'platform_notifications_v1.env'; + +const describe = authHelper.prepareTests(configFile); + +describe('PlatformNotificationsV1_integration', () => { + jest.setTimeout(timeout); + + // Service instance + let platformNotificationsService; + let accountId; + let destinationId; + let iamId; + + beforeAll(() => { + const config = readExternalSources(PlatformNotificationsV1.DEFAULT_SERVICE_NAME); + + platformNotificationsService = PlatformNotificationsV1.newInstance({ + serviceUrl: config.serviceUrl, + }); + accountId = config.accountId; + destinationId = config.destinationId; + iamId = config.iamId; + platformNotificationsService.enableRetries(); + }); + + test('Initialize service', async () => { + expect(platformNotificationsService).not.toBeNull(); + }); + + test('testDistributionListDestination()', async () => { + // Request models needed by this operation. + + // TestDestinationRequestBodyPrototypeTestEventNotificationDestinationRequestBodyPrototype + const testDestinationRequestBodyPrototypeModel = { + destination_type: 'event_notifications', + notification_type: 'incident', + }; + + const params = { + accountId, + destinationId, + testDestinationRequestBodyPrototype: testDestinationRequestBodyPrototypeModel, + }; + + const res = await platformNotificationsService.testDistributionListDestination(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('deleteDistributionListDestination()', async () => { + const params = { + accountId, + destinationId, + }; + + const res = await platformNotificationsService.deleteDistributionListDestination(params); + expect(res).toBeDefined(); + expect(res.status).toBe(204); + expect(res.result).toBeDefined(); + }); + + test('createDistributionListDestination()', async () => { + // Request models needed by this operation. + + // AddDestinationPrototypeEventNotificationDestinationPrototype + const addDestinationPrototypeModel = { + destination_id: destinationId, + destination_type: 'event_notifications', + }; + + const params = { + accountId, + addDestinationPrototype: addDestinationPrototypeModel, + }; + + const res = await platformNotificationsService.createDistributionListDestination(params); + expect(res).toBeDefined(); + expect(res.status).toBe(201); + expect(res.result).toBeDefined(); + }); + + test('listDistributionListDestinations()', async () => { + const params = { + accountId, + }; + + const res = await platformNotificationsService.listDistributionListDestinations(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('getDistributionListDestination()', async () => { + const params = { + accountId, + destinationId, + }; + + const res = await platformNotificationsService.getDistributionListDestination(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('createPreferences()', async () => { + // Request models needed by this operation. + + // PreferenceValueWithUpdates + const preferenceValueWithUpdatesModel = { + channels: ['email'], + updates: true, + }; + + // PreferenceValueWithoutUpdates + const preferenceValueWithoutUpdatesModel = { + channels: ['email'], + }; + + const params = { + iamId, + incidentSeverity1: preferenceValueWithUpdatesModel, + incidentSeverity2: preferenceValueWithUpdatesModel, + incidentSeverity3: preferenceValueWithUpdatesModel, + incidentSeverity4: preferenceValueWithUpdatesModel, + maintenanceHigh: preferenceValueWithUpdatesModel, + maintenanceMedium: preferenceValueWithUpdatesModel, + maintenanceLow: preferenceValueWithUpdatesModel, + announcementsMajor: preferenceValueWithoutUpdatesModel, + announcementsMinor: preferenceValueWithoutUpdatesModel, + securityNormal: preferenceValueWithoutUpdatesModel, + accountNormal: preferenceValueWithoutUpdatesModel, + billingAndUsageOrder: preferenceValueWithoutUpdatesModel, + billingAndUsageInvoices: preferenceValueWithoutUpdatesModel, + billingAndUsagePayments: preferenceValueWithoutUpdatesModel, + billingAndUsageSubscriptionsAndPromoCodes: preferenceValueWithoutUpdatesModel, + billingAndUsageSpendingAlerts: preferenceValueWithoutUpdatesModel, + resourceactivityNormal: preferenceValueWithoutUpdatesModel, + orderingReview: preferenceValueWithoutUpdatesModel, + orderingApproved: preferenceValueWithoutUpdatesModel, + orderingApprovedVsi: preferenceValueWithoutUpdatesModel, + orderingApprovedServer: preferenceValueWithoutUpdatesModel, + provisioningReloadComplete: preferenceValueWithoutUpdatesModel, + provisioningCompleteVsi: preferenceValueWithoutUpdatesModel, + provisioningCompleteServer: preferenceValueWithoutUpdatesModel, + accountId, + }; + + const res = await platformNotificationsService.createPreferences(params); + expect(res).toBeDefined(); + expect(res.status).toBe(201); + expect(res.result).toBeDefined(); + }); + + test('getPreferences()', async () => { + const params = { + iamId, + accountId, + }; + + const res = await platformNotificationsService.getPreferences(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('replaceNotificationPreferences()', async () => { + // Request models needed by this operation. + + // PreferenceValueWithUpdates + const preferenceValueWithUpdatesModel = { + channels: ['email'], + updates: true, + }; + + // PreferenceValueWithoutUpdates + const preferenceValueWithoutUpdatesModel = { + channels: ['email'], + }; + + const params = { + iamId, + incidentSeverity1: preferenceValueWithUpdatesModel, + incidentSeverity2: preferenceValueWithUpdatesModel, + incidentSeverity3: preferenceValueWithUpdatesModel, + incidentSeverity4: preferenceValueWithUpdatesModel, + maintenanceHigh: preferenceValueWithUpdatesModel, + maintenanceMedium: preferenceValueWithUpdatesModel, + maintenanceLow: preferenceValueWithUpdatesModel, + announcementsMajor: preferenceValueWithoutUpdatesModel, + announcementsMinor: preferenceValueWithoutUpdatesModel, + securityNormal: preferenceValueWithoutUpdatesModel, + accountNormal: preferenceValueWithoutUpdatesModel, + billingAndUsageOrder: preferenceValueWithoutUpdatesModel, + billingAndUsageInvoices: preferenceValueWithoutUpdatesModel, + billingAndUsagePayments: preferenceValueWithoutUpdatesModel, + billingAndUsageSubscriptionsAndPromoCodes: preferenceValueWithoutUpdatesModel, + billingAndUsageSpendingAlerts: preferenceValueWithoutUpdatesModel, + resourceactivityNormal: preferenceValueWithoutUpdatesModel, + orderingReview: preferenceValueWithoutUpdatesModel, + orderingApproved: preferenceValueWithoutUpdatesModel, + orderingApprovedVsi: preferenceValueWithoutUpdatesModel, + orderingApprovedServer: preferenceValueWithoutUpdatesModel, + provisioningReloadComplete: preferenceValueWithoutUpdatesModel, + provisioningCompleteVsi: preferenceValueWithoutUpdatesModel, + provisioningCompleteServer: preferenceValueWithoutUpdatesModel, + accountId, + }; + + const res = await platformNotificationsService.replaceNotificationPreferences(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listNotifications()', async () => { + const params = { + accountId, + }; + + const res = await platformNotificationsService.listNotifications(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listNotifications() via NotificationsPager', async () => { + const params = { + accountId, + limit: 50, + }; + + const allResults = []; + + // Test getNext(). + let pager = new PlatformNotificationsV1.NotificationsPager( + platformNotificationsService, + params + ); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new PlatformNotificationsV1.NotificationsPager(platformNotificationsService, 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.`); + }); + + test('getAcknowledgement()', async () => { + const res = await platformNotificationsService.getAcknowledgement(); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('replaceNotificationAcknowledgement()', async () => { + const params = { + lastAcknowledgedId: '1772804159452', + accountId, + }; + + const res = await platformNotificationsService.replaceNotificationAcknowledgement(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('deleteNotificationPreferences()', async () => { + const params = { + iamId, + accountId, + }; + + const res = await platformNotificationsService.deleteNotificationPreferences(params); + expect(res).toBeDefined(); + expect(res.status).toBe(204); + expect(res.result).toBeDefined(); + }); +}); diff --git a/test/unit/platform-notifications.v1.test.js b/test/unit/platform-notifications.v1.test.js new file mode 100644 index 0000000..6a2bd33 --- /dev/null +++ b/test/unit/platform-notifications.v1.test.js @@ -0,0 +1,1372 @@ +/** + * (C) Copyright IBM Corp. 2026. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-disable no-await-in-loop */ + +const nock = require('nock'); + +// need to import the whole package to mock getAuthenticatorFromEnvironment +const sdkCorePackage = require('ibm-cloud-sdk-core'); + +const { NoAuthAuthenticator } = sdkCorePackage; +const PlatformNotificationsV1 = require('../../dist/platform-notifications/v1'); + +const { + getOptions, + checkUrlAndMethod, + checkMediaHeaders, + expectToBePromise, + checkForSuccessfulExecution, +} = require('@ibm-cloud/sdk-test-utilities'); + +const platformNotificationsServiceOptions = { + authenticator: new NoAuthAuthenticator(), + url: 'https://notifications.cloud.ibm.com/api', +}; + +const platformNotificationsService = new PlatformNotificationsV1(platformNotificationsServiceOptions); + +let createRequestMock = null; +function mock_createRequest() { + if (!createRequestMock) { + createRequestMock = jest.spyOn(platformNotificationsService, 'createRequest'); + createRequestMock.mockImplementation(() => Promise.resolve()); + } +} +function unmock_createRequest() { + if (createRequestMock) { + createRequestMock.mockRestore(); + createRequestMock = null; + } +} + +// dont actually construct an authenticator +const getAuthenticatorMock = jest.spyOn(sdkCorePackage, 'getAuthenticatorFromEnvironment'); +getAuthenticatorMock.mockImplementation(() => new NoAuthAuthenticator()); + +describe('PlatformNotificationsV1', () => { + beforeEach(() => { + mock_createRequest(); + }); + + afterEach(() => { + if (createRequestMock) { + createRequestMock.mockClear(); + } + getAuthenticatorMock.mockClear(); + }); + + describe('the newInstance method', () => { + test('should use defaults when options not provided', () => { + const testInstance = PlatformNotificationsV1.newInstance(); + + expect(getAuthenticatorMock).toHaveBeenCalled(); + expect(testInstance.baseOptions.authenticator).toBeInstanceOf(NoAuthAuthenticator); + expect(testInstance.baseOptions.serviceName).toBe(PlatformNotificationsV1.DEFAULT_SERVICE_NAME); + expect(testInstance.baseOptions.serviceUrl).toBe(PlatformNotificationsV1.DEFAULT_SERVICE_URL); + expect(testInstance).toBeInstanceOf(PlatformNotificationsV1); + }); + + test('should set serviceName, serviceUrl, and authenticator when provided', () => { + const options = { + authenticator: new NoAuthAuthenticator(), + serviceUrl: 'custom.com', + serviceName: 'my-service', + }; + + const testInstance = PlatformNotificationsV1.newInstance(options); + + expect(getAuthenticatorMock).not.toHaveBeenCalled(); + expect(testInstance.baseOptions.authenticator).toBeInstanceOf(NoAuthAuthenticator); + expect(testInstance.baseOptions.serviceUrl).toBe('custom.com'); + expect(testInstance.baseOptions.serviceName).toBe('my-service'); + expect(testInstance).toBeInstanceOf(PlatformNotificationsV1); + }); + }); + + describe('the constructor', () => { + test('use user-given service url', () => { + const options = { + authenticator: new NoAuthAuthenticator(), + serviceUrl: 'custom.com', + }; + + const testInstance = new PlatformNotificationsV1(options); + + expect(testInstance.baseOptions.serviceUrl).toBe('custom.com'); + }); + + test('use default service url', () => { + const options = { + authenticator: new NoAuthAuthenticator(), + }; + + const testInstance = new PlatformNotificationsV1(options); + + expect(testInstance.baseOptions.serviceUrl).toBe(PlatformNotificationsV1.DEFAULT_SERVICE_URL); + }); + }); + + describe('listDistributionListDestinations', () => { + describe('positive tests', () => { + function __listDistributionListDestinationsTest() { + // Construct the params object for operation listDistributionListDestinations + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const listDistributionListDestinationsParams = { + accountId, + }; + + const listDistributionListDestinationsResult = platformNotificationsService.listDistributionListDestinations(listDistributionListDestinationsParams); + + // all methods should return a Promise + expectToBePromise(listDistributionListDestinationsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/distribution_lists/{account_id}/destinations', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listDistributionListDestinationsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __listDistributionListDestinationsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __listDistributionListDestinationsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listDistributionListDestinationsParams = { + accountId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.listDistributionListDestinations(listDistributionListDestinationsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.listDistributionListDestinations({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.listDistributionListDestinations(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('createDistributionListDestination', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // AddDestinationPrototypeEventNotificationDestinationPrototype + const addDestinationPrototypeModel = { + destination_id: '12345678-1234-1234-1234-123456789012', + destination_type: 'event_notifications', + }; + + function __createDistributionListDestinationTest() { + // Construct the params object for operation createDistributionListDestination + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const addDestinationPrototype = addDestinationPrototypeModel; + const createDistributionListDestinationParams = { + accountId, + addDestinationPrototype, + }; + + const createDistributionListDestinationResult = platformNotificationsService.createDistributionListDestination(createDistributionListDestinationParams); + + // all methods should return a Promise + expectToBePromise(createDistributionListDestinationResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/distribution_lists/{account_id}/destinations', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body).toEqual(addDestinationPrototype); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createDistributionListDestinationTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __createDistributionListDestinationTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __createDistributionListDestinationTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const addDestinationPrototype = addDestinationPrototypeModel; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createDistributionListDestinationParams = { + accountId, + addDestinationPrototype, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.createDistributionListDestination(createDistributionListDestinationParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.createDistributionListDestination({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.createDistributionListDestination(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getDistributionListDestination', () => { + describe('positive tests', () => { + function __getDistributionListDestinationTest() { + // Construct the params object for operation getDistributionListDestination + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const destinationId = '12345678-1234-1234-1234-123456789012'; + const getDistributionListDestinationParams = { + accountId, + destinationId, + }; + + const getDistributionListDestinationResult = platformNotificationsService.getDistributionListDestination(getDistributionListDestinationParams); + + // all methods should return a Promise + expectToBePromise(getDistributionListDestinationResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/distribution_lists/{account_id}/destinations/{destination_id}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.destination_id).toEqual(destinationId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getDistributionListDestinationTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __getDistributionListDestinationTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __getDistributionListDestinationTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const destinationId = '12345678-1234-1234-1234-123456789012'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getDistributionListDestinationParams = { + accountId, + destinationId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.getDistributionListDestination(getDistributionListDestinationParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.getDistributionListDestination({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.getDistributionListDestination(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteDistributionListDestination', () => { + describe('positive tests', () => { + function __deleteDistributionListDestinationTest() { + // Construct the params object for operation deleteDistributionListDestination + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const destinationId = '12345678-1234-1234-1234-123456789012'; + const deleteDistributionListDestinationParams = { + accountId, + destinationId, + }; + + const deleteDistributionListDestinationResult = platformNotificationsService.deleteDistributionListDestination(deleteDistributionListDestinationParams); + + // all methods should return a Promise + expectToBePromise(deleteDistributionListDestinationResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/distribution_lists/{account_id}/destinations/{destination_id}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.destination_id).toEqual(destinationId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteDistributionListDestinationTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __deleteDistributionListDestinationTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __deleteDistributionListDestinationTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const destinationId = '12345678-1234-1234-1234-123456789012'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteDistributionListDestinationParams = { + accountId, + destinationId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.deleteDistributionListDestination(deleteDistributionListDestinationParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.deleteDistributionListDestination({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.deleteDistributionListDestination(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('testDistributionListDestination', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // TestDestinationRequestBodyPrototypeTestEventNotificationDestinationRequestBodyPrototype + const testDestinationRequestBodyPrototypeModel = { + destination_type: 'event_notifications', + notification_type: 'incident', + }; + + function __testDistributionListDestinationTest() { + // Construct the params object for operation testDistributionListDestination + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const destinationId = '12345678-1234-1234-1234-123456789012'; + const testDestinationRequestBodyPrototype = testDestinationRequestBodyPrototypeModel; + const testDistributionListDestinationParams = { + accountId, + destinationId, + testDestinationRequestBodyPrototype, + }; + + const testDistributionListDestinationResult = platformNotificationsService.testDistributionListDestination(testDistributionListDestinationParams); + + // all methods should return a Promise + expectToBePromise(testDistributionListDestinationResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/distribution_lists/{account_id}/destinations/{destination_id}/test', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body).toEqual(testDestinationRequestBodyPrototype); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.destination_id).toEqual(destinationId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __testDistributionListDestinationTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __testDistributionListDestinationTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __testDistributionListDestinationTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const destinationId = '12345678-1234-1234-1234-123456789012'; + const testDestinationRequestBodyPrototype = testDestinationRequestBodyPrototypeModel; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const testDistributionListDestinationParams = { + accountId, + destinationId, + testDestinationRequestBodyPrototype, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.testDistributionListDestination(testDistributionListDestinationParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.testDistributionListDestination({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.testDistributionListDestination(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('createPreferences', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // PreferenceValueWithUpdates + const preferenceValueWithUpdatesModel = { + channels: ['email'], + updates: true, + }; + + // PreferenceValueWithoutUpdates + const preferenceValueWithoutUpdatesModel = { + channels: ['email'], + }; + + function __createPreferencesTest() { + // Construct the params object for operation createPreferences + const iamId = 'IBMid-1234567890'; + const incidentSeverity1 = preferenceValueWithUpdatesModel; + const incidentSeverity2 = preferenceValueWithUpdatesModel; + const incidentSeverity3 = preferenceValueWithUpdatesModel; + const incidentSeverity4 = preferenceValueWithUpdatesModel; + const maintenanceHigh = preferenceValueWithUpdatesModel; + const maintenanceMedium = preferenceValueWithUpdatesModel; + const maintenanceLow = preferenceValueWithUpdatesModel; + const announcementsMajor = preferenceValueWithoutUpdatesModel; + const announcementsMinor = preferenceValueWithoutUpdatesModel; + const securityNormal = preferenceValueWithoutUpdatesModel; + const accountNormal = preferenceValueWithoutUpdatesModel; + const billingAndUsageOrder = preferenceValueWithoutUpdatesModel; + const billingAndUsageInvoices = preferenceValueWithoutUpdatesModel; + const billingAndUsagePayments = preferenceValueWithoutUpdatesModel; + const billingAndUsageSubscriptionsAndPromoCodes = preferenceValueWithoutUpdatesModel; + const billingAndUsageSpendingAlerts = preferenceValueWithoutUpdatesModel; + const resourceactivityNormal = preferenceValueWithoutUpdatesModel; + const orderingReview = preferenceValueWithoutUpdatesModel; + const orderingApproved = preferenceValueWithoutUpdatesModel; + const orderingApprovedVsi = preferenceValueWithoutUpdatesModel; + const orderingApprovedServer = preferenceValueWithoutUpdatesModel; + const provisioningReloadComplete = preferenceValueWithoutUpdatesModel; + const provisioningCompleteVsi = preferenceValueWithoutUpdatesModel; + const provisioningCompleteServer = preferenceValueWithoutUpdatesModel; + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const createPreferencesParams = { + iamId, + incidentSeverity1, + incidentSeverity2, + incidentSeverity3, + incidentSeverity4, + maintenanceHigh, + maintenanceMedium, + maintenanceLow, + announcementsMajor, + announcementsMinor, + securityNormal, + accountNormal, + billingAndUsageOrder, + billingAndUsageInvoices, + billingAndUsagePayments, + billingAndUsageSubscriptionsAndPromoCodes, + billingAndUsageSpendingAlerts, + resourceactivityNormal, + orderingReview, + orderingApproved, + orderingApprovedVsi, + orderingApprovedServer, + provisioningReloadComplete, + provisioningCompleteVsi, + provisioningCompleteServer, + accountId, + }; + + const createPreferencesResult = platformNotificationsService.createPreferences(createPreferencesParams); + + // all methods should return a Promise + expectToBePromise(createPreferencesResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/notifications/{iam_id}/preferences', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.incident_severity1).toEqual(incidentSeverity1); + expect(mockRequestOptions.body.incident_severity2).toEqual(incidentSeverity2); + expect(mockRequestOptions.body.incident_severity3).toEqual(incidentSeverity3); + expect(mockRequestOptions.body.incident_severity4).toEqual(incidentSeverity4); + expect(mockRequestOptions.body.maintenance_high).toEqual(maintenanceHigh); + expect(mockRequestOptions.body.maintenance_medium).toEqual(maintenanceMedium); + expect(mockRequestOptions.body.maintenance_low).toEqual(maintenanceLow); + expect(mockRequestOptions.body.announcements_major).toEqual(announcementsMajor); + expect(mockRequestOptions.body.announcements_minor).toEqual(announcementsMinor); + expect(mockRequestOptions.body.security_normal).toEqual(securityNormal); + expect(mockRequestOptions.body.account_normal).toEqual(accountNormal); + expect(mockRequestOptions.body.billing_and_usage_order).toEqual(billingAndUsageOrder); + expect(mockRequestOptions.body.billing_and_usage_invoices).toEqual(billingAndUsageInvoices); + expect(mockRequestOptions.body.billing_and_usage_payments).toEqual(billingAndUsagePayments); + expect(mockRequestOptions.body.billing_and_usage_subscriptions_and_promo_codes).toEqual(billingAndUsageSubscriptionsAndPromoCodes); + expect(mockRequestOptions.body.billing_and_usage_spending_alerts).toEqual(billingAndUsageSpendingAlerts); + expect(mockRequestOptions.body.resourceactivity_normal).toEqual(resourceactivityNormal); + expect(mockRequestOptions.body.ordering_review).toEqual(orderingReview); + expect(mockRequestOptions.body.ordering_approved).toEqual(orderingApproved); + expect(mockRequestOptions.body.ordering_approved_vsi).toEqual(orderingApprovedVsi); + expect(mockRequestOptions.body.ordering_approved_server).toEqual(orderingApprovedServer); + expect(mockRequestOptions.body.provisioning_reload_complete).toEqual(provisioningReloadComplete); + expect(mockRequestOptions.body.provisioning_complete_vsi).toEqual(provisioningCompleteVsi); + expect(mockRequestOptions.body.provisioning_complete_server).toEqual(provisioningCompleteServer); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + expect(mockRequestOptions.path.iam_id).toEqual(iamId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createPreferencesTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __createPreferencesTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __createPreferencesTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const iamId = 'IBMid-1234567890'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createPreferencesParams = { + iamId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.createPreferences(createPreferencesParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.createPreferences({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.createPreferences(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getPreferences', () => { + describe('positive tests', () => { + function __getPreferencesTest() { + // Construct the params object for operation getPreferences + const iamId = 'IBMid-1234567890'; + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const getPreferencesParams = { + iamId, + accountId, + }; + + const getPreferencesResult = platformNotificationsService.getPreferences(getPreferencesParams); + + // all methods should return a Promise + expectToBePromise(getPreferencesResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/notifications/{iam_id}/preferences', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + expect(mockRequestOptions.path.iam_id).toEqual(iamId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getPreferencesTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __getPreferencesTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __getPreferencesTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const iamId = 'IBMid-1234567890'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getPreferencesParams = { + iamId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.getPreferences(getPreferencesParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.getPreferences({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.getPreferences(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('replaceNotificationPreferences', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // PreferenceValueWithUpdates + const preferenceValueWithUpdatesModel = { + channels: ['email'], + updates: true, + }; + + // PreferenceValueWithoutUpdates + const preferenceValueWithoutUpdatesModel = { + channels: ['email'], + }; + + function __replaceNotificationPreferencesTest() { + // Construct the params object for operation replaceNotificationPreferences + const iamId = 'IBMid-1234567890'; + const incidentSeverity1 = preferenceValueWithUpdatesModel; + const incidentSeverity2 = preferenceValueWithUpdatesModel; + const incidentSeverity3 = preferenceValueWithUpdatesModel; + const incidentSeverity4 = preferenceValueWithUpdatesModel; + const maintenanceHigh = preferenceValueWithUpdatesModel; + const maintenanceMedium = preferenceValueWithUpdatesModel; + const maintenanceLow = preferenceValueWithUpdatesModel; + const announcementsMajor = preferenceValueWithoutUpdatesModel; + const announcementsMinor = preferenceValueWithoutUpdatesModel; + const securityNormal = preferenceValueWithoutUpdatesModel; + const accountNormal = preferenceValueWithoutUpdatesModel; + const billingAndUsageOrder = preferenceValueWithoutUpdatesModel; + const billingAndUsageInvoices = preferenceValueWithoutUpdatesModel; + const billingAndUsagePayments = preferenceValueWithoutUpdatesModel; + const billingAndUsageSubscriptionsAndPromoCodes = preferenceValueWithoutUpdatesModel; + const billingAndUsageSpendingAlerts = preferenceValueWithoutUpdatesModel; + const resourceactivityNormal = preferenceValueWithoutUpdatesModel; + const orderingReview = preferenceValueWithoutUpdatesModel; + const orderingApproved = preferenceValueWithoutUpdatesModel; + const orderingApprovedVsi = preferenceValueWithoutUpdatesModel; + const orderingApprovedServer = preferenceValueWithoutUpdatesModel; + const provisioningReloadComplete = preferenceValueWithoutUpdatesModel; + const provisioningCompleteVsi = preferenceValueWithoutUpdatesModel; + const provisioningCompleteServer = preferenceValueWithoutUpdatesModel; + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const replaceNotificationPreferencesParams = { + iamId, + incidentSeverity1, + incidentSeverity2, + incidentSeverity3, + incidentSeverity4, + maintenanceHigh, + maintenanceMedium, + maintenanceLow, + announcementsMajor, + announcementsMinor, + securityNormal, + accountNormal, + billingAndUsageOrder, + billingAndUsageInvoices, + billingAndUsagePayments, + billingAndUsageSubscriptionsAndPromoCodes, + billingAndUsageSpendingAlerts, + resourceactivityNormal, + orderingReview, + orderingApproved, + orderingApprovedVsi, + orderingApprovedServer, + provisioningReloadComplete, + provisioningCompleteVsi, + provisioningCompleteServer, + accountId, + }; + + const replaceNotificationPreferencesResult = platformNotificationsService.replaceNotificationPreferences(replaceNotificationPreferencesParams); + + // all methods should return a Promise + expectToBePromise(replaceNotificationPreferencesResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/notifications/{iam_id}/preferences', 'PUT'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.incident_severity1).toEqual(incidentSeverity1); + expect(mockRequestOptions.body.incident_severity2).toEqual(incidentSeverity2); + expect(mockRequestOptions.body.incident_severity3).toEqual(incidentSeverity3); + expect(mockRequestOptions.body.incident_severity4).toEqual(incidentSeverity4); + expect(mockRequestOptions.body.maintenance_high).toEqual(maintenanceHigh); + expect(mockRequestOptions.body.maintenance_medium).toEqual(maintenanceMedium); + expect(mockRequestOptions.body.maintenance_low).toEqual(maintenanceLow); + expect(mockRequestOptions.body.announcements_major).toEqual(announcementsMajor); + expect(mockRequestOptions.body.announcements_minor).toEqual(announcementsMinor); + expect(mockRequestOptions.body.security_normal).toEqual(securityNormal); + expect(mockRequestOptions.body.account_normal).toEqual(accountNormal); + expect(mockRequestOptions.body.billing_and_usage_order).toEqual(billingAndUsageOrder); + expect(mockRequestOptions.body.billing_and_usage_invoices).toEqual(billingAndUsageInvoices); + expect(mockRequestOptions.body.billing_and_usage_payments).toEqual(billingAndUsagePayments); + expect(mockRequestOptions.body.billing_and_usage_subscriptions_and_promo_codes).toEqual(billingAndUsageSubscriptionsAndPromoCodes); + expect(mockRequestOptions.body.billing_and_usage_spending_alerts).toEqual(billingAndUsageSpendingAlerts); + expect(mockRequestOptions.body.resourceactivity_normal).toEqual(resourceactivityNormal); + expect(mockRequestOptions.body.ordering_review).toEqual(orderingReview); + expect(mockRequestOptions.body.ordering_approved).toEqual(orderingApproved); + expect(mockRequestOptions.body.ordering_approved_vsi).toEqual(orderingApprovedVsi); + expect(mockRequestOptions.body.ordering_approved_server).toEqual(orderingApprovedServer); + expect(mockRequestOptions.body.provisioning_reload_complete).toEqual(provisioningReloadComplete); + expect(mockRequestOptions.body.provisioning_complete_vsi).toEqual(provisioningCompleteVsi); + expect(mockRequestOptions.body.provisioning_complete_server).toEqual(provisioningCompleteServer); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + expect(mockRequestOptions.path.iam_id).toEqual(iamId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __replaceNotificationPreferencesTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __replaceNotificationPreferencesTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __replaceNotificationPreferencesTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const iamId = 'IBMid-1234567890'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const replaceNotificationPreferencesParams = { + iamId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.replaceNotificationPreferences(replaceNotificationPreferencesParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.replaceNotificationPreferences({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.replaceNotificationPreferences(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteNotificationPreferences', () => { + describe('positive tests', () => { + function __deleteNotificationPreferencesTest() { + // Construct the params object for operation deleteNotificationPreferences + const iamId = 'IBMid-1234567890'; + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const deleteNotificationPreferencesParams = { + iamId, + accountId, + }; + + const deleteNotificationPreferencesResult = platformNotificationsService.deleteNotificationPreferences(deleteNotificationPreferencesParams); + + // all methods should return a Promise + expectToBePromise(deleteNotificationPreferencesResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/notifications/{iam_id}/preferences', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + expect(mockRequestOptions.path.iam_id).toEqual(iamId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteNotificationPreferencesTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __deleteNotificationPreferencesTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __deleteNotificationPreferencesTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const iamId = 'IBMid-1234567890'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteNotificationPreferencesParams = { + iamId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.deleteNotificationPreferences(deleteNotificationPreferencesParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.deleteNotificationPreferences({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.deleteNotificationPreferences(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('listNotifications', () => { + describe('positive tests', () => { + function __listNotificationsTest() { + // Construct the params object for operation listNotifications + const accountId = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; + const start = '3fe78a36b9aa7f26'; + const limit = 50; + const listNotificationsParams = { + accountId, + start, + limit, + }; + + const listNotificationsResult = platformNotificationsService.listNotifications(listNotificationsParams); + + // all methods should return a Promise + expectToBePromise(listNotificationsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/notifications', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + expect(mockRequestOptions.qs.start).toEqual(start); + expect(mockRequestOptions.qs.limit).toEqual(limit); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listNotificationsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __listNotificationsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __listNotificationsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listNotificationsParams = { + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.listNotifications(listNotificationsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + + test('should not have any problems when no parameters are passed in', () => { + // invoke the method with no parameters + platformNotificationsService.listNotifications({}); + checkForSuccessfulExecution(createRequestMock); + }); + }); + + describe('NotificationsPager tests', () => { + const serviceUrl = platformNotificationsServiceOptions.url; + const path = '/v1/notifications'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"total_count":2,"limit":1,"notifications":[{"title":"System Maintenance Scheduled","body":"Scheduled maintenance will occur on March 15th from 10:00 AM to 11:00 AM UTC.","id":"12345","category":"maintenance","component_names":["component_names"],"start_time":1771791490,"is_global":false,"state":"new","regions":["regions"],"crn_masks":["crn_masks"],"record_id":"rec-67890","source_id":"src-11111","completion_code":"successful","end_time":1771791490,"update_time":1771791490,"severity":2,"lucene_query":"region:us-south AND service_name:event-notifications","resource_link":"https://cloud.ibm.com/status/incident/12345"}]}'; + const mockPagerResponse2 = + '{"total_count":2,"limit":1,"notifications":[{"title":"System Maintenance Scheduled","body":"Scheduled maintenance will occur on March 15th from 10:00 AM to 11:00 AM UTC.","id":"12345","category":"maintenance","component_names":["component_names"],"start_time":1771791490,"is_global":false,"state":"new","regions":["regions"],"crn_masks":["crn_masks"],"record_id":"rec-67890","source_id":"src-11111","completion_code":"successful","end_time":1771791490,"update_time":1771791490,"severity":2,"lucene_query":"region:us-south AND service_name:event-notifications","resource_link":"https://cloud.ibm.com/status/incident/12345"}]}'; + + beforeEach(() => { + unmock_createRequest(); + const scope = nock(serviceUrl) + .get((uri) => uri.includes(path)) + .reply(200, mockPagerResponse1) + .get((uri) => uri.includes(path)) + .reply(200, mockPagerResponse2); + }); + + afterEach(() => { + nock.cleanAll(); + mock_createRequest(); + }); + + test('getNext()', async () => { + const params = { + accountId: 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6', + limit: 50, + }; + const allResults = []; + const pager = new PlatformNotificationsV1.NotificationsPager(platformNotificationsService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + + test('getAll()', async () => { + const params = { + accountId: 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6', + limit: 50, + }; + const pager = new PlatformNotificationsV1.NotificationsPager(platformNotificationsService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('getAcknowledgement', () => { + describe('positive tests', () => { + function __getAcknowledgementTest() { + // Construct the params object for operation getAcknowledgement + const accountId = '1369339417d906e5620b8d861d40cfd7'; + const getAcknowledgementParams = { + accountId, + }; + + const getAcknowledgementResult = platformNotificationsService.getAcknowledgement(getAcknowledgementParams); + + // all methods should return a Promise + expectToBePromise(getAcknowledgementResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/notifications/acknowledgement', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getAcknowledgementTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __getAcknowledgementTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __getAcknowledgementTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getAcknowledgementParams = { + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.getAcknowledgement(getAcknowledgementParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + + test('should not have any problems when no parameters are passed in', () => { + // invoke the method with no parameters + platformNotificationsService.getAcknowledgement({}); + checkForSuccessfulExecution(createRequestMock); + }); + }); + }); + + describe('replaceNotificationAcknowledgement', () => { + describe('positive tests', () => { + function __replaceNotificationAcknowledgementTest() { + // Construct the params object for operation replaceNotificationAcknowledgement + const lastAcknowledgedId = '1772804159452'; + const accountId = '1369339417d906e5620b8d861d40cfd7'; + const replaceNotificationAcknowledgementParams = { + lastAcknowledgedId, + accountId, + }; + + const replaceNotificationAcknowledgementResult = platformNotificationsService.replaceNotificationAcknowledgement(replaceNotificationAcknowledgementParams); + + // all methods should return a Promise + expectToBePromise(replaceNotificationAcknowledgementResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/notifications/acknowledgement', 'PUT'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.last_acknowledged_id).toEqual(lastAcknowledgedId); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __replaceNotificationAcknowledgementTest(); + + // enable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.enableRetries(); + __replaceNotificationAcknowledgementTest(); + + // disable retries and test again + createRequestMock.mockClear(); + platformNotificationsService.disableRetries(); + __replaceNotificationAcknowledgementTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const lastAcknowledgedId = '1772804159452'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const replaceNotificationAcknowledgementParams = { + lastAcknowledgedId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + platformNotificationsService.replaceNotificationAcknowledgement(replaceNotificationAcknowledgementParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await platformNotificationsService.replaceNotificationAcknowledgement({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await platformNotificationsService.replaceNotificationAcknowledgement(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); +});