var SuggestionConstants = require('../constants/SuggestionConstants'); var ErrorActions = require('./ErrorActions'); var models = require('../models'); var Suggestion = models.Suggestion; var PopularSuggestion = models.PopularSuggestion; var Error = models.Error; function fetchSuggestions() { return { type: SuggestionConstants.FETCH_SUGGESTIONS } } function suggestionsFetched(suggestions) { return { type: SuggestionConstants.SUGGESTIONS_FETCHED, suggestions: suggestions } } function createSuggestion() { return { type: SuggestionConstants.CREATE_SUGGESTION } } function suggestionCreated(suggestion) { return { type: SuggestionConstants.SUGGESTION_CREATED, suggestion: suggestion } } function fetchPopularSuggestions() { return { type: SuggestionConstants.FETCH_POPULAR_SUGGESTIONS } } function popularSuggestionsFetched(suggestions) { return { type: SuggestionConstants.POPULAR_SUGGESTIONS_FETCHED, suggestions: suggestions } } function fetchAll() { return function (dispatch) { dispatch(fetchSuggestions()); $.ajax({ type: "GET", dataType: "json", url: "suggestion/", success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { ErrorActions.serverError(e); } else { dispatch(suggestionsFetched(data.suggestions.map(function(json) { var a = new Suggestion(); a.fromJSON(json); return a; }))); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } function create(suggestion) { return function (dispatch) { dispatch(createSuggestion()); $.ajax({ type: "POST", dataType: "json", url: "suggestion/", data: {suggestion: suggestion.toJSON()}, success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { ErrorActions.serverError(e); } else { var a = new Suggestion(); a.fromJSON(data); dispatch(suggestionCreated(a)); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } function fetchPopular() { return function (dispatch) { dispatch(fetchPopularSuggestions()); $.ajax({ type: "GET", dataType: "json", url: "popularsuggestions/", success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { ErrorActions.serverError(e); } else { dispatch(popularSuggestionsFetched(data.popularsuggestions.map(function(json) { var a = new PopularSuggestion(); a.fromJSON(json); return a; }))); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } module.exports = { fetchAll: fetchAll, create: create, fetchPopular: fetchPopular };