All files / src/clients twitter.ts

22.22% Statements 4/18
50% Branches 1/2
20% Functions 1/5
22.22% Lines 4/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 761x   1x   1x         24x                                                                                                                                    
import { config } from '../config';
import { BindTwitterRequestDto, BindTwitterResultDto } from 'src/extensions/dao/models';
import { EUploadMimeType, TwitterApi, UserV2Result } from 'twitter-api-v2';
 
export default class TwitterClient {
  
  client: TwitterApi;
 
  constructor() {
    this.client = process.env.hasOwnProperty('TWITTER_ACCESS_TOKEN_KEY') ? new TwitterApi({
      accessToken: process.env.TWITTER_ACCESS_TOKEN_KEY,
      accessSecret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
      appKey: process.env.TWITTER_API_KEY,
      appSecret: process.env.TWITTER_API_KEY_SECRET,
    }) : undefined;    
  }
 
  async startLogin() {
    const client = new TwitterApi({
      clientId: process.env.TWITTER_CLIENT_ID,
      clientSecret: process.env.TWITTER_CLIENT_SECRET
    })
    const result = client.generateOAuth2AuthLink(config.twitterAPIRedirectURL, {
        scope: ['tweet.read', 'users.read']
    })
 
    return result
  }
 
  async finalizeLogin(infos: any, request: BindTwitterRequestDto):Promise<BindTwitterResultDto> {
    const client = new TwitterApi({
      clientId: process.env.TWITTER_CLIENT_ID,
      clientSecret: process.env.TWITTER_CLIENT_SECRET
    })
    const { client: userClient, accessToken, refreshToken } = await client.loginWithOAuth2({
      code: request.code,
      codeVerifier: infos.codeVerifier,
      redirectUri: `${config.twitterAPIRedirectURL}`
    })
    console.log('client: ', userClient)
    const user = await userClient.currentUserV2()
    console.log('user', user)
    const currentUser = await userClient.v2.me({
      "user.fields": "created_at"
    })
    console.log('currentUser', currentUser)
    return {
      createdAt: currentUser.data.created_at,
      id: currentUser.data.id,
      name: currentUser.data.name,
      username: currentUser.data.username,
      accessToken,
      refreshToken
    }
    /*
 
currentUser {
  data: {
    created_at: '2021-08-11T19:58:06.000Z',
    id: '1425547057486520329',
    name: 'tat2bu.eth',
    username: 'tat2bu'
  }
}*/
  }
  
  uploadMedia(processedImage: Buffer, options: { mimeType: EUploadMimeType; }): string | PromiseLike<string> {
    this.client.appLogin
    return this.client.v1.uploadMedia(processedImage, options);
  }
  
  tweet(tweetText: string, options:any): any {
    return this.client.v2.tweet(tweetText, options)
  }
  
}