Skip to content

Instantly share code, notes, and snippets.

@TravisBallard
Created August 21, 2019 16:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TravisBallard/9505619548e8f56795b276877c467db7 to your computer and use it in GitHub Desktop.
Save TravisBallard/9505619548e8f56795b276877c467db7 to your computer and use it in GitHub Desktop.
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