Created
July 24, 2018 23:28
-
-
Save kukicado/559e7495d0ad1e751ecc9a38ea1953ae 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
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