Created
October 21, 2013 19:48
-
-
Save mulderp/7089766 to your computer and use it in GitHub Desktop.
redis movies import
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 url = require('url'); | |
| var _ = require('underscore'); | |
| var querystring = require('querystring'); | |
| var Promise = require("bluebird"); | |
| //assume client is a redisClient | |
| // | |
| var now = (typeof Date.now === 'function')? Date.now : function(){ | |
| return +(new Date()); | |
| }; | |
| // redis | |
| var password, database; | |
| var parsed_url = url.parse(process.env.REDISTOGO_URL || 'redis://localhost:6379'); | |
| var parsed_auth = (parsed_url.auth || '').split(':'); | |
| var options = querystring.parse(parsed_url.query); | |
| var client = require('redis').createClient(parsed_url.port, parsed_url.hostname, options); | |
| if (password = parsed_auth[1]) { | |
| client.auth(password, function(err) { | |
| if (err) throw err; | |
| }); | |
| } | |
| Promise.promisifyAll(client); | |
| var fs = Promise.promisifyAll(require("fs")); | |
| // read file | |
| fs.readFileAsync("server/movies.json", "utf8") | |
| .then(function(f) { | |
| return JSON.parse(f); | |
| }) | |
| .then(function(movies) { | |
| return importMovies(movies); | |
| }) | |
| .catch(function(err) { | |
| console.log(err); | |
| }); | |
| // save to database | |
| function importMovies(movies) { | |
| _.each(movies, function(movie) { | |
| var movieId; | |
| client.incrAsync("movies.count") | |
| .then(function(id) { | |
| movieId = id; | |
| // add movie | |
| client.hmsetAsync( | |
| 'movies:' + id, | |
| 'id', id, | |
| 'title', movie.title, | |
| 'description', movie.description, | |
| 'year', movie.year, | |
| 'showtime', movie.showtime, | |
| 'genres', movie.genres, | |
| 'length', movie.length, | |
| 'director', movie.director, | |
| 'rating', 0 | |
| ); | |
| // add genres | |
| _.each(movie.genres, function(genre) { | |
| client.saddAsync("movies.genres", genre); | |
| client.saddAsync(genre, movieId); | |
| }); | |
| // add ids | |
| client.saddAsync('movies.ids', movieId); | |
| }) | |
| .then(function(result) { | |
| console.log(movie); | |
| }); | |
| console.log(movie); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment