Skip to content

Instantly share code, notes, and snippets.

@yann-yinn
Created August 23, 2017 13:01
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yann-yinn/5a6d1a523aa8c3698b1675985a68422a to your computer and use it in GitHub Desktop.
Save yann-yinn/5a6d1a523aa8c3698b1675985a68422a to your computer and use it in GitHub Desktop.
Using cachios with Nuxt.js and express
/**
* Get content from wordpress via REST Api
*/
const config = require('../nuxt.config.js')
const axios = require('axios')
// always call the proxy here :
const endpoint = config.env.proxyApiBaseUrl
/**
* @param {int} perPage : number of post to return per page
* @param {int} pageNumber : current page to display
* @param {int} tagId : filter posts by a tagId
*
* @return {object}
*/
export const getPaginatedPosts = async (perPage = 10, pageNumber = 1, tagId = null) => {
let url = `${endpoint}/posts?per_page=${perPage}&page=${pageNumber}`
if (tagId) {
url += `&tags=${tagId}`
}
return axios.get(url)
.then(response => {
const result = {
total: Number(response.headers['x-wp-total']),
totalPages: Number(response.headers['x-wp-totalpages']),
data: response.data
}
return result
})
.catch(e => console.log(`${url} ${e.message}`))
}
export const getPosts = (perPage = 10) => {
const url = `${endpoint}/posts?per_page=${perPage}`
return axios.get(url)
.then(r => r.data)
.catch(e => console.log(`${url} ${e.message}`))
}
export const getPostBySlug = slug => {
const url = `${endpoint}/posts?_embed&slug=${slug}`
return axios.get(url)
.then(r => r.data[0] )
.catch(e => console.log(`${url} ${e.message}`))
}
export const getTagBySlug = slug => {
const url = `${endpoint}/tags?slug=${slug}`
return axios.get(url)
.then(r => r.data[0])
.catch(e => console.log(`${url} ${e.message}`))
}
/**
* Proxy to request wordpress.
* all internal /api/xxx requests are handled by this file,
* which pass requests then to Wordpress API.
* This let us a chance to implement custom cache of our own.
*/
const cachios = require('cachios')
const express = require('express')
const config = require('../nuxt.config.js')
const router = express.Router()
const endpoint = config.env.wordpressApiBaseUrl
cachios.getResponseCopy = response => {
return {
status: response.status,
headers: response.headers,
data: response.data
}
}
// infos about the cache
router.get('/cache', (req, res) => {
res.send(JSON.stringify(cachios.cache.getStats()))
});
// by default, just pass the request to Wordpress api and cache it with cachios
router.get('*', async (req, res) => {
const url = endpoint + req.originalUrl.replace('/api', '')
cachios.get(url, {
ttl: 86400 // one day, in seconds
}).then(r => {
res.set('x-wp-total', r.headers['x-wp-total'])
res.set('x-wp-totalpages', r.headers['x-wp-totalpages'])
res.json(r.data)
}).catch(e => res.send(url + ' ' + e.message))
})
module.exports = router
const { Nuxt, Builder } = require('nuxt')
const app = require('express')()
const isProd = (process.env.NODE_ENV === 'production')
const port = process.env.PORT || 3000
// API PROXY
app.use('/api', require('./api/proxy.js'))
// We instantiate nuxt.js
const config = require('./nuxt.config.js')
config.dev = !isProd
const nuxt = new Nuxt(config)
app.use(nuxt.render)
// Build only in dev mode with hot-reloading
if (config.dev) {
new Builder(nuxt).build()
.catch((error) => {
console.error(error)
process.exit(1)
})
}
// Listen the server
app.listen(port, '0.0.0.0')
const currentEnv = isProd ? 'production' : 'developpement'
console.log(`Server listening on localhost ${port} in ${currentEnv} mode`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment