Skip to content

Commit

Permalink
fix: get access token before calling traditional API
Browse files Browse the repository at this point in the history
  • Loading branch information
dantio committed Dec 2, 2022
1 parent ee74317 commit a4a3123
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 18 deletions.
14 changes: 14 additions & 0 deletions examples/traditional/trading.GetSingleItem.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// tslint:disable:no-console
import eBayApi from '../../src';

const eBay = eBayApi.fromEnv();

eBay.shopping.GetSingleItem({
ItemID: '255734197431',
IncludeSelector: 'Details'
}).then(result => {
console.log(JSON.stringify(result, null, 2));
}).catch(e => {
console.error(e);
});

26 changes: 12 additions & 14 deletions src/api/traditional/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default class Traditional extends Api {
},
calls: TradingCalls,
xmlns: 'urn:ebay:apis:eBLBaseComponents',
headers: (callName: string, accessToken?: string) => ({
headers: (callName: string, accessToken?: string | null) => ({
'X-EBAY-API-CALL-NAME': callName,
'X-EBAY-API-CERT-NAME': this.config.certId,
'X-EBAY-API-APP-NAME': this.config.appId,
Expand All @@ -53,9 +53,9 @@ export default class Traditional extends Api {
},
xmlns: 'urn:ebay:apis:eBLBaseComponents',
calls: ShoppingCalls,
headers: (callName: string, accessToken?: string) => ({
headers: (callName: string, accessToken?: string | null) => ({
'X-EBAY-API-CALL-NAME': callName,
// 'X-EBAY-API-APP-ID': this.config.appId, deprecated on June 30, 2021
// 'X-EBAY-API-APP-ID': this.config.appId, deprecated on June 30, 2021
'X-EBAY-API-SITE-ID': this.config.siteId,
'X-EBAY-API-VERSION': 863,
'X-EBAY-API-REQUEST-ENCODING': 'xml',
Expand Down Expand Up @@ -137,7 +137,7 @@ export default class Traditional extends Api {
}

public createBusinessPolicyManagementApi() {
throw new Error('Important! This API is deprecated and will be decommissioned on January 31, 2022. We recommend that you migrate to the fulfillment_policy, payment_policy, and return_policy resources of the Account API to set up and manage all of your fulfillment, payment, and return business policies.')
throw new Error('Important! This API is deprecated and will be decommissioned on January 31, 2022. We recommend that you migrate to the fulfillment_policy, payment_policy, and return_policy resources of the Account API to set up and manage all of your fulfillment, payment, and return business policies.');
}

private createXMLRequest = (callName: string, api: TraditionalApi) => async (fields: Fields, opts: TraditionalApiConfig) => {
Expand All @@ -153,39 +153,37 @@ export default class Traditional extends Api {

throw error;
}
}
};

private async request(apiConfig: TraditionalApiConfig, api: TraditionalApi, callName: string, fields: Fields, refreshToken = false) {
try {
if (refreshToken) {
await this.auth.OAuth2.refreshToken();
}

const config = this.getConfig(api, callName, apiConfig);
const config = await this.getConfig(api, callName, apiConfig);
const xmlRequest = new XMLRequest(callName, fields, config, this.req);

return await xmlRequest.request();
} catch (e) {
handleEBayError(e)
handleEBayError(e);
}
}

private getConfig(api: TraditionalApi, callName: string, apiConfig: TraditionalApiConfig) {
private async getConfig(api: TraditionalApi, callName: string, apiConfig: TraditionalApiConfig) {
const eBayAuthToken = this.auth.authNAuth.eBayAuthToken;
const userAccessToken = this.auth.OAuth2.getUserAccessToken();
const useIaf = (!eBayAuthToken || userAccessToken && apiConfig.useIaf);
const accessToken = !eBayAuthToken && apiConfig.useIaf ? (await this.auth.OAuth2.getAccessToken()) : null;
const useIaf = !eBayAuthToken && accessToken;

return {
...apiConfig,
xmlns: api.xmlns,
endpoint: api.endpoint[this.config.sandbox ? 'sandbox' : 'production'],
headers: {
...api.headers(callName, userAccessToken && useIaf ? userAccessToken : undefined),
...api.headers(callName, useIaf ? accessToken : null),
...apiConfig.headers
},
...(eBayAuthToken && !useIaf && {
eBayAuthToken
})
...(!useIaf ? { eBayAuthToken } : {})
};
}

Expand Down
4 changes: 2 additions & 2 deletions src/auth/authNAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default class AuthNAuth extends Base {
].join('');
}

private authToken?: AuthToken;
private authToken: AuthToken | null = null;

constructor(config: AppConfig, req?: IEBayApiRequest) {
super(config, req)
Expand Down Expand Up @@ -101,7 +101,7 @@ export default class AuthNAuth extends Base {
return token;
}

public setAuthToken(authToken: AuthToken | string) {
public setAuthToken(authToken: AuthToken | string | null) {
if (typeof authToken === 'string') {
this.authToken = {
eBayAuthToken: authToken
Expand Down
2 changes: 1 addition & 1 deletion src/types/apiTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export type RestConfig = {

export type TraditionalConfig = {
siteId?: number
authToken?: string
authToken?: string | null
}

export type eBayConfig = Keyset & {
Expand Down
2 changes: 1 addition & 1 deletion src/types/traditonalTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,5 @@ export type TraditionalApi = {
endpoint: Endpoint,
xmlns: string,
calls: typeof TradingCalls | typeof ShoppingCalls | typeof FindingCalls | typeof ClientAlertsCalls | typeof MerchandisingCalls,
headers: (callName: string, accessToken?: string) => object
headers: (callName: string, accessToken?: string | null) => object
};
32 changes: 32 additions & 0 deletions test/api/traditional/traditional.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,37 @@ describe('Traditional', () => {
});
});

it('use Auth Token event if "accessToken" is available', () => {
const post = sinon.stub().returns(Promise.resolve({data: '<GetAccountResponse></GetAccountResponse>'}));
const req: IEBayApiRequest<any> = {
get: sinon.stub(),
delete: sinon.stub(),
put: sinon.stub(),
post,
postForm: sinon.stub(),
instance: sinon.stub()
};
auth.OAuth2.setCredentials({
access_token: 'accessToken',
refresh_token_expires_in: 0,
refresh_token: 'refresh_token',
token_type: 'token_type',
expires_in: 0
});

const traditional = new Traditional(config, req, auth);
const trading = traditional.createTradingApi();
return trading.GetAccount({}, {raw: true}).then(data => {
expect(post.args[0][1]).to.equal([
'<?xml version="1.0" encoding="utf-8"?>',
'<GetAccountRequest xmlns="urn:ebay:apis:eBLBaseComponents">',
'<RequesterCredentials><eBayAuthToken>eBayAuthToken</eBayAuthToken></RequesterCredentials></GetAccountRequest>',
].join(''));
expect(data).to.equal('<GetAccountResponse></GetAccountResponse>');
expect(post.args[0][2].headers['X-EBAY-API-IAF-TOKEN']).to.equal(undefined);
});
});

it('use IAF token if "accessToken" is available', () => {
const post = sinon.stub().returns(Promise.resolve({data: '<GetAccountResponse></GetAccountResponse>'}));
const req: IEBayApiRequest<any> = {
Expand All @@ -79,6 +110,7 @@ describe('Traditional', () => {
expires_in: 0
});

auth.authNAuth.setAuthToken(null);
const traditional = new Traditional(config, req, auth);
const trading = traditional.createTradingApi();
return trading.GetAccount({}, {raw: true}).then(data => {
Expand Down

0 comments on commit a4a3123

Please sign in to comment.