essay.coffee 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. Spine = require('spine/core')
  2. utils = require('lib/utils')
  3. moment = require('lib/moment')
  4. BaseModel = require('models/base')
  5. class Essay extends BaseModel
  6. @configure "Essay", "site", "slug", "title", "intro", "body", "photo", "published", "published_at", "updated_at", "author_id", "sponsor_id", "sponsor_start", "sponsor_end", "sponsors_history", "collections", "_attachments"
  7. @extend @CouchAjax
  8. @extend @CouchChanges
  9. handler: @CouchChanges.PrivateChanges
  10. @alphaSort: (a, b) ->
  11. if (a.title or a.published_at) > (b.title or b.published_at) then 1 else -1
  12. @dateSort: (a, b) ->
  13. if (a.published_at or a.title) < (b.published_at or b.title) then 1 else -1
  14. @queryOn: ['title','slug']
  15. validate: ->
  16. @slug = utils.cleanSlug @slug
  17. return 'Site is required' unless @site
  18. return 'Slug is required' unless @slug
  19. return 'Title is required' unless @title
  20. # Validate the `slug` to be unique within site
  21. found = Essay.select (essay) =>
  22. matched = essay.site is @site and essay.slug is @slug
  23. if @isNew()
  24. matched
  25. else
  26. essay.id isnt @id and matched
  27. return 'Slug has been already used for this site.' if found.length
  28. # Take care of some dates
  29. @updated_at = moment.utc().format()
  30. published_at = moment(@published_at) or moment()
  31. return "Published #{utils.msg.DATE_NOT_VALID}" unless published_at.isValid()
  32. @published_at = published_at.utc().format()
  33. # Convert some boolean properties
  34. @published = Boolean(@published)
  35. # Sponsor dates if setting a sponsor
  36. if @sponsor_id
  37. return 'Sponsor Start Date is required' unless @sponsor_start
  38. return 'Sponsor End Date is required' unless @sponsor_end
  39. sponsor_start = moment(@sponsor_start)
  40. sponsor_end = moment(@sponsor_end)
  41. return "Sponsor Start #{utils.msg.DATE_NOT_VALID}" unless sponsor_start.isValid()
  42. return "Sponsor End #{utils.msg.DATE_NOT_VALID}" unless sponsor_end.isValid()
  43. return 'Sponsor Start Date cannot be later than End Date' if sponsor_start >= sponsor_end
  44. # Save in UTC format string
  45. @sponsor_start = sponsor_start.utc().format()
  46. @sponsor_end = sponsor_end.utc().format()
  47. # Some content transformation
  48. @intro = utils.cleanContent @intro
  49. @body = utils.cleanContent @body
  50. return false
  51. module.exports = Essay