var SuggestionConstants = require('../constants/SuggestionConstants'); var ErrorActions = require('./ErrorActions'); var models = require('../models.js'); var Suggestion = models.Suggestion; var Error = models.Error; function fetchSuggestions() { return { type: SuggestionConstants.FETCH_SUGGESTIONS } } function restaurantsFetched(restaurants) { return { type: SuggestionConstants.SUGGESTIONS_FETCHED, restaurants: restaurants } } function createSuggestion() { return { type: SuggestionConstants.CREATE_SUGGESTION } } function restaurantCreated(restaurant) { return { type: SuggestionConstants.SUGGESTION_CREATED, restaurant: restaurant } } function fetchAll() { return function (dispatch) { dispatch(fetchSuggestions()); $.ajax({ type: "GET", dataType: "json", url: "restaurant/", success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { ErrorActions.serverError(e); } else { dispatch(restaurantsFetched(data.restaurants.map(function(json) { var a = new Suggestion(); a.fromJSON(json); return a; }))); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } function create(restaurant) { return function (dispatch) { dispatch(createSuggestion()); $.ajax({ type: "POST", dataType: "json", url: "restaurant/", data: {restaurant: restaurant.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(restaurantCreated(a)); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } module.exports = { fetchAll: fetchAll, create: create };