Skip to content

Instantly share code, notes, and snippets.

@kukicado
Created July 24, 2018 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kukicado/4b56055e2edfe67077e607458dc8bb57 to your computer and use it in GitHub Desktop.
Save kukicado/4b56055e2edfe67077e607458dc8bb57 to your computer and use it in GitHub Desktop.
const express = require('express');
const Webtask = require('webtask-tools');
const bodyParser = require('body-parser');
const request = require('request');
const jwt = require('express-jwt');
const jwks = require('jwks-rsa');
const shuffle = require('lodash.shuffle');
const app = express();
const jwtCheck = jwt({
secret: jwks.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: "https://adobot.auth0.com/.well-known/jwks.json"
}),
audience: 'gifbattle',
issuer: "https://adobot.auth0.com/",
algorithms: ['RS256']
});
app.use(bodyParser.json());
app.get('/random', (req, res) => {
request('http://api.giphy.com/v1/gifs/random?api_key=uF5RTlWnH7glmKFQcG1EQpOKRAeZredD', (error, response, body) => {
body = JSON.parse(body);
const gif = {
id: body.data.id,
url: body.data.image_original_url
};
res.json(gif);
});
});
app.post('/', (req, res) => {
var gif = req.body;
db(req, (data) => {
data = data || [];
data.push(gif);
req.webtaskContext.storage.set(data, (err)=>{
res.json({message:"Success!"})
})
})
});
app.post('/vote', (req, res)=>{
let gif = req.body;
db(req, (data) => {
const index = data.findIndex(item => item.id === gif.id);
data[index].votes += 1;
req.webtaskContext.storage.set(data, (err) =>{
res.json({message:"Success!"})
})
})
})
app.get('/versus', (req, res)=>{
let response = {};
db(req, (data) => {
data = shuffle(data);
response = {
gif_one: data[0],
gif_two: data[1]
}
res.json(response);
})
})
app.get('/leaderboard', (req, res)=>{
db(req, (data) => {
data.sort((a,b)=>{return b.votes - a.votes});
res.json(data);
});
})
function db(req, cb){
req.webtaskContext.storage.get((err, data)=>{
cb(data);
});
}
module.exports = Webtask.fromExpress(app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment