Last active
September 4, 2017 19:02
-
-
Save herber/9e490d4a6df463a06826d2d4413ea4cd to your computer and use it in GitHub Desktop.
A simple gifs microservice.
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 app = require('express')(); | |
const fetch = require('node-fetch'); | |
const cache = require('memory-cache'); | |
const request = require('request'); | |
app.get('/', (req, res) => { | |
res.status(404); | |
res.json({ body: `gifs.tobihrbr.com // Get a random gif: gifs.tobihrbr.com/random // Search for a gif: // gifs.tobihrbr.com/_TERM_` }); | |
}); | |
const getGif = (term) => ( | |
new Promise((resolve, reject) => { | |
const qs = 'api_key=' + process.env.GIPHY_KEY + (term !== undefined ? '&tag=' + term : ''); | |
fetch('http://api.giphy.com/v1/gifs/random?' + qs) | |
.then((res) => res.json()) | |
.then((body) => { | |
resolve(body); | |
}).catch((err) => { | |
reject(err); | |
}); | |
}) | |
); | |
app.get('/random', async (req, res) => { | |
const data = await getGif(); | |
res.redirect('/gif/' + data.data.id); | |
}); | |
app.get('/gif/:id', (req, res) => { | |
const url = 'http://api.giphy.com/v1/gifs?api_key=' + process.env.GIPHY_KEY + '&gif_id=' + req.params.id; | |
fetch(url) | |
.then((res) => res.json()) | |
.then((body) => { | |
if (body.meta.status !== 200) { | |
res.status(404); | |
return res.json({ error: 'gif not found' }); | |
} | |
request.get('https://media0.giphy.com/media/' + req.params.id + '/giphy.gif').pipe(res); | |
}).catch((err) => { | |
res.status(500); | |
res.json({ error: 'internal server error' }); | |
}); | |
}); | |
app.get('/:term', async (req, res) => { | |
const data = await getGif(req.params.term); | |
res.redirect('/gif/' + data.data.id); | |
}); | |
app.listen(3000); |
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
{ | |
"name": "gifs", | |
"main": "index", | |
"scripts": { | |
"start": "node index.js" | |
}, | |
"dependencies": { | |
"express": "^4.15.4", | |
"node-fetch": "^1.7.2", | |
"memory-cache": "^0.2.0", | |
"request": "^2.81.0" | |
}, | |
"license": "MIT" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment