Skip to content

Commit 09e2050

Browse files
authored
fix(client): retry a failed current user fetch, plugin hook errors, cloneWithPrefix() (#650)
* fix(client): don't cache a failed current user fetch, and fix cloneWithPrefix() * fix(plugins): await the OAuth 1.0a request token hook, catch the OAuth 2.0 one
1 parent e7264ee commit 09e2050

5 files changed

Lines changed: 118 additions & 10 deletions

File tree

‎doc/plugins.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,9 @@ interface ITwitterApiClientPlugin {
3737
/* Executed when a stream request is about to be prepared. This method **can't** return a `Promise`. */
3838
onBeforeStreamRequestConfig?: TTwitterApiBeforeStreamRequestConfigHook
3939
// Request token
40-
/* Executed after a `.generateAuthLink`, mainly to allow automatic collect of `oauth_token`/`oauth_token_secret` couples. */
40+
/* Executed after a `.generateAuthLink`, mainly to allow automatic collect of `oauth_token`/`oauth_token_secret` couples. `.generateAuthLink` waits for it, and rejects if it fails. */
4141
onOAuth1RequestToken?: TTwitterApiAfterOAuth1RequestTokenHook
42-
/* Executed after a `.generateOAuth2AuthLink`, mainly to allow automatic collect of `state`/`codeVerifier` couples. */
42+
/* Executed after a `.generateOAuth2AuthLink`, mainly to allow automatic collect of `state`/`codeVerifier` couples. `.generateOAuth2AuthLink` is sync: it doesn't wait for a returned `Promise`, and only logs an error of the hook with `TwitterApiV2Settings.logger`. */
4343
onOAuth2RequestToken?: TTwitterApiAfterOAuth2RequestTokenHook
4444
}
4545
```

‎src/client.base.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ export default abstract class TwitterApiBase {
9292
}
9393

9494
public cloneWithPrefix(prefix: string): this {
95-
const clone = (this.constructor as any)(this);
95+
const clone = new (this.constructor as any)(this);
9696
(clone as TwitterApiBase).setPrefix(prefix);
9797

9898
return clone;
@@ -163,13 +163,19 @@ export default abstract class TwitterApiBase {
163163
return this._currentUser.promise;
164164
}
165165

166-
this._currentUser = sharedPromise(() => this.get<UserV1>(
166+
const currentUser = this._currentUser = sharedPromise(() => this.get<UserV1>(
167167
'account/verify_credentials.json',
168168
{ tweet_mode: 'extended' },
169169
{ prefix: API_V1_1_PREFIX },
170170
));
171+
// Don't cache a failure, so that the next call retries
172+
currentUser.promise.catch(() => {
173+
if (this._currentUser === currentUser) {
174+
this._currentUser = null;
175+
}
176+
});
171177

172-
return this._currentUser.promise;
178+
return currentUser.promise;
173179
}
174180

175181
/**
@@ -188,9 +194,15 @@ export default abstract class TwitterApiBase {
188194
return this._currentUserV2.promise;
189195
}
190196

191-
this._currentUserV2 = sharedPromise(() => this.get<UserV2Result>('users/me', undefined, { prefix: API_V2_PREFIX }));
197+
const currentUser = this._currentUserV2 = sharedPromise(() => this.get<UserV2Result>('users/me', undefined, { prefix: API_V2_PREFIX }));
198+
// Don't cache a failure, so that the next call retries
199+
currentUser.promise.catch(() => {
200+
if (this._currentUserV2 === currentUser) {
201+
this._currentUserV2 = null;
202+
}
203+
});
192204

193-
return this._currentUserV2.promise;
205+
return currentUser.promise;
194206
}
195207

196208
/* Direct HTTP methods */

‎src/client/readonly.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import TwitterApiv1ReadOnly from '../v1/client.v1.read';
1414
import TwitterApiv2ReadOnly from '../v2/client.v2.read';
1515
import { OAuth2Helper } from '../client-mixins/oauth2.helper';
1616
import RequestParamHelpers from '../client-mixins/request-param.helper';
17+
import { TwitterApiV2Settings } from '../settings';
1718

1819
/**
1920
* Twitter v1.1 and v2 API client.
@@ -112,7 +113,7 @@ export default class TwitterApiReadOnly extends TwitterApiBase {
112113
}
113114

114115
if (this._requestMaker.hasPlugins()) {
115-
this._requestMaker.applyPluginMethod('onOAuth1RequestToken', {
116+
await this._requestMaker.applyPluginMethod('onOAuth1RequestToken', {
116117
client: this._requestMaker,
117118
url,
118119
oauthResult,
@@ -256,11 +257,12 @@ export default class TwitterApiReadOnly extends TwitterApiBase {
256257
};
257258

258259
if (this._requestMaker.hasPlugins()) {
260+
// This method is sync, so it can't wait for the hooks: log their errors instead of leaving an unhandled rejection
259261
this._requestMaker.applyPluginMethod('onOAuth2RequestToken', {
260262
client: this._requestMaker,
261263
result,
262264
redirectUri,
263-
});
265+
}).catch(error => TwitterApiV2Settings.logger.log('onOAuth2RequestToken plugin hook failed:', error));
264266
}
265267

266268
return result;

‎test/client.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import 'mocha';
2+
import { expect } from 'chai';
3+
import { ApiResponseError, TwitterApiv2 } from '../src';
4+
import { FakeX } from './fake-x';
5+
6+
const me = { id: '12', name: 'Jack', username: 'jack' };
7+
8+
describe('Client (offline: a fake X answers)', () => {
9+
let x: FakeX;
10+
11+
before(async () => {
12+
x = await FakeX.start();
13+
});
14+
15+
after(() => x.close());
16+
17+
beforeEach(() => x.reset());
18+
19+
describe('Current user cache', () => {
20+
it('Should cache the current user, with one request for two calls', async () => {
21+
x.on('GET', '/2/users/me', { body: { data: me } });
22+
const client = x.client();
23+
24+
expect(await client.currentUserV2()).to.deep.equal({ data: me });
25+
expect(await client.currentUserV2()).to.deep.equal({ data: me });
26+
expect(x.requests).to.have.length(1);
27+
});
28+
29+
it('Should not cache a failure, so that the next call retries', async () => {
30+
x.on('GET', '/2/users/me', { status: 503, body: { title: 'Service Unavailable', type: 'about:blank', status: 503, detail: 'Service Unavailable' } });
31+
const client = x.client();
32+
33+
const error = await client.v2.bookmark('20').then(() => null, (e: Error) => e);
34+
expect(error).to.be.instanceOf(ApiResponseError);
35+
expect((error as ApiResponseError).code).to.equal(503);
36+
37+
x.on('GET', '/2/users/me', { body: { data: me } });
38+
await client.v2.bookmark('20');
39+
40+
expect(x.requests.map(({ method, url }) => `${method} ${url.pathname}`)).to.deep.equal([
41+
'GET /2/users/me',
42+
'GET /2/users/me',
43+
'POST /2/users/12/bookmarks',
44+
]);
45+
});
46+
});
47+
48+
it('cloneWithPrefix() should send the requests of the clone to the new prefix', async () => {
49+
x.on('GET', '/2/users/me', { body: { data: me } });
50+
const client = x.client();
51+
52+
const clone = client.v2.cloneWithPrefix('https://api.twitter.com/2/');
53+
expect(clone).to.be.instanceOf(TwitterApiv2);
54+
55+
await clone.me();
56+
await client.v2.me();
57+
58+
expect(x.requests.map(({ url }) => url.href)).to.deep.equal([
59+
'https://api.twitter.com/2/users/me',
60+
'https://api.x.com/2/users/me',
61+
]);
62+
});
63+
});

‎test/plugin.test.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type {
77
ITwitterApiAfterRequestHookArgs,
88
ITwitterApiAfterOAuth1RequestTokenHookArgs,
99
} from '../src';
10-
import { TwitterApi } from '../src';
10+
import { TwitterApi, TwitterApiV2Settings } from '../src';
1111
import { FakeX } from './fake-x';
1212

1313
const consumerKeys = { appKey: FakeX.userKeys.appKey, appSecret: FakeX.userKeys.appSecret };
@@ -94,4 +94,35 @@ describe('Plugin API (offline: a fake X answers)', () => {
9494
// const { client: loggedClient, accessToken, accessSecret } = await loginPlugin.login(oauth_token, 'xxxxxxxx');
9595
// - Save accessToken, accessSecret to persistent storage
9696
});
97+
98+
it('Wait for the OAuth 1.0a request token hook, and reject with its error', async () => {
99+
x.on('POST', '/oauth/request_token', { body: 'oauth_token=request-token&oauth_token_secret=request-secret&oauth_callback_confirmed=true' });
100+
const client = x.client(consumerKeys, {
101+
plugins: [{ onOAuth1RequestToken: async () => { throw new Error('session store down'); } }],
102+
});
103+
104+
const error = await client.generateAuthLink('oob').then(() => null, (e: Error) => e);
105+
106+
expect(error?.message).to.equal('session store down');
107+
});
108+
109+
it('Log the error of an OAuth 2.0 request token hook, as the auth link is returned without waiting for it', async () => {
110+
const client = x.client({ clientId: 'client-id' }, {
111+
plugins: [{ onOAuth2RequestToken: async () => { throw new Error('session store down'); } }],
112+
});
113+
const logger = TwitterApiV2Settings.logger;
114+
const logs: any[][] = [];
115+
TwitterApiV2Settings.logger = { log: (...args: any[]) => logs.push(args) };
116+
117+
try {
118+
const { url } = client.generateOAuth2AuthLink('https://example.com/callback', { scope: ['tweet.read'] });
119+
await new Promise(resolve => setImmediate(resolve));
120+
121+
expect(url).to.match(/^https:\/\/x\.com\/i\/oauth2\/authorize\?/);
122+
expect(logs).to.have.length(1);
123+
expect(logs[0][1].message).to.equal('session store down');
124+
} finally {
125+
TwitterApiV2Settings.logger = logger;
126+
}
127+
});
97128
});

0 commit comments

Comments
 (0)