Skip to content

Commit

Permalink
Merge pull request #1185 from contentstack/feat/CS-42859
Browse files Browse the repository at this point in the history
feat: New marketplace sdk adapter added in utility [CS-42859]
  • Loading branch information
antonyagustine authored Nov 29, 2023
2 parents e2d8ef6 + 4c1878b commit 3d0cc7a
Show file tree
Hide file tree
Showing 5 changed files with 165 additions and 3 deletions.
18 changes: 18 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/contentstack-utilities/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"license": "MIT",
"dependencies": {
"@contentstack/management": "~1.12.0",
"@contentstack/marketplace-sdk": "^1.0.0",
"@oclif/core": "^2.9.3",
"axios": "^1.6.0",
"chalk": "^4.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class ManagementSDKInitiator {
retryCondition: (error: any): boolean => {
// LINK https://github.com/contentstack/contentstack-javascript/blob/72fee8ad75ba7d1d5bab8489ebbbbbbaefb1c880/src/core/stack.js#L49
if (error.response && error.response.status) {
switch (error.status) {
switch (error.response.status) {
case 401:
case 429:
case 408:
Expand Down
138 changes: 138 additions & 0 deletions packages/contentstack-utilities/src/contentstack-marketplace-sdk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { Agent } from 'node:https';
import { client, ContentstackConfig, ContentstackClient, ContentstackToken } from '@contentstack/marketplace-sdk';

import authHandler from './auth-handler';
import configStore from './config-handler';

type ConfigType = Pick<ContentstackConfig, 'host' | 'endpoint' | 'retryDelay' | 'retryLimit'> & {
management_token?: string;
skipTokenValidity?: string;
};

class MarketplaceSDKInitiator {
private analyticsInfo: string;

/**
* The function returns a default configuration object for Contentstack API requests in TypeScript.
* @returns a default configuration object of type `ContentstackConfig`.
*/
get defaultOptions(): ContentstackConfig {
return {
headers: {},
retryLimit: 3,
timeout: 60000,
maxRequests: 10,
// host: 'api.contentstack.io',
maxContentLength: 100000000,
maxBodyLength: 1000000000,
httpsAgent: new Agent({
timeout: 60000, // active socket keepalive for 60 seconds
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
}),
retryDelay: Math.floor(Math.random() * (8000 - 3000 + 1) + 3000),
retryCondition: (error: any): boolean => {
if (error?.response?.status) {
switch (error.response.status) {
case 401:
case 429:
case 408:
return true;
default:
return false;
}
}
},
retryDelayOptions: {
base: 1000,
customBackoff: () => 1,
},
};
}

init(context) {
this.analyticsInfo = context?.analyticsInfo;
}

/**
* The function `refreshTokenHandler` returns a promise that resolves with a `ContentstackToken`
* object based on the `authorizationType` parameter.
* @param {string} authorizationType - The `authorizationType` parameter is a string that specifies
* the type of authorization being used. It can have one of the following values:
* @returns The refreshTokenHandler function returns a function that returns a Promise of type
* ContentstackToken.
*/
refreshTokenHandler(authorizationType: string) {
return (): Promise<ContentstackToken> => {
return new Promise((resolve, reject) => {
if (authorizationType === 'BASIC') {
// NOTE Handle basic auth 401 here
reject(new Error('Session timed out, please login to proceed'));
} else if (authorizationType === 'OAUTH') {
authHandler
.compareOAuthExpiry(true)
.then(() => resolve({ authorization: `Bearer ${configStore.get('oauthAccessToken')}` }))
.catch(reject);
} else {
reject(new Error('You do not have permissions to perform this action, please login to proceed'));
}
});
};
}

/**
* The function creates a Contentstack SDK client with the provided configuration.
* @param config - The `config` parameter is an object that contains the following properties:
* @returns a Promise that resolves to a ContentstackClient object.
*/
async createAppSDKClient(config?: ConfigType): Promise<ContentstackClient> {
const authorizationType = configStore.get('authorisationType');

const option = this.defaultOptions;
option.refreshToken = this.refreshTokenHandler(authorizationType);

if (config.host) {
option.host = config.host;
}

if (config.endpoint) {
option.endpoint = config.endpoint;
}

if (config.retryLimit) {
option.retryLimit = config.retryLimit;
}

if (config.retryDelay) {
option.retryDelay = config.retryDelay;
}

if (this.analyticsInfo) {
option.headers['X-CS-CLI'] = this.analyticsInfo;
}

if (!config.management_token) {
option.authtoken = '';
option.authorization = '';

if (authorizationType === 'BASIC') {
option.authtoken = configStore.get('authtoken');
} else if (authorizationType === 'OAUTH') {
if (!config.skipTokenValidity) {
await authHandler.compareOAuthExpiry();
option.authorization = `Bearer ${configStore.get('oauthAccessToken')}`;
}
}
}

return client(option);
}
}

export const marketplaceSDKInitiator = new MarketplaceSDKInitiator();
const marketplaceSDKClient: typeof marketplaceSDKInitiator.createAppSDKClient =
marketplaceSDKInitiator.createAppSDKClient.bind(marketplaceSDKInitiator);
export { MarketplaceSDKInitiator, ContentstackConfig, ContentstackClient };

export default marketplaceSDKClient;
9 changes: 7 additions & 2 deletions packages/contentstack-utilities/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import Logger from './logger'
import Logger from './logger';
import marketplaceSDKClient, { MarketplaceSDKInitiator, marketplaceSDKInitiator } from './contentstack-marketplace-sdk';

export { LoggerService } from './logger';
export { default as cliux } from './cli-ux';
export { default as CLIError } from './cli-error';
Expand All @@ -21,6 +23,9 @@ export * from './interfaces';
export * from './date-time';
export * from './add-locale';

// Marketplace SDK export
export { marketplaceSDKClient, MarketplaceSDKInitiator, marketplaceSDKInitiator };

// NOTE Exporting all @oclif/core modules: So that all the module can be acessed through cli-utility
export {
Args,
Expand Down Expand Up @@ -55,4 +60,4 @@ export { FlagInput, ArgInput } from '@oclif/core/lib/interfaces/parser';

export { default as TablePrompt } from './inquirer-table-prompt';

export { Logger };
export { Logger };

0 comments on commit 3d0cc7a

Please sign in to comment.