lunch/js/actions/SuggestionActions.js

94 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-12-24 10:00:21 -05:00
var SuggestionConstants = require('../constants/SuggestionConstants');
2016-12-23 20:38:59 -05:00
var ErrorActions = require('./ErrorActions');
var models = require('../models.js');
2016-12-24 10:00:21 -05:00
var Suggestion = models.Suggestion;
2016-12-23 20:38:59 -05:00
var Error = models.Error;
2016-12-24 10:00:21 -05:00
function fetchSuggestions() {
2016-12-23 20:38:59 -05:00
return {
2016-12-24 10:00:21 -05:00
type: SuggestionConstants.FETCH_SUGGESTIONS
2016-12-23 20:38:59 -05:00
}
}
function restaurantsFetched(restaurants) {
return {
2016-12-24 10:00:21 -05:00
type: SuggestionConstants.SUGGESTIONS_FETCHED,
2016-12-23 20:38:59 -05:00
restaurants: restaurants
}
}
2016-12-24 10:00:21 -05:00
function createSuggestion() {
2016-12-23 20:38:59 -05:00
return {
2016-12-24 10:00:21 -05:00
type: SuggestionConstants.CREATE_SUGGESTION
2016-12-23 20:38:59 -05:00
}
}
function restaurantCreated(restaurant) {
return {
2016-12-24 10:00:21 -05:00
type: SuggestionConstants.SUGGESTION_CREATED,
2016-12-23 20:38:59 -05:00
restaurant: restaurant
}
}
function fetchAll() {
return function (dispatch) {
2016-12-24 10:00:21 -05:00
dispatch(fetchSuggestions());
2016-12-23 20:38:59 -05:00
$.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) {
2016-12-24 10:00:21 -05:00
var a = new Suggestion();
2016-12-23 20:38:59 -05:00
a.fromJSON(json);
return a;
})));
}
},
error: function(jqXHR, status, error) {
ErrorActions.ajaxError(e);
}
});
};
}
function create(restaurant) {
return function (dispatch) {
2016-12-24 10:00:21 -05:00
dispatch(createSuggestion());
2016-12-23 20:38:59 -05:00
$.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 {
2016-12-24 10:00:21 -05:00
var a = new Suggestion();
2016-12-23 20:38:59 -05:00
a.fromJSON(data);
dispatch(restaurantCreated(a));
}
},
error: function(jqXHR, status, error) {
ErrorActions.ajaxError(e);
}
});
};
}
module.exports = {
fetchAll: fetchAll,
create: create
};