diff --git a/lib/api.js b/lib/api.js index 0e8bc4f..be466ed 100644 --- a/lib/api.js +++ b/lib/api.js @@ -1,8 +1,13 @@ import axios from 'axios' -export default { - uploadImage -} +const gistClient = axios.create({ + baseURL: 'https://api.github.com', + timeout: 5000, + headers: { + Accept: 'application/vnd.github.v3+json', + 'Content-Type': 'application/json' + } +}); async function uploadImage (encodedImage) { // upload image @@ -28,4 +33,19 @@ async function uploadImage (encodedImage) { console.log('bummer man') console.log(e) } -} \ No newline at end of file +} + +const getGist = (id) => { + const uid = id.split('/').pop() + return gistClient.get(`/gists/${uid}`) + .then(res => res.data) + .then(gist => gist.files) + .then(files => files[Object.keys(files)[0]]) + .then(file => file.content) +} + + +export default { + uploadImage, + getGist +} diff --git a/package.json b/package.json index 7f4fa3d..60d0486 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,8 @@ "license": "MIT", "scripts": { "dev": "node server.js", - "next": "next" + "build": "next build", + "start": "next start" }, "dependencies": { "axios": "^0.16.2", diff --git a/pages/index.js b/pages/index.js index 8e7c03d..3a90997 100644 --- a/pages/index.js +++ b/pages/index.js @@ -2,7 +2,7 @@ import React from 'react' import Axios from 'axios' import CodeImage from '../components/codeImage' -import api from '../api' +import api from '../lib/api' const code = ` const pluckDeep = key => obj => key.split('.').reduce((accum, key) => accum[key], obj) @@ -17,22 +17,34 @@ const unfold = (f, seed) => { return go(f, seed, []) }` -export default (props) => { - return ( -
- -

Welcome to Code Image

- - {code} - -
- ) +export default class extends React.Component { + /* pathname, asPath, err, req, res */ + static async getInitialProps ({ asPath }) { + try { + const content = await api.getGist(asPath) + return { content } + } catch (e) { + console.log(e) + return {} + } + } + render () { + return ( +
+ +

Welcome to Code Image

+ + {this.props.content || code} + +
+ ) + } } diff --git a/server.js b/server.js index 51e8cae..134f1d9 100644 --- a/server.js +++ b/server.js @@ -22,17 +22,15 @@ app.prepare() server.use(morgan('tiny')) // if root, render webpage from next - server.get('/', (req, res) => { - return app.render(req, res, '/', req.query) - }) + server.get('*', (req, res) => + app.render(req, res, '/', req.query)) + + // otherwise, try and get gist + server.get('*', handle) // api endpoints server.post('/upload', bodyParser.json(), wrap(require('./handlers/upload'))) - // otherwise, try and get gist - server.get('*', (req, res) => { - return handle(req, res) - }) server.listen(3000, (err) => { if (err) throw err