-
-
Save TravisBallard/9505619548e8f56795b276877c467db7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {youtube} from "../client-config"; | |
const axios = require('axios'); | |
const redis = require('redis'); | |
const client = redis.createClient('redis://effpv.netlify.com:6379'); | |
const expirationTime = 3600 * 12; | |
exports.handler = async (event, context, callback) => { | |
try { | |
const {id} = JSON.parse(event.body); | |
const url = `https://www.googleapis.com/youtube/v3/videos?key=${youtube.key}&part=statistics&id=${id}`; | |
client.get(id, async (error, data) => { | |
if (error) throw error; | |
if (data !== null) { | |
console.log('Serving video info from redis cache: ', data); | |
callback(null, {statusCode: 200, body: data}); | |
} else { | |
await axios.get(url).then(response => { | |
const {data} = response; | |
const {items} = data; | |
if (items === undefined || items.length === 0) { | |
callback(null, {statusCode: 200, body: '{"status":"No Items."}'}); | |
} | |
const {statistics} = items[0]; | |
client.setex(id, expirationTime, JSON.stringify(statistics)); | |
callback(null, {statusCode: 200, body: JSON.stringify(statistics)}); | |
}, e => console.error(e)); | |
} | |
}); | |
} catch (e) { | |
callback(e); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment