Skip to content

Commit

Permalink
Count the number of removed records in case of an error or attempting…
Browse files Browse the repository at this point in the history
… to remove a missing record
  • Loading branch information
wdavidw committed Oct 3, 2012
1 parent 1f84b2b commit 25a0900
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
22 changes: 19 additions & 3 deletions lib/Records.coffee
Expand Up @@ -597,21 +597,37 @@ module.exports = class Records extends Schema
---------------------------
Remove one or several records from the database. The function will also
handle all the indexes referencing those records.
`records` Record object or array of record objects.
`callback` Called on success or failure. Received parameters are:
* `err` Error object if any.
* `removed` Number of removed records.
Removing a single record:
Users.remove id, (err, removed) ->
console.log "#{removed} user removed"
###
remove: (records, callback) ->
{redis, hash} = @
{db, name, identifier, index, unique} = @data
isArray = Array.isArray records
records = [records] unless isArray
removed = 0
@get records, [].concat(Object.keys(unique), Object.keys(index)), (err, records) ->
return callback err if err
multi = redis.multi()
for record in records
# Bypass null records, not much to do with it
continue if record is null
do (record) ->
# delete objects
recordId = record[identifier]
multi.del "#{db}:#{name}:#{recordId}"
multi.del "#{db}:#{name}:#{recordId}", (err) ->
removed++
# delete indexes
multi.srem "#{db}:#{name}_#{identifier}", recordId
for property of unique
Expand All @@ -622,7 +638,7 @@ module.exports = class Records extends Schema
console.warn('Missing indexed property') if count isnt 1
multi.exec (err, results) ->
return callback err if err
callback null, records.length
callback null, removed
###
`update(records, [options], callback)`
Expand Down
9 changes: 9 additions & 0 deletions test/remove.coffee
Expand Up @@ -37,3 +37,12 @@ describe 'remove', ->
Users.exists user.user_id, (err, exists) ->
should.not.exist exists
next()

it 'should not remove a missing record', (next) ->
# Delete record based on identifier
Users.remove -1, (err, count) ->
should.not.exist err
# Count shouldn't be incremented
count.should.eql 0
next()

0 comments on commit 25a0900

Please sign in to comment.