Created
November 25, 2012 19:42
-
-
Save casualjim/4144993 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyAppBinding[T](b: FieldDescriptor[T]) { | |
def unique[TId](collection: MongoCollection, currentItem: Option[TId] = None) = b.validateWith(_ ⇒ { | |
_ flatMap { Validators.uniqueField(b.name, collection, currentItem).validate(_) } | |
}) | |
} | |
abstract class MyAppCommand[S](implicit mf: Manifest[S], protected val jsonFormats: Formats) extends ModelCommand[S] with JsonCommand { | |
type Result = S | |
implicit def myAppValidators[T](b: FieldDescriptor[T]) = new MyAppBinding[T](b) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Validators { | |
def uniqueField[TId, TResult](fieldName: String, collection: MongoCollection, currentItem: Option[TId] = None): Validator[TResult] = { | |
new Validator[TResult] { | |
def q(s: TResult) = Map(fieldName -> s) | |
def newQ(s: TResult) = currentItem.fold(id ⇒ q(s) ++ Map("_id" -> ("$ne" -> id)), q(s)) | |
def validate[R >: TResult <: TResult](subject: R): FieldValidation[R] = { | |
if (collection.count(newQ(subject), Map(fieldName -> 1)) == 0) subject.success | |
else ValidationError(fieldName.humanize + " exists already.", FieldName(fieldName), NotUnique).fail | |
} | |
} | |
} | |
} | |
object Validations { | |
def uniqueField[TId, TResult](fieldName: String, value: ⇒ TResult, collection: MongoCollection, currentItem: Option[TId] = None): FieldValidation[TResult] = { | |
Validators.uniqueField(fieldName, collection, currentItem).validate(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment