var RestaurantConstants = require('../constants/RestaurantConstants'); var ErrorActions = require('./ErrorActions'); var models = require('../models.js'); var Restaurant = models.Restaurant; var Error = models.Error; function fetchRestaurants() { return { type: RestaurantConstants.FETCH_RESTAURANTS } } function restaurantsFetched(restaurants) { return { type: RestaurantConstants.RESTAURANTS_FETCHED, restaurants: restaurants } } function createRestaurant() { return { type: RestaurantConstants.CREATE_RESTAURANT } } function restaurantCreated(restaurant) { return { type: RestaurantConstants.RESTAURANT_CREATED, restaurant: restaurant } } function fetchAll() { return function (dispatch) { dispatch(fetchRestaurants()); $.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 Restaurant(); a.fromJSON(json); return a; }))); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } function create(restaurant) { return function (dispatch) { dispatch(createRestaurant()); $.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 Restaurant(); a.fromJSON(data); dispatch(restaurantCreated(a)); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } module.exports = { fetchAll: fetchAll, create: create };