Implement Twitch API connector

This commit is contained in:
Dessa Simpson 2020-07-05 11:46:41 -07:00
parent 2ef965f749
commit df68c990fc
6 changed files with 85 additions and 2 deletions

View file

@ -1,9 +1,12 @@
import * as config from "./config";
import * as requests from "./requests";
import * as twitch from "./twitch";
import { URLSearchParams } from "url";
import { QueryResult } from "pg";
import express from "express";
import session from "express-session";
import pgSessionStore from "connect-pg-simple";
import fetch, { Response as FetchResponse } from "node-fetch";
import db from "./db";
import errorHandler from "./errors";
@ -14,9 +17,12 @@ app.use(session({
secret: config.sessionSecret,
saveUninitialized: false,
resave: false,
store: new (pgSessionStore(session))()
store: new (pgSessionStore(session))({
pool: db
})
}));
// API
app.get("/api/getRequests", async (request, response) => {
var requestCount = ( request.query.count ? parseInt(request.query.count as string, 10) : 5 );
requests.getRequests(requestCount).then((val: QueryResult) => response.send(val))
@ -101,6 +107,26 @@ app.post("/api/deleteRequest", async (request, response) => {
.catch((e: any) => errorHandler(request,response,e));
});
// Twitch callback
app.get("/callback", async (request, response) => {
var authcode = request.query.code as string;
var tokenResponse = await fetch("https://id.twitch.tv/oauth2/token", { method: "POST", body: new URLSearchParams({
client_id: config.twitchClientId,
client_secret: config.twitchSecret,
code: authcode,
grant_type: "authorization_code",
redirect_uri: `${config.urlPrefix}/callback`
})}).then((res: FetchResponse) => res.json() as Promise<twitch.TokenResponse>)
.catch((e: any) => errorHandler(request,response,e));
if (typeof request.session == 'undefined') throw new Error('Session is undefined');
if (typeof tokenResponse == 'undefined') throw new Error('tokenResponse is undefined');
request.session.tokenpair = { access_token: tokenResponse.access_token, refresh_token: tokenResponse.refresh_token };
request.session.user = (await twitch.apiRequest(request.session.tokenpair,"GET","/users")).data[0];
response.redirect(307, '/');
});
//app.get("/session", (request, response) => { response.send(request.session); });
const server = app.listen(config.port, () => {
console.log(`Listening on port ${config.port}`);
});

View file

@ -4,6 +4,18 @@ if (!process.env.PORT) {
}
export const port: number = parseInt(process.env.PORT as string, 10);
if (!process.env.URL_PREFIX) {
console.log("Missing environment variable URL_PREFIX");
process.exit(1);
}
export const urlPrefix: string = process.env.URL_PREFIX;
if (!process.env.TWITCH_CLIENTID) {
console.log("Missing environment variable TWITCH_CLIENTID");
process.exit(1);
}
export const twitchClientId: string = process.env.TWITCH_CLIENTID;
if (!process.env.TWITCH_SECRET) {
console.log("Missing environment variable TWITCH_SECRET");
process.exit(1);

25
src/twitch.ts Normal file
View file

@ -0,0 +1,25 @@
import * as config from "./config";
import fetch, { Response as FetchResponse } from "node-fetch";
export interface TokenResponse {
access_token: string;
refresh_token: string;
token_type: string;
expires_in: number;
}
export interface TokenPair {
access_token: string;
refresh_token: string;
}
export async function apiRequest(tokens: TokenPair, method: string, endpoint: string): Promise<any>;
export async function apiRequest(tokens: TokenPair, method: string, endpoint: string, query: string): Promise<any>;
export async function apiRequest(tokens: TokenPair, method: string, endpoint: string, query?: string,) {
var headers = {
"Authorization": "Bearer " + tokens.access_token,
"Client-ID": config.twitchClientId
};
return fetch("https://api.twitch.tv/helix" + endpoint, { method: method, headers: headers})
.then(async (res: FetchResponse) => res.json());
}