Created
September 11, 2012 12:32
-
-
Save eladb/3698083 to your computer and use it in GitHub Desktop.
node-express-csvdb
This file contains hidden or 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
var csvdb = require('csvdb'); | |
var express = require('express'); | |
var path = require('path'); | |
// | |
// Returns an `express` middleware that can used to | |
// `source` is the url of the csv source (required) | |
// `options.filter` is a function called for each entry in `source` and allows one to filter the served results (default is no filter). | |
// `options.autofetch` is an interval for autofetching from source (default 5000ms). | |
// `options.view` is the name of a view to render when requests come in with `http` in their `accept` header (optional). | |
// | |
module.exports = function(source, options) { | |
options = options || {}; | |
options.filter = options.filter || function(obj) { return true; }; | |
options.autofetch = options.autofetch || 5000; | |
options.view = options.view || null; | |
var db = csvdb(source, options); | |
var app = express(); | |
app.get('/', function(req, res) { | |
var output; | |
if (Array.isArray(db.entries)){ | |
output = []; | |
db.entries.forEach(function(obj) { | |
if (options.filter(obj)) { | |
output.push(obj); | |
} | |
}); | |
} | |
else { | |
output = {}; | |
for (var key in db.entries) { | |
if (options.filter(db.entries[key])) { | |
output[key] = db.entries[key]; | |
} | |
} | |
} | |
return res.send(output); | |
}); | |
app.get('/:id', function(req, res) { | |
var entry = db.entries[req.params.id]; | |
if (!entry) { | |
return res.send(404); | |
} | |
if (options.view && req.headers.accept && req.headers.accept.indexOf('text/html') !== -1) { | |
entry.layout = false; | |
return res.render(options.view, entry); | |
} | |
return res.send(entry); | |
}); | |
// access current state | |
Object.defineProperty(app, 'db', { | |
get: function() { | |
return db; | |
}, | |
}) | |
return app; | |
} |
This file contains hidden or 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
var express = require('express'); | |
var csvdb = require('csvdb'); | |
var app = express(); | |
app.use('/items', csvdb('http://path/to/csv/file')); | |
app.listen(5000); | |
/* | |
$ curl localhost:5000/items | |
<JSON array of items in CSV> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment