global_search.coffee 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. class App.GlobalSearch extends App.Controller
  2. constructor: ->
  3. super
  4. @searchResultCache = {}
  5. @lastQuery = undefined
  6. @apiPath = App.Config.get('api_path')
  7. @ajaxId = "search-#{Math.floor( Math.random() * 999999 )}"
  8. search: (params) =>
  9. query = params.query
  10. # use cache for search result
  11. currentTime = new Date
  12. if @searchResultCache[query] && @searchResultCache[query].time > currentTime.setSeconds(currentTime.getSeconds() - 20)
  13. @renderTry(@searchResultCache[query].result, query)
  14. return
  15. App.Ajax.request(
  16. id: @ajaxId
  17. type: 'GET'
  18. url: "#{@apiPath}/search"
  19. data:
  20. query: query
  21. limit: @limit || 10
  22. processData: true
  23. success: (data, status, xhr) =>
  24. App.Collection.loadAssets(data.assets)
  25. result = {}
  26. for item in data.result
  27. if App[item.type] && App[item.type].find
  28. if !result[item.type]
  29. result[item.type] = []
  30. item_object = App[item.type].find(item.id)
  31. if item_object.searchResultAttributes
  32. item_object_search_attributes = item_object.searchResultAttributes()
  33. result[item.type].push item_object_search_attributes
  34. else
  35. App.Log.error('_globalSearchSingleton', "No such model #{item.type.toLocaleLowerCase()}.searchResultAttributes()")
  36. else
  37. App.Log.error('_globalSearchSingleton', "No such model App.#{item.type}")
  38. @renderTry(result, query)
  39. )
  40. renderTry: (result, query) =>
  41. # if result hasn't changed, do not rerender
  42. diff = false
  43. if @lastQuery is query && @searchResultCache[query]
  44. diff = difference(@searchResultCache[query].result, result)
  45. return if diff isnt false && _.isEmpty(diff)
  46. @lastQuery = query
  47. # cache search result
  48. @searchResultCache[query] =
  49. result: result
  50. time: new Date
  51. @render(result)
  52. close: =>
  53. @lastQuery = undefined