Building post data best practices?


#1

Hello,

I’m building an app that uses Ember data with the mirage addon. I have a few routes and templates setup to GET data such as

/orders

/order/:id

and that all works fine. I have a route called create where I’d like to create a new order and do a POST to orders. I’ve found I can build the post data manually and send all within a controller (using store.createRecord) and that posts fine, but I have a component that is also trying to use and update the data that’s in the controller, and it’s starting to get messy.

Specifically, my create.js controller builds and sends the data, and I have a component called individual-pizza that contains the form elements for each individual pizza in a single order (attributes include size, toppings, etc.). I have an “Add another Pizza” button with an action (defined in the controller) that renders that template and an X with an action on the component that calls this.destroy() to remove that component (the idea is you can add/remove additional pizzas to your order). It’s almost working, but I’m finding I am trying to maintain my post data object in multiple places and in multiple files. I know there has got to be a better way to maintain the post data, and I’ve googled and read through the guides and docs and being new to this I’m not fully grasping how I should set this up (using a service, model, controller, component).

Here is my controllers/create.js file:

import Ember from 'ember';

export default Ember.Controller.extend({
	store: Ember.inject.service(),
	router: Ember.inject.service('-routing'),
	orderData: {
		'name': '',
		'totalCost': 0,
		'pizzas': [{
			'id': 0,
			'toppings': [{
				"name": "pepperoni",
				"selected": false
			},
			{
				"name": "sausage",
				"selected": false
			}]
		}],
		
	},
	actions:{
		addAnotherPizza(){
			var i = this.get('orderData.pizzas').length + 1;
			var pizzaTemplate = { 
				'id': i,
				'toppings': [{
					"name": "pepperoni",
					"selected": false
				},
				{
					"name": "sausage",
					"selected": false
				}]
			};
			this.get('orderData.pizzas').pushObject(pizzaTemplate);
		},
		createOrder() {
			var store = this.get('store');
			var order1 = this.get('orderData');
			const orderOne = store.createRecord('order', order1);
			orderOne.save()
			.then(() => {
			this.get('router').transitionTo('confirmation');
			});
		}
	}

});

And here is my create.js route:

import Ember from 'ember';

export default Ember.Route.extend({
	actions: {
		willTransition: function() {
			this.controller.set('orderData.pizzas', [{ 
				'id': 1,
				'toppings': [{
					"name": "pepperoni",
					"selected": false
				},
				{
					"name": "sausage",
					"selected": false
				}]
			}]);
		}
	}
});

Any direction as to how I should be structuring this part of the app according to best practices would be appreciated.

Thanks in advance!