@@ -10,13 +10,28 @@ var config = require('./config');
1010var client = require ( './leetcode_client' ) ;
1111var h = require ( './helper' ) ;
1212
13+ function saveProblem ( problem ) {
14+ // it would be better to leave specific problem cache being user
15+ // independent, thus try to reuse existing cache as much as possible
16+ // after changing user.
17+ var p = _ . omit ( problem , [ 'locked' , 'state' , 'starred' ] ) ;
18+ return cache . set ( p . key , p ) ;
19+ }
20+
21+ function saveUser ( user ) {
22+ // when auto login enabled, have to save password to re-login later
23+ // otherwise don't dump password for the sake of security.
24+ var u = _ . omit ( user , config . AUTO_LOGIN ? [ ] : [ 'pass' ] ) ;
25+ cache . set ( '.user' , u ) ;
26+ }
27+
1328var core = { } ;
1429
1530core . getProblems = function ( cb ) {
16- var cached = cache . get ( 'all' ) ;
17- if ( cached ) {
31+ var problems = cache . get ( 'all' ) ;
32+ if ( problems ) {
1833 log . debug ( 'loading from all.json' ) ;
19- return cb ( null , cached ) ;
34+ return cb ( null , problems ) ;
2035 }
2136
2237 client . getProblems ( function ( e , problems ) {
@@ -39,16 +54,17 @@ core.getProblem = function(keyword, cb) {
3954 if ( ! problem )
4055 return cb ( 'Problem not found!' ) ;
4156
42- var cached = cache . get ( problem . key ) ;
43- if ( cached ) {
57+ var problemDetail = cache . get ( problem . key ) ;
58+ if ( problemDetail ) {
4459 log . debug ( 'loading from ' + problem . key + '.json' ) ;
45- return cb ( null , cached ) ;
60+ _ . extendOwn ( problem , problemDetail ) ;
61+ return cb ( null , problem ) ;
4662 }
4763
4864 client . getProblem ( problem , function ( e , problem ) {
4965 if ( e ) return cb ( e ) ;
5066
51- cache . set ( problem . key , problem ) ;
67+ saveProblem ( problem ) ;
5268 return cb ( null , problem ) ;
5369 } ) ;
5470 } ) ;
@@ -82,7 +98,7 @@ core.updateProblem = function(problem, kv) {
8298 _ . extend ( oldProblem , kv ) ;
8399 _ . extend ( problem , kv ) ;
84100
85- var singleUpdated = cache . set ( problem . key , problem ) ;
101+ var singleUpdated = saveProblem ( problem ) ;
86102 var allUpdated = cache . set ( 'all' , problems ) ;
87103 return singleUpdated && allUpdated ;
88104} ;
@@ -129,12 +145,7 @@ core.login = function(user, cb) {
129145
130146 self . logout ( ) ;
131147
132- if ( config . AUTO_LOGIN )
133- // need save password thus we can auto re-login later
134- cache . set ( '.user' , user ) ;
135- else
136- cache . set ( '.user' , _ . omit ( user , 'pass' ) ) ;
137-
148+ saveUser ( user ) ;
138149 return cb ( null , user ) ;
139150 } ) ;
140151} ;
0 commit comments