Skip to content

Instantly share code, notes, and snippets.

@casualjim
Created November 25, 2012 19:42
Show Gist options
  • Save casualjim/4144993 to your computer and use it in GitHub Desktop.
Save casualjim/4144993 to your computer and use it in GitHub Desktop.
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)
}
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