Skip to content

Instantly share code, notes, and snippets.

@tolumide-ng
Created January 25, 2020 17:48
Show Gist options
  • Save tolumide-ng/133e9644bc9bdd50ff189deca8f05d4b to your computer and use it in GitHub Desktop.
Save tolumide-ng/133e9644bc9bdd50ff189deca8f05d4b to your computer and use it in GitHub Desktop.
getting bearer token from twitter oauth2.0
import { ResolverMap } from "../../types/graphql-utils";
import axios from "axios";
import dotenv from "dotenv";
const qs = require("qs");
dotenv.config();
export const resolvers: ResolverMap = {
Query: {
twitterLogin: async (_: any): Promise<any> => {
let bearerToken: string = "";
try {
const data = { grant_type: "client_credentials" };
const firstRequest = await axios({
method: "post",
url: "https://api.twitter.com/oauth2/token",
headers: {
Authorization:
"Basic " +
Buffer.from(
`${process.env.TWITTER_API_KEY}:${process.env.TWITTER_API_SECRET}`
).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
data: qs.stringify(data)
});
const {
status,
data: { token_type, access_token }
} = firstRequest;
if (status === 200 && token_type === "bearer") {
console.log(token_type);
bearerToken = access_token;
console.log(bearerToken);
const secondRequest = await axios({
method: "get",
url:
"https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name=twitterapi",
headers: {
Authorization: `Bearer ${bearerToken}`
}
});
console.log(
"this is the second response ?>>>>>>>>>>>",
secondRequest
);
} else {
throw new Error("Authentication Failed");
}
return { status: "200" };
} catch (err) {
console.log(err);
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment