Skip to content

Instantly share code, notes, and snippets.

@stigok
Last active March 10, 2016 20:38
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 stigok/ba980f2b667a5733f595 to your computer and use it in GitHub Desktop.
Save stigok/ba980f2b667a5733f595 to your computer and use it in GitHub Desktop.
Express web-server for Angular app with cached HTTP API backend
'use strict';
module.exports.jsonResponseObject = function jsonResponseObject(err, data) {
return {
meta: {
status: err ? (err.status || 500) : 200,
message: err ? (err.message || 'Error') : 'OK'
},
response: data || {}
};
};
'use strict';
const express = require('express');
const path = require('path');
const cache = require('memory-cache');
const helpers = require('./helpers');
const router = new express.Router();
const responseObject = helpers.jsonResponseObject;
const cacheTimeout = 15 * 60 * 1000;
// Angular app
router.use('/', express.static(path.join(__dirname, '/static')));
// API calls
router.use('/api/posts', (req, res) => {
let key = 'test-key';
let cached = cache.get(key);
if (!cached) {
// Add value stating that a fresh data request is pending
cache.put(key, 'pending', 5000);
// Get fresh data
myApi.expensiveOperation((err, data) => {
if (err) {
return console.error('api call error', err);
}
console.log('Cache key %s updated with fresh data', key);
// Fill up the cache with the real data
cache.put(key, data, cacheTimeout);
});
// Return empty array
return res.json(responseObject('Data not ready...'));
}
// Return cache data
return res.json(responseObject(null, cache.get(key)));
});
module.exports = router;
'use strict';
const express = require('express');
const helmet = require('helmet');
const router = require('./router.js');
const helpers = require('./helpers');
const responseObject = helpers.jsonResponseObject;
const app = express();
app.use(helmet());
app.use(router);
app.use(function errorHandler(err, req, res, next) { // eslint-disable-line no-unused-vars
if (!err) {
err = new Error('Not found');
err.status = 404;
}
console.error('errorHandler', err);
res
.status(err.status || 404)
.json(responseObject(err));
});
module.exports = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment