Created
April 1, 2021 01:23
-
-
Save goleary/0810370f9ad4a0f218b9d94efcb75c97 to your computer and use it in GitHub Desktop.
twitter-api-client search v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios, { AxiosInstance } from 'axios'; | |
import { TwitterClient as TwitterClientV1, Search } from 'twitter-api-client'; | |
type V2SearchParams = { | |
query: string; | |
fields?: string[]; | |
}; | |
export type Status = { | |
text: string; | |
id: string; | |
created_at: string; | |
author_id: string; | |
entities: Search['statuses'][0]['entities']; | |
}; | |
class TwitterClient { | |
private client: AxiosInstance; | |
v1: TwitterClientV1; | |
constructor() { | |
this.client = axios.create({ | |
baseURL: 'https://api.twitter.com/2/', | |
timeout: 2000, | |
headers: { Authorization: `Bearer ${process.env.BEARER_TOKEN}` }, | |
}); | |
this.v1 = new TwitterClientV1({ | |
apiKey: process.env.API_KEY, | |
apiSecret: process.env.API_KEY_SECRET, | |
accessToken: process.env.ACCESS_TOKEN, | |
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET, | |
}); | |
} | |
async search({ query, fields = ['entities', 'created_at'] }: V2SearchParams): Promise<Status[]> { | |
const params = { | |
query, | |
['tweet.fields']: fields.join(','), | |
}; | |
const { data } = await this.client.get('/tweets/search/recent', { params }); | |
return data.data; | |
} | |
} | |
export const twitterClient = new TwitterClient(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment