Git Product home page Git Product logo

aio-lib-events's Introduction

Version Downloads/week Build Status License Greenkeeper badge Codecov Coverage

Adobe I/O Events Lib

Installing

$ npm install @adobe/aio-lib-events

Usage

  1. Initialize the SDK
const sdk = require('@adobe/aio-lib-events')

async function sdkTest() {
  //initialize sdk
  const client = await sdk.init('<organization id>', 'x-api-key', '<valid auth token>', '<options>')
}
  1. Call methods using the initialized SDK
const sdk = require('@adobe/aio-lib-events')

async function sdkTest() {
  // initialize sdk
  const client = await sdk.init('<organization id>', 'x-api-key', '<valid auth token>', '<options>')

  // call methods
  try {
    // get profiles by custom filters
    const result = await client.getSomething({})
    console.log(result)

  } catch (e) {
    console.error(e)
  }
}
  1. Using the poller for journalling
const sdk = require('@adobe/aio-lib-events')

async function sdkTest() {
  // initialize sdk
  const client = await sdk.init('<organization id>', 'x-api-key', '<valid auth token>', '<http options>')
  // get the journalling observable
  const journalling = client.getEventsObservableFromJournal('<journal url>', '<journalling options>')
  // call methods
  const subscription = journalling.subscribe({
    next: (v) => console.log(v), // Action to be taken on event
    error: (e) => console.log(e), // Action to be taken on error
    complete: () => console.log('Complete') // Action to be taken on complete
  })
  
  // To stop receiving events from this subscription based on a timeout
  setTimeout(() => subscription.unsubscribe(), <timeout in ms>)
}

One observable can have multiple subscribers. Each subscription can be handled differently. For more details on using the poller for Journalling check getEventsObservableFromJournal

Classes

EventsCoreAPI

This class provides methods to call your Adobe I/O Events APIs. Before calling any method initialize the instance by calling the init method on it with valid values for organizationId, apiKey, accessToken and optional http options such as timeout and max number of retries

Functions

init(organizationId, apiKey, accessToken, [httpOptions])Promise.<EventsCoreAPI>

Returns a Promise that resolves with a new EventsCoreAPI object.

Typedefs

EventsCoreAPIOptions : object
ProviderFilterOptions : object
ProviderOptions : object
ProviderInputModel : object
EventMetadataInputModel : object
EventsOfInterest : object
RegistrationCreateModel : object
RegistrationUpdateModel : object
Page : object
EventsJournalOptions : object
EventsJournalPollingOptions : object

EventsCoreAPI

This class provides methods to call your Adobe I/O Events APIs. Before calling any method initialize the instance by calling the init method on it with valid values for organizationId, apiKey, accessToken and optional http options such as timeout and max number of retries

Kind: global class

eventsCoreAPI.httpOptions

Http options {retries, timeout}

Kind: instance property of EventsCoreAPI

eventsCoreAPI.organizationId

The organization id from your integration

Kind: instance property of EventsCoreAPI

eventsCoreAPI.apiKey

The api key from your integration

Kind: instance property of EventsCoreAPI

eventsCoreAPI.accessToken

The JWT Token for the integration with IO Management API scope

Kind: instance property of EventsCoreAPI

eventsCoreAPI.init(organizationId, apiKey, accessToken, [httpOptions]) ⇒ Promise.<EventsCoreAPI>

Initialize SDK.

Kind: instance method of EventsCoreAPI
Returns: Promise.<EventsCoreAPI> - returns object of the class EventsCoreAPI

Param Type Description
organizationId string The organization id from your integration
apiKey string The api key from your integration
accessToken string JWT Token for the integration with IO Management API scope
[httpOptions] EventsCoreAPIOptions Options to configure API calls

eventsCoreAPI.getAllProviders(consumerOrgId, providerOptions) ⇒ Promise.<object>

Fetch all the providers

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Returns list of providers for the org

Param Type Description
consumerOrgId string Consumer Org Id from the console
providerOptions ProviderOptions Provider options

eventsCoreAPI.getProvider(providerId, [fetchEventMetadata]) ⇒ Promise.<object>

Fetch a provider

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Returns the provider specified by the provider id

Param Type Default Description
providerId string The id that uniquely identifies the provider to be fetched
[fetchEventMetadata] boolean false Set this to true if you want to fetch the associated eventmetadata of the provider

eventsCoreAPI.createProvider(consumerOrgId, projectId, workspaceId, body) ⇒ Promise.<object>

Create a new provider given the provider details

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Returns the details of the provider created

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
body ProviderInputModel Json data that describes the provider

eventsCoreAPI.updateProvider(consumerOrgId, projectId, workspaceId, providerId, body) ⇒ Promise.<object>

Update a provider given the id and provider details

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Returns the details of the provider updated

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
providerId string The id that uniquely identifies the provider to be updated
body ProviderInputModel Json data that describes the provider

eventsCoreAPI.deleteProvider(consumerOrgId, projectId, workspaceId, providerId) ⇒ Promise.<object>

Delete a provider given the id

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Returns an empty object if the deletion was successful

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
providerId string The id that uniquely identifies the provider to be deleted

eventsCoreAPI.getProviderMetadata() ⇒ Promise.<object>

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Returns the list of all entitled provider metadata for the org

eventsCoreAPI.getAllEventMetadataForProvider(providerId) ⇒ Promise.<object>

Get all event metadata for a provider

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - List of all event metadata of the provider

Param Type Description
providerId string The id that uniquely identifies the provider whose event metadata is to be fetched

eventsCoreAPI.getEventMetadataForProvider(providerId, eventCode) ⇒ Promise.<object>

Get an event metadata for given provider and event code

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Event metadata that corresponds to the specified event code

Param Type Description
providerId string The id that uniquely identifies the provider whose event metadata is to be fetched
eventCode string The specific event code for which the details of the event metadata is to be fetched

eventsCoreAPI.createEventMetadataForProvider(consumerOrgId, projectId, workspaceId, providerId, body) ⇒ Promise.<object>

Create an event metadata for a provider

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Details of the event metadata created

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
providerId string provider for which the event metadata is to be added
body EventMetadataInputModel Json data that describes the event metadata

eventsCoreAPI.updateEventMetadataForProvider(consumerOrgId, projectId, workspaceId, providerId, eventCode, body) ⇒ Promise.<object>

Update the event metadata for a provider

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Details of the event metadata updated

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
providerId string provider for which the event metadata is to be updated
eventCode string eventCode of the event metadata to be updated
body EventMetadataInputModel Json data that describes the event metadata

eventsCoreAPI.deleteEventMetadata(consumerOrgId, projectId, workspaceId, providerId, eventCode) ⇒ Promise.<object>

Delete an event metadata of a provider

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Empty object if deletion was successful

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
providerId string provider for which the event metadata is to be updated
eventCode string eventCode of the event metadata to be updated

eventsCoreAPI.deleteAllEventMetadata(consumerOrgId, projectId, workspaceId, providerId) ⇒ Promise.<object>

Delete all event metadata of a provider

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Empty object if deletion was successful

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
providerId string provider for which the event metadata is to be updated

eventsCoreAPI.createRegistration(consumerOrgId, projectId, workspaceId, body) ⇒ Promise.<object>

Create a webhook or journal registration

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Details of the webhook/journal registration created

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
body RegistrationCreateModel Json data contains details of the registration

eventsCoreAPI.updateRegistration(consumerOrgId, projectId, workspaceId, registrationId, body) ⇒ Promise.<object>

Update a webhook or journal registration

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Details of the webhook/journal registration to be updated

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
registrationId string Registration id whose details are to be fetched
body RegistrationUpdateModel Json data contains details of the registration

eventsCoreAPI.getRegistration(consumerOrgId, projectId, workspaceId, registrationId) ⇒ Promise.<object>

Get registration details for a given registration

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Details of the webhook/journal registration

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
registrationId string Registration id whose details are to be fetched

eventsCoreAPI.getAllRegistrationsForWorkspace(consumerOrgId, projectId, workspaceId) ⇒ Promise.<object>

Get all registration details for a workspace

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - List of all webhook/journal registrations

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console

eventsCoreAPI.getAllRegistrationsForOrg(consumerOrgId, [page]) ⇒ Promise.<object>

Get all registration details for an org

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Paginated response of all webhook/journal registrations for an org

Param Type Description
consumerOrgId string Consumer Org Id from the console
[page] Page page size and page number

eventsCoreAPI.deleteRegistration(consumerOrgId, projectId, workspaceId, registrationId) ⇒ Promise.<object>

Delete webhook registration

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - Empty object if deletion was successful

Param Type Description
consumerOrgId string Consumer Org Id from the console
projectId string Project Id from the console
workspaceId string Workspace Id from the console
registrationId string Id of the registration to be deleted

eventsCoreAPI.publishEvent(cloudEvent) ⇒ Promise.<string>

Publish Cloud Events

Event publishers can publish events to the Adobe I/O Events using this SDK. The events should follow Cloud Events 1.0 specification: https://github.com/cloudevents/spec/blob/v1.0/spec.md. As of now, only application/json is accepted as the content-type for the "data" field of the cloud event. If retries are set, publish events are retried on network issues, 5xx and 429 error response codes.

Kind: instance method of EventsCoreAPI
Returns: Promise.<string> - Returns OK/ undefined in case of success and error in case of failure

Param Type Description
cloudEvent object Object to be published to event receiver in cloud event format

eventsCoreAPI.getEventsFromJournal(journalUrl, [eventsJournalOptions], [fetchResponseHeaders]) ⇒ Promise.<object>

Get events from a journal.

Kind: instance method of EventsCoreAPI
Returns: Promise.<object> - with the response json includes events and links (if available)

Param Type Description
journalUrl string URL of the journal or 'next' link to read from (required)
[eventsJournalOptions] EventsJournalOptions Query options to send with the URL
[fetchResponseHeaders] boolean Set this to true if you want to fetch the complete response headers

eventsCoreAPI.getEventsObservableFromJournal(journalUrl, [eventsJournalOptions], [eventsJournalPollingOptions]) ⇒ Observable

getEventsObservableFromJournal returns an RxJS Observable

One can go through the extensive documentation on RxJS in order to learn more and leverage the various RxJS Operators to act on emitted events.

Kind: instance method of EventsCoreAPI
Returns: Observable - observable to which the user can subscribe to in order to listen to events

Param Type Description
journalUrl string URL of the journal or 'next' link to read from (required)
[eventsJournalOptions] EventsJournalOptions Query options to send with the Journal URL
[eventsJournalPollingOptions] EventsJournalPollingOptions Journal polling options

eventsCoreAPI.verifyDigitalSignatureForEvent(event, recipientClientId, signatureOptions) ⇒ boolean

Authenticating events by verifying digital signature

Kind: instance method of EventsCoreAPI
Returns: boolean - If signature matches return true else return false

Param Type Description
event * JSON payload delivered to the registered webhook URL
recipientClientId * Target recipient client id retrieved from the Adobe I/O Console integration
signatureOptions * map of all digital signature header values consisting fields as below digiSignature1 : Value of digital signature retrieved from the x-adobe-digital-signature1 header in each POST request to webhook digiSignature2 : Value of digital signature retrieved from the x-adobe-digital-signature2 header in each POST request to webhook publicKeyPath1 : Relative path of ioevents public key retrieved from the x-adobe-public-key1-path header in each POST request to webhook publicKeyPath2 : Relative path of ioevents public key retrieved from the x-adobe-public-key2-path header in each POST request to webhook

init(organizationId, apiKey, accessToken, [httpOptions]) ⇒ Promise.<EventsCoreAPI>

Returns a Promise that resolves with a new EventsCoreAPI object.

Kind: global function
Returns: Promise.<EventsCoreAPI> - returns object of the class EventsCoreAPI

Param Type Description
organizationId string The organization id from your integration
apiKey string The api key from your integration
accessToken string JWT Token for the integration with IO Management API scope
[httpOptions] EventsCoreAPIOptions Options to configure API calls

EventsCoreAPIOptions : object

Kind: global typedef
Properties

Name Type Description
[timeout] number Http request timeout in ms (optional)
[retries] number Number of retries in case of 5xx errors. Default 0 (optional)
[eventsBaseURL] string Base URL for Events Default https://api.adobe.io (optional)
[eventsIngressURL] string Ingress URL for Events. Default https://eventsingress.adobe.io (optional)

ProviderFilterOptions : object

Kind: global typedef
Properties

Name Type Description
[providerMetadataId] string Fetch by providerMetadataId for the consumer org
[instanceId] string For Self registered providers, instanceId is a must while fetching by providerMetadataId
[providerMetadataIds] Array.<string> Fetch all providers ( and all instances ) for the list of provider metadata ids

ProviderOptions : object

Kind: global typedef
Properties

Name Type Description
fetchEventMetadata boolean Option to fetch event metadata for each of the the providers in the list
filterBy ProviderFilterOptions Provider filtering options based on either (providerMetadataId and instanceId) or list of providerMetadataIds

ProviderInputModel : object

Kind: global typedef
Properties

Name Type Description
label string The label of this Events Provider
[description] string The description of this Events Provider
[docs_url] string The documentation url of this Events Provider

EventMetadataInputModel : object

Kind: global typedef
Properties

Name Type Description
label string The description of this Event Metadata
description string The label of this Event Metadata
event_code string The event_code of this Event Metadata. This event_code describes the type of event. Ideally it should be prefixed with a reverse-DNS name (dictating the organization which defines the semantics of this event type) It is equivalent to the CloudEvents' type. See https://github.com/cloudevents/spec/blob/master/spec.md#type
[sample_event_template] string An optional base64 encoded sample event template

EventsOfInterest : object

Kind: global typedef
Properties

Name Type Description
provider_id string The id of the provider of the events to be subscribed
event_code string The requested valid event code belonging to the provider

RegistrationCreateModel : object

Kind: global typedef
Properties

Name Type Description
client_id string Client id for which the registration is created
name string The name of the registration
description string The description of the registration
[webhook_url] string A valid webhook url where the events would be delivered for webhook or webhook_batch delivery_type
events_of_interest Array.<EventsOfInterest> The events for which the registration is to be subscribed to
delivery_type string Delivery type can either be webhook
[enabled] string Enable or disable the registration. Default true.

RegistrationUpdateModel : object

Kind: global typedef
Properties

Name Type Description
name string The name of the registration
description string The description of the registration
[webhook_url] string A valid webhook url where the events would be delivered for webhook or webhook_batch delivery_type
events_of_interest Array.<EventsOfInterest> The events for which the registration is to be subscribed to
delivery_type string Delivery type can either be webhook
[enabled] string Enable or disable the registration. Default true.

Page : object

Kind: global typedef
Properties

Name Type Description
[page] number page number to be fetched. Default 0 (optional)
[size] number size of each page. Default 10 (optional)

EventsJournalOptions : object

Kind: global typedef
Properties

Name Type Description
[latest] boolean Retrieve latest events (optional)
[since] string Position at which to start fetching the events from (optional)
[limit] number Maximum number of events to retrieve (optional)

EventsJournalPollingOptions : object

Kind: global typedef
Properties

Name Type Description
[interval] number Interval at which to poll the journal; If not provided, a default value will be used (optional)

Debug Logs

LOG_LEVEL=debug <your_call_here>

Prepend the LOG_LEVEL environment variable and debug value to the call that invokes your function, on the command line. This should output a lot of debug data for your SDK calls.

Contributing

Contributions are welcome! Read the Contributing Guide for more information.

Licensing

This project is licensed under the Apache V2 License. See LICENSE for more information.

aio-lib-events's People

Contributors

abhupadh avatar amulyakashyap09 avatar arjuncooliitr avatar dependabot[bot] avatar greenkeeper[bot] avatar himavanth avatar kgera avatar macdonst avatar meryllblanchet avatar michaelgoberling avatar moritzraho avatar nicdard avatar pratyushbanerjee avatar purplecabbage avatar sandeep-paliwal avatar sangeetha5491 avatar shazron avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aio-lib-events's Issues

Erroneous example for `getEventsObservableFromJournal` in README.md

README of the project includes an example for "Using the poller for journalling", which suggests invocation of .unsubscribe on object returned by RxJS' Observable.subscribe's returned by EventsCoreAPI.getEventsObservableFromJournal.

Expected Behaviour

journalling.unsubscribe should stop the stream of events being emitted after the timeout expires.

Actual Behaviour

  setTimeout(() => this.subscription.unsubscribe(), 1000)
                                     ^

TypeError: Cannot read property 'unsubscribe' of undefined
    at Timeout._onTimeout (/Users/ashishc/repo/aio-journal-consumer/journalConsumer.js:20:38)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)

Reproduce Scenario (including but not limited to)

Execution of the sample-code for project README is sufficient to demonstrate the issue.

Steps to Reproduce

"Using the poller for journalling" sample-code from README, set a valid timeout and wait for that duration to pass after invocation of the code.

Platform and Version

macOS 10.15.4
node v13.13.0
npm v6.16.4

Sample Code that illustrates the problem

"Using the poller for journalling" sample-code from README

Logs taken while reproducing problem

N/A

Invalid test for function signatureUtils::getKeyFromCache

Function signatureUtils::getKeyFromCache :

/**
* Gets the public key from cache
*
* @param {*} state aio state lib instance
* @param {*} publicKeyFileNameAsKey public key file name in format pub-key-<random-uuid>.pem
* @returns {string} public key
*/
async function getKeyFromCache (state, publicKeyFileNameAsKey) {
try {
const keyObj = await state.get(publicKeyFileNameAsKey)
/**
* key json obj fetched from cache in below format
* {
* "value":"pem public key",
* "expiration":"24h timestamp"
* }
*/
return keyObj.value
} catch (error) {
logger.error('aio lib state get error due to => %s', error.message)
}
return null
}

On error, the function returns null, and never rethrows an Error.

The test "Test Get Key from Cache -> get key from cache throws" in signatureUtils.test.js is an invalid test since the tested function will never throw an error. In fact the test is bogus - it doesn't really test the return value or catch the function's error - it tests an error that it sets up itself.

The test is here:

describe('Test Get Key from Cache', () => {
it('get key from cache throws', async () => {
await signatureUtils.getKeyFromCache('state', 'invalid-url')
.then(res => {
throw new Error('lib state get error')
})
.catch(e => {
// eslint-disable-next-line jest/no-conditional-expect
expect(e instanceof Error).toBe(true)
// eslint-disable-next-line jest/no-conditional-expect
expect(e.message).toEqual('lib state get error')
})
})

upcoming major version change to @adobe/aio-lib-core-networking

Description

This is to communicate an upcoming major version change to @adobe/aio-lib-core-networking to 2.0.0.
Your @adobe/aio-lib-core-networking version is ^1.0.0 and will not be affected by an npm install unless you manually change it to ^2.0.0

PR for discussion: adobe/aio-lib-core-networking#14

What Changed

The major change to take note if you upgrade, is the export of the library.
In 1.x.x the export of @adobe/aio-lib-core-networking returns an instance of the HttpExponentialBackoff class.
In 2.x.x the export of @adobe/aio-lib-core-networking returns an object, which contains the HttpExponentialBackoff class (which you need to instantiate).

Migration Example

1.x.x:

const fetchRetry = require('@adobe/aio-lib-core-networking')
fetchRetry.exponentialBackoff('http://example.com', {})

2.x.x:

const { HttpExponentialBackoff } = require('@adobe/aio-lib-core-networking')
const fetchRetry = new HttpExponentialBackoff()
fetchRetry.exponentialBackoff('http://example.com', {})

An in-range update of eslint-plugin-jsdoc is breaking the build 🚨


🚨 Reminder! Less than one month left to migrate your repositories over to Snyk before Greenkeeper says goodbye on June 3rd! 💜 🚚💨 💚

Find out how to migrate to Snyk at greenkeeper.io


The devDependency eslint-plugin-jsdoc was updated from 25.2.0 to 25.2.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-jsdoc is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details

Release Notes for v25.2.1

25.2.1 (2020-05-12)

Bug Fixes

  • check-param-names, require-param: check ExperimentalRestProperty from babel-eslint as with RestElement; fixes #536 (d330391)
Commits

The new version differs by 3 commits.

  • d330391 fix(check-param-names, require-param): check ExperimentalRestProperty from babel-eslint as with RestElement; fixes #536
  • aaae00e test(require-jsdoc): show exclusion of constructor
  • 87c6384 chore: bump regextras version

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

fix issues with jest/no-conditional-expect

Search for the text:
eslint-disable-next-line jest/no-conditional-expect

The disabling of these lines were temporary due to the eslint config upgrade. Using conditional expects do hide certain implementation issues or bad/incomplete tests.

index.test.js

  1. Get registration with retries -> Test for retries on 5xx response
  2. Publish event with retries -> Test for retries on 5xx response
  3. Fetch from journalling -> Fetch from journal with retries

signatureUtils.test.js

  1. Test Fetch Key from CloudFront with Invalid Pub Key Url -> verify for invalid pub key
  2. Test Fetch Pem Encoded Public Keys -> verify for invalid pub key url throws
  3. Test Get Key from Cache -> get key from cache throws

See #56, #57, and #58 before updating the tests.

Incorrect implementation and test for function signatureUtils::fetchPublicKeyFromCloudFront

Function signatureUtils::fetchPublicKeyFromCloudFront:

/**
* Fetches public key using the cloud front public key url
*
* @param {*} publicKeyUrl - cloud front public key url of format
* https://static.adobeioevents.com/prod/keys/pub-key-<random-uuid>.pem
* @returns {string} public key
*/
async function fetchPublicKeyFromCloudFront (publicKeyUrl) {
let pubKey
await fetch(publicKeyUrl)
.then(response => response.text())
.then(text => {
logger.info('successfully fetched the public key %s from cloud front url %s', text, publicKeyUrl)
pubKey = text
})
.catch(error => {
logger.error('error fetching the public key from cloud front url %s due to => %s', publicKeyUrl, error.message)
return helpers.exportFunctions.genErrorResponse(500, error.message)
})
return pubKey
}

This is an odd use of both async/await and Promise.then, it works - but can be confusing for devs not used to it.

The then() clause assigns to a variable pubKey, which works in this case because of the await (if not pubKey would always be undefined), but it could just simply be the return value for the then(), and should therefore end up to be the return value of the await.

But the problematic item is the catch() clause. It returns helpers.exportFunctions.genErrorResponse(500, error.message), which has two problems:

  1. Since the return value of the await is not used, this return value will never be used.
  2. helpers.exportFunctions.genErrorResponse returns an object, and this function explicitly says it should return a string in the jsdoc. This is a mismatch.

This therefore renders the test "Test Fetch Key from CloudFront with Invalid Pub Key Url -> verify for invalid pub key" in signatureUtils.test.js as an invalid test since it will never throw an error. In fact the test is bogus (it passes but it is made to pass) - it doesn't really test the (mocked) return value - it tests an error that it sets up itself.

The test is here:

describe('Test Fetch Key from CloudFront with Invalid Pub Key Url', () => {
it('verify for invalid pub key', async () => {
const invalidCloudFrontUrl = undefined
fetch.mockImplementation(() => {
return Promise.resolve(Error)
})
await signatureUtils.fetchPublicKeyFromCloudFront(invalidCloudFrontUrl)
.then(res => {
throw new Error('invalid url')
})
.catch(e => {
// eslint-disable-next-line jest/no-conditional-expect
expect(e instanceof Error).toBe(true)
// eslint-disable-next-line jest/no-conditional-expect
expect(e.message).toEqual('invalid url')
})
})
})

Incorrect implementation and test for function signatureUtils::fetchPemEncodedPublicKeys

Function signatureUtils::fetchPemEncodedPublicKeys :

/**
* Feteched the pem encoded public keys either from the state lib cache or directly via cloud front url
*
* @param {*} pubKeyUrl1 cloud front url of format https://static.adobeioevents.com/prod/keys/pub-key-<random-uuid>.pem
* @param {*} pubKeyUrl2 cloud front url of format https://static.adobeioevents.com/prod/keys/pub-key-<random-uuid>.pem
* @returns {Array} of two public keys
*/
async function fetchPemEncodedPublicKeys (pubKeyUrl1, pubKeyUrl2) {
let pubKey1Pem, pubKey2Pem
try {
const state = await stateLib.init()
pubKey1Pem = await fetchPubKeyFromCacheOrApi(pubKeyUrl1, state)
pubKey2Pem = await fetchPubKeyFromCacheOrApi(pubKeyUrl2, state)
} catch (error) {
logger.error('error occurred while fetching pem encoded public keys either from cache or public key urls due to %s', error.message)
return helpers.exportFunctions.genErrorResponse(500, 'Error occurred while fetching pem encoded Public Key')
}
return [pubKey1Pem, pubKey2Pem]
}

The problematic item is the catch() clause. It returns helpers.exportFunctions.genErrorResponse(500, 'Error occurred while fetching pem encoded Public Key'), which has a problem:

  1. helpers.exportFunctions.genErrorResponse returns an object, and this function explicitly says it should return an Array of (two) strings (tuple).

This therefore renders the test "Test Fetch Pem Encoded Public Keys -> verify for invalid pub key url throws" in signatureUtils.test.js as an invalid test since it will never throw an error. In fact the test is bogus - it doesn't really test the (mocked) return value - it tests an error that it sets up itself.

The test is here:

describe('Test Fetch Pem Encoded Public Keys', () => {
it('verify for invalid pub key url throws', async () => {
const invalidCloudFrontUrl = undefined
fetch.mockImplementation(() => {
return Promise.resolve(Error)
})
await signatureUtils.fetchPemEncodedPublicKeys(invalidCloudFrontUrl)
.then(res => {
throw new Error('invalid url')
})
.catch(e => {
// eslint-disable-next-line jest/no-conditional-expect
expect(e instanceof Error).toBe(true)
// eslint-disable-next-line jest/no-conditional-expect
expect(e.message).toEqual('invalid url')
})
})
})

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.