import axios , { AxiosRequestConfig } from 'axios' ; export type Tweet = { id : string ; text : string ; author_id : string ; created_at : string ; attachments ? : { media_keys : string [ ] ; } ; public_metrics : TwitterPublicMetrics ; } ; export type TwitterPublicMetrics = { retweet_count : number ; reply_count : number ; like_count : number ; quote_count : number ; } ; export type TwitterUser = { username : string ; profile_image_url : string ; id : string ; name : string ; } ; type TwitterMedia = { type ? : 'photo' | 'animated_gif' ; media_key ? : string ; preview_image_url ? : string ; url ? : string ; } ; export type TwitterUserResponse = { data : TwitterUser ; } ; export type TwitterTimelineResponse = { data : Tweet [ ] ; meta : { oldest_id : string ; newest_id : string ; result_count : number ; nextToken : string ; } ; includes ? : { media ? : TwitterMedia [ ] ; } ; } ; export class TwitterService { private _bearerToken = process . env . TWITTER_BEARER_TOKEN ; private _http = axios . create ( ) ; public constructor ( ) { this . _http . interceptors . request . use ( ( config ) : AxiosRequestConfig => { config . headers = { Authorization : `Bearer ${ this . _bearerToken }` } ; return config ; } ) ; } param id param max returns public async getLatestTweets ( id , max = 5 ) { const config = { params : { expansions : 'attachments.media_keys,referenced_tweets.id,author_id' , 'media.fields' : 'duration_ms,height,media_key,preview_image_url,public_metrics,type,url,width' , 'tweet.fields' : 'created_at,public_metrics' , 'max_results' : `${ max < 5 ? 5 : max }` } } ; const response = await this . _http . get < TwitterTimelineResponse > ( `https://api.twitter.com/2/users/${ id }/tweets` , config ) ; const { data } = response . data ; if ( max < data . length ) { response . data . data = data . slice ( 0 , max ) ; } return response . data ; } param id returns public async getUser ( id ) { const config = { params : { 'user.fields' : 'profile_image_url' , } } ; const response = await this . _http . get < TwitterUserResponse > ( `https://api.twitter.com/2/users/${ id }` , config ) ; return response . data . data ; } }