var AttendeeConstants = require('../constants/AttendeeConstants'); var ErrorActions = require('./ErrorActions'); var models = require('../models.js'); var Attendee = models.Attendee; var Error = models.Error; function fetchAttendees() { return { type: AttendeeConstants.FETCH_ATTENDEES } } function attendeesFetched(attendees) { return { type: AttendeeConstants.ATTENDEES_FETCHED, attendees: attendees } } function createAttendee() { return { type: AttendeeConstants.CREATE_ATTENDEE } } function attendeeCreated(attendee) { return { type: AttendeeConstants.ATTENDEE_CREATED, attendee: attendee } } function fetchPopularAttendees() { return { type: AttendeeConstants.FETCH_POPULAR_ATTENDEES } } function popularAttendeesFetched(attendees) { return { type: AttendeeConstants.POPULAR_ATTENDEES_FETCHED, attendees: attendees } } function fetchAll() { return function (dispatch) { dispatch(fetchAttendees()); $.ajax({ type: "GET", dataType: "json", url: "attendee/", success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { ErrorActions.serverError(e); } else { dispatch(attendeesFetched(data.attendees.map(function(json) { var a = new Attendee(); a.fromJSON(json); return a; }))); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } function create(attendee) { return function (dispatch) { dispatch(createAttendee()); $.ajax({ type: "POST", dataType: "json", url: "attendee/", data: {attendee: attendee.toJSON()}, success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { ErrorActions.serverError(e); } else { var a = new Attendee(); a.fromJSON(data); dispatch(attendeeCreated(a)); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } function fetchPopular() { return function (dispatch) { dispatch(fetchPopularAttendees()); $.ajax({ type: "GET", dataType: "json", url: "popularattendees/", success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { ErrorActions.serverError(e); } else { dispatch(popularAttendeesFetched(data.attendees.map(function(json) { var a = new Attendee(); a.fromJSON(json); return a; }))); } }, error: function(jqXHR, status, error) { ErrorActions.ajaxError(e); } }); }; } module.exports = { fetchAll: fetchAll, create: create, fetchPopular: fetchPopular };