From 5ab11f69f6f59d2f745faf4d7155d6157003cee7 Mon Sep 17 00:00:00 2001 From: Dessa Simpson Date: Mon, 9 Nov 2020 16:28:30 -0700 Subject: [PATCH] Add Youtube API connectivity --- src/config.ts | 9 +++++++-- src/youtube.ts | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 src/youtube.ts diff --git a/src/config.ts b/src/config.ts index 9d95f94..ce3e768 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,5 +1,4 @@ -import * as logging from './logging'; -import { log, LogLevel } from "./logging" +import { LogLevel } from "./logging" if (typeof process.env.PORT == 'undefined') { console.log("Missing environment variable PORT"); @@ -31,6 +30,12 @@ if (typeof process.env.SESSION_SECRET == 'undefined') { } export const sessionSecret: string = process.env.SESSION_SECRET!; +if (typeof process.env.YOUTUBE_SECRET == 'undefined') { + console.log("Missing environment variable YOUTUBE_SECRET"); + process.exit(1); +} +export const youtubeSecret: string = process.env.YOUTUBE_SECRET!; + export const logLevel = (process.env.LOG_LEVEL ? LogLevel[process.env.LOG_LEVEL as keyof typeof LogLevel] : LogLevel.ERROR ); console.log("Running with logLevel = " + logLevel) diff --git a/src/youtube.ts b/src/youtube.ts new file mode 100644 index 0000000..a447f27 --- /dev/null +++ b/src/youtube.ts @@ -0,0 +1,21 @@ +import * as config from "./config"; +import { log, LogLevel } from "./logging" +import fetch, { Response as FetchResponse } from "node-fetch"; + +export async function apiRequest(endpoint: string, parameters: URLSearchParams): Promise { + log(LogLevel.DEBUG,`Call: youtube.apiRequest(${endpoint})`); + parameters.set('key',config.youtubeSecret); + var requestUrl = "https://www.googleapis.com/youtube/v3/" + endpoint + "?" + parameters.toString(); + return fetch(requestUrl) + .then(async (res: FetchResponse) => { + if (res.status == 200) { + return res.json(); + } else { + log(LogLevel.WARNING,"Failed Youtube API request:"); + log(LogLevel.WARNING,"Request URL: " + requestUrl); + log(LogLevel.WARNING,"Response:"); + log(LogLevel.WARNING,JSON.stringify(await res.json(),null,2)); + return false; + } + }) +}