Skip to content

Instantly share code, notes, and snippets.

@mrzafod
Created August 7, 2015 09:10
Show Gist options
  • Save mrzafod/62684df4b5d38f76a72f to your computer and use it in GitHub Desktop.
Save mrzafod/62684df4b5d38f76a72f to your computer and use it in GitHub Desktop.
# dboperator
class DBOperator extends Factory.ExtClass
constructor: (@_collection) ->
@_selector = {}
@_options = {}
@_modifier = {}
where: (args...) ->
for arg in args
unless _is.object arg
@_selector._id = arg
else
_.extend @_selector, arg
return @
modify: (mod, arg) ->
@_modifier[mod] = @_modifier[mod] or {}
if _is.object arg
_.extend @_modifier[mod], arg
return @
set: (arg) -> @modify '$set', arg
unset: (arg) -> @modify '$unset', arg
add: (arg) -> @modify '$addToSet', arg
push: (arg) -> @modify '$push', arg
pull: (arg) -> @modify '$pull', arg
inc: (arg) -> @modify '$inc', arg
skip: (num) ->
@_options.skip = num
return @
limit: (num) ->
@_options.limit = num
return @
range: (skip, limit) ->
@skip(skip).limit(limit)
fields: (args...) ->
@_options.fields = @_options.fields or {}
for arg in args
if _is.object arg
_.extend @_options.fields, arg
return @
only: (args...) ->
@_options.fields = @_options.fields or {}
for arg in args
if _is.string arg
@_options.fields[arg] = 1
return @
without: (args...) ->
@_options.fields = @_options.fields or {}
for arg in args
if _is.string arg
@_options.fields[arg] = -1
return @
sort: (args...) ->
@_options.sort = @_options.sort or []
for arg in args
if _is.object arg
for key, value of arg
value = if (value is 0) or (value is -1) or (value is 'desc') then 'desc' else 'asc'
@_options.sort.push [key, value]
return @
sortUp: (args...) ->
@_options.sort = @_options.sort or []
for arg in args
if _is.string arg
@_options.sort.push [arg, 'asc']
return @
sortDown: (args...) ->
@_options.sort = @_options.sort or []
for arg in args
if _is.string arg
@_options.sort.push [arg, 'desc']
return @
multy: (arg = true) ->
@_options.multy = arg
return @
find: () ->
@_collections.find @_selector, @_options
findOne: () ->
@_collections.findOne @_selector, @_options
undate: (callback) ->
@_collection.update @_selector, @_modifier, callback
upsert: (callback) ->
@_collection.upsert @_selector, @_modifier,callback
remove: (callback) ->
@_collection.remove @_selector, @_modifier, callback
_.each ['where', 'modify', 'set', 'unset', 'add', 'push', 'pull', 'inc', 'skip', 'limit', 'range', 'fields', 'only', 'without', 'sort', 'sortUp', 'sortDown', 'multy'], (name) ->
Mongo.Collection::[name] = (new DBOperator @)[name]
# servise for create or manage database
class DBService extends Factory.ExtClass
# db collections
@_collections: {}
# return collection inctance
# @params
# name - [string] collection name
# options - [object] collection options
@instance: (name, options) ->
# register service
Services.DB = DBService
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment