Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added egg.Datastore, for e.g. localStorage

  • Loading branch information...
commit e271baa4c9338edd17d28504f7374e7d76f3e744 1 parent fe088cd
Mark Evans authored
Showing with 45 additions and 0 deletions.
  1. +2 −0  Cakefile
  2. +25 −0 src/datastore.coffee
  3. +18 −0 test/src/datastore.coffee
2  Cakefile
View
@@ -31,6 +31,7 @@ task 'build', 'Build single application file from source files', ->
'src/base'
'src/set'
'src/rest_api'
+ 'src/datastore'
'src/model'
'src/active_record'
'src/index'
@@ -54,4 +55,5 @@ task 'build_tests', 'Build tests from source files', ->
'test/src/index'
'test/src/jquery_plugins'
'test/src/presenter'
+ 'test/src/datastore'
], 'test/tests'
25 src/datastore.coffee
View
@@ -0,0 +1,25 @@
+class egg.Datastore extends egg.Base
+
+ @init (opts)->
+ # Store should conform to the same api as localStorage
+ @store = opts.store || throw("Need 'store' option in #{@class.name}")
+
+ load: (klass)->
+ deferred = $.Deferred()
+
+ models = []
+ data = @get(klass)
+ if data
+ models.push klass.load(attrs: attrs) for attrs in data
+ deferred.resolve(models)
+
+ deferred.promise()
+
+ get: (klass)->
+ JSON.parse @store.getItem(klass.name)
+
+ save: (klass)->
+ @store.setItem(klass.name, JSON.stringify(klass.all().map('attrs')))
+
+ destroy: (klass)->
+ @store.removeItem(klass.name)
18 test/src/datastore.coffee
View
@@ -0,0 +1,18 @@
+describe 'egg.Datastore', ->
+
+ class Fig extends egg.Model
+
+ describe 'saving', ->
+ store = null
+
+ beforeEach ->
+ store = egg.Datastore.create(store: localStorage)
+
+ it "should store the correct thing yo", ->
+ Fig.create(attrs: {colour: 'orange'})
+ Fig.create(attrs: {size: 16})
+ store.save(Fig)
+ expect( store.get(Fig) ).toEqual([
+ {colour: 'orange'}
+ {size: 16}
+ ])
Please sign in to comment.
Something went wrong with that request. Please try again.