-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtinymodel.coffee
More file actions
348 lines (317 loc) · 8.33 KB
/
tinymodel.coffee
File metadata and controls
348 lines (317 loc) · 8.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
app = @
class @TinyModel
@collection: undefined
errors: []
constructor: (params={}) ->
for field,value of params
if @constructor.an_embedded? and @constructor.an_embedded[field]?
klass = app[@constructor.an_embedded[field]]
@[field] = new klass(value)
else if @constructor.many_embedded? and @constructor.many_embedded[field]?
klass = app[@constructor.many_embedded[field]]
@[field] = (new klass(params) for params in value)
else
@[field] = value
# Intialize the model.
#
# doc - the model attributes
#
# Examples
#
# Car.new( color: 'blue' )
# # => <Car color: 'blue' ... >
#
# Returns a model
@new: (doc={}) ->
obj = new @(doc)
obj._id = doc._id
obj.createdAt = doc.createdAt
obj.updatedAt = doc.updatedAt
obj
@field: (name, options={}) ->
@::[name] = options.default
@validates: (field, validations) ->
# defining @validators class variable here instead of
# above so that @validators is shared between instances
# of the same subclass but not shared between all TinyModels
@validators or= []
for validator, condition of validations
switch validator
when 'presence'
@validators.push new PresenceValidator(field, condition)
when 'length'
@validators.push new LengthValidator(field, condition)
when 'exclusion'
@validators.push new ExclusionValidator(field, condition)
when 'format'
@validators.push new FormatValidator(field, condition)
when 'inclusion'
@validators.push new InclusionValidator(field, condition)
when 'numericality'
@validators.push new NumericalityValidator(field, condition)
@has: (options={}) ->
# belongs_to relationship
if options.a? and options.of_class?
method_name = options.a
class_name = options.of_class
belongs_to_id = "#{method_name}_id"
@::[belongs_to_id] = undefined
# add an instance method named method_name to the class that
# has the @has declaration in it.
@::[method_name] = do( class_name, belongs_to_id ) ->
() -> app[class_name].findOne( _id: @[belongs_to_id] )
# has_many relationship
else if options.many? and options.of_class?
method_name = options.many
class_name = options.of_class
has_many_id = "#{@name.toLowerCase()}_id"
@::[method_name] = do( class_name, has_many_id ) ->
(selector={}) ->
selector[has_many_id] = @_id
app[class_name].all( selector )
# an_embedded relationship
else if options.an_embedded? and options.of_class?
method_name = options.an_embedded
class_name = options.of_class
@an_embedded or= []
@an_embedded[method_name] = class_name
# many_embedded relationship
else if options.many_embedded? and options.of_class
method_name = options.many_embedded
class_name = options.of_class
@many_embedded or= []
@many_embedded[method_name] = class_name
# Find all documents that match the selector.
#
# selector - selection criteria
#
# Examples
#
# Car.find( color: 'red' )
# # => Cursor
#
# Returns a cursor. Once cursor is iterated, returns models.
@find: (selector={}, options={}) ->
options.transform = (doc) => @new( doc )
@collection.find( selector, options )
# Find all documents that match the selector and initialize.
#
# selector - selection criteria
#
# Examples
#
# Car.all( color: 'blue' )
# # => [Car, Car, Car]
#
# Returns an array of models
@all: (selector={}, options={}) ->
@find( selector, options ).fetch()
# Find first document that match the selector and initialize.
#
# selector - selection criteria
#
# Examples
#
# Car.findOne( color: 'blue' )
# # => <Car color: 'blue'...>
#
# Returns one model
@findOne: (selector={}) ->
doc = @collection.findOne( selector )
@new( doc ) if doc
# Inserts a document with given attributes
#
# params - attributes
#
# Examples
#
# Car.insert( color: 'blue', spoiler: true )
# # => <Car _id: '123', color: 'blue', spoiler: true ...>
#
# Returns one model
@insert: (params={}) ->
doc = new @( params )
doc.updatedAt = doc.createdAt = new Date()
return doc unless doc.isValid()
doc._id = @collection.insert( doc )
doc
# Remove documents based on selector
#
# selector - selection criteria
#
# Examples
#
# Car.remove( color: 'blue' )
# # => 1
#
# Car.remove( {} )
# # => removes all documents
#
# Returns number of documents removed
@remove: (selector) ->
@collection.remove( selector )
# Find the number of documents in the collection
#
# selector - selection criteria
#
# Examples
#
# Car.count( color: 'blue' )
# # => 2
#
# Car.count()
# # => total count of all documents
#
# Returns a number
@count: (selector={}) ->
@collection.find( selector ).count()
# Get name of collection
#
# Examples
#
# Car.toString()
# # => 'cars'
#
# Returns a string
@toString: ->
@collection._name
# Modified from -
# https://coffeescript-cookbook.github.io/chapters/classes_and_objects/cloning
#
# Clone a model
#
# obj - the object to clone
#
# Examples
#
# Car.clone( car )
# # => <Car color: 'blue'...>
#
# Returns an unsaved model
@clone: (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date( obj.getTime() )
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
if key == '_id'
newInstance['_id'] = undefined
else
newInstance[key] = @clone( obj[key] )
return @new( newInstance )
# Insert this model.
#
# Examples
#
# car = new Car
# car.color = 'blue'
# car.insert()
# # => '123abc'
#
# Returns the id of the newly created document or false if insert failed
insert: ->
if @persisted()
@update()
else
return false unless @isValid()
@updatedAt = @createdAt = new Date()
@_id = @constructor.collection.insert( @attributes() )
# Update this model.
#
# Examples
#
# car = Car.findOne( color: 'blue' )
# car.color = 'red'
# car.update()
# # => 1
#
# Returns the # of documents updated or false if update failed
update: ->
if @persisted()
return false unless @isValid()
@updatedAt = new Date()
@constructor.collection.update( @_id, { $set: @attributes() } )
else
false
# Removes this model.
#
# Examples
#
# car = Car.findOne( color: 'blue' )
# car.remove()
# # => 1
#
# Returns the # of documents removed
remove: ->
if @persisted()
@constructor.collection.remove( @_id )
else
false
# Check if this model is persisted (has an _id).
#
# Examples
#
# car = Car.findOne( color: 'blue' )
# car.persisted()
# # => true
#
# Returns true if document has an id, false otherwise
persisted: ->
@_id?
# Runs all validators on this model
validate: ->
@constructor.validators or= []
val.run(@) for val in @constructor.validators
@errors.length == 0
# Check if this model is valid
#
# Examples
#
# car = new Car
# car.color = 'red'
# car.isValid()
# # => true
#
# Returns true if model has no errors, false otherwise
isValid: ->
@errors = []
@validate()
isInvalid: ->
@errors = []
not @validate()
# Get the own properties of this model
#
# Examples
#
# car = Car.findOne( color: 'blue' )
# car.attributes()
# # => { color: 'blue' }
#
# Returns an object with the models attributes
attributes: ->
own = Object.getOwnPropertyNames( @ )
props = _.pick( @, own )
attrs = _.omit( props, '_id', 'errors' )
error: (field, message) ->
@errors ||= []
e = {}
e[field] = message
@errors.push e
hasErrors: ->
@errors.length > 0
errorMessages: ->
msg = []
for i in @errors
for key, value of i
msg.push value
msg.join(', ')
copy: (obj) ->
@constructor.clone( @ )