Last active
July 24, 2018 16:36
-
-
Save fed135/01fc38761b0ebc5b28194c5632fa914f to your computer and use it in GitHub Desktop.
ha-store sample 1
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
/** | |
* Data access layer | |
*/ | |
/* Requires --------------------------------------------------------------*/ | |
const MongoClient = require('mongo').MongoClient; | |
/* Init ------------------------------------------------------------------*/ | |
let db = null; | |
MongoClient.connect('mongodb://localhost:27017', function(err, client) { | |
if (err) throw new Error(err); | |
db = client.db('my_db'); | |
}); | |
// Unfortunatly, we need to do a lot of formatting due to the limitations of | |
// the mongo database interface | |
function getProducts(ids, params) { | |
if (db === null) throw new Error('Database not ready'); | |
return new Promise((resolve, reject) => { | |
db.collection('products').find(ids.map((id) => ({ | |
name: id, | |
language: params.language || 'en', | |
currency: params.currency || 'usd' | |
})).toArray((err, results) => { | |
if (err) return reject(err); | |
return resolve(results.reduce((acc, product) => { | |
acc[product.name] = product; | |
return acc; | |
}, {})); | |
}); | |
}); | |
} | |
/* Exports ---------------------------------------------------------------*/ | |
module.exports = { getProducts }; |
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
/** | |
* Your application's entry-point | |
* In this sample, we'll make it a rest API that sits in front of a Mongo database | |
*/ | |
/* Requires --------------------------------------------------------------*/ | |
const express = require('express'); | |
const store = require('ha-store'); | |
const redisStore = require('ha-store-redis'); | |
const { getProducts } = require('./db'); | |
/* Init ------------------------------------------------------------------*/ | |
const app = express(); | |
const productStore = store({ | |
resolver: getProducts, | |
uniqueParams: ['language', 'currency'], | |
cache: { | |
base: 10000, | |
limit: 100000 | |
}, | |
store: redisStore('0.0.0.0:6379') | |
}); | |
app.get('/products/:id', function (req, res) { | |
productStore.get(req.params.id, req.query) | |
.then(product => res.json(product)) | |
.catch(err => res.status(500).json(err); | |
}); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment