RESTful Multiple Updates (Example: Clear a Shopping Cart)? - rest

Let's say I have I have an online store with a "shopping cart" feature and I want to implement an "empty cart" link in a RESTful way.
For simplicity, let's say my resources are a Cart that contains CartItems, each of which has a Product. My URIs might be:
# add a product to the current user's Cart
POST /products/product_id/cart_items/
# remove a product from the current user's Cart
DELETE /cart_items/cart_item_id/
If so, what would the RESTful URI for the "empty cart" link look like?
Instead, I could think of the Cart as a general-purpose holder for Actions (as described here):
# add a product
# form data contains e.g., product_id=123&action=add
POST /carts/cart_id/actions/
# remove a product
# action_id is the id of the action adding product 123
DELETE actions/action_id
# empty cart
# form data contains action=clear
POST /carts/cart_id/actions/
This approach seems more complicated than it needs to be. What would be a better way?

Don't do the second approach. Funneling different actions through one endpoint does not feel RESTful IMO.
You have DELETE /cart_items/cart_item_id/ that removes cart_item_id from their cart. What about DELETE /cart_items/ to clear the cart itself?

Adding an item to a cart:
POST carts/{cartid}/items
Retrieving a specific item from the cart:
GET carts/{cartid}/items/{itemid}
Deleting a specific item from the cart:
DELETE carts/{cartid}/items/{itemid}
Getting the state of the cart:
GET carts/{cartid}/state
(Could return a value like 0,1 that indicates the number of items in the cart)
Emptying the cart:
PUT carts/{cartid}/state?state=0
Does this look intuitive?

DELETE /cart_items/ is an interesting idea that has also been discussed here.

Related

web2py: customizing form.vars to pass inputs id

I'm building a web app using web2py for attending employees.
this is the db in the model
db.define_table(
'employee',
Field('name'),
format = '%(name)s'
)
db.define_table(
'attendance',
Field('employee_id',db.employee),
Field('attend','boolean'),
Field('comments','text')
)
This is the controller:
employeeIDS=db(db.employee).select(db.employee.ALL)
table=[]
for eid in employeeIDS:
table.append([eid.name,INPUT(_type="checkbox",_name=eid.id,_id=eid.id),INPUT(_type="text",_name="comments",_id=eid.id)])
form=FORM( TABLE(TR("employee name","attended?","comments"),*[TR(*rows) for rows in table]),INPUT(_type="submit",_value="SUBMIT"))
if form.accepts(request,session):
response.flash="form accepted"
print(request.vars)
elif form.errors:
response.flash="form is invalid"
else:
response.flash="please fill the form"
return dict(form=form,vars=form.vars)
My question is this:
How can I access the id of the attend and comments fields in each row to associate these fields with the related employee. So, when I insert the form.vars to the attendance table, I guarantee that each employee recorded as attendance or absence and the related comments will inserted too.
Thanx
Instead of giving each comments input the same name, make the names unique, including the record ID as part of the name:
INPUT(_type="text", _name="comments_%s" % eid.id)
Then you will have form.vars.comments_1, form.vars.comments_2, etc.
As an aside, note that HTML id attributes should be unique, but you are using the value eid.id as the id attribute of both the checkbox input and the comments input.
I think a better choice is to use SQLFROM instead of FORM.
There you can customize the resulting form in the view right the layout you want to, even with HTML helper for tables, you have already used.
Please have a look at the signature of the SQLFORM - it offers a lot options as labels or showid (following the link just scroll down a little).
To exclude a field of being changed or even displayed in the SQLFORM use:
db.my_table.a_field.writable = False
db.my_table.a_field.readable = False
as described here - it's the same for SQLFORMS.

IBM Watson Conversation: How to capture and retrieve a list of values in a variable

I have a dialog where users can enter one or more country names.
How do I retrieve the values from the entity defined to store the responses.
Example :
Entity : Country
Question : Where did you travel to?
Answer : Africa, Thailand and
China.
How can I capture these 3 values in a list entity?
Henrik is right, just to add to that,
What he said will return them in an array, if you do
"countries": "<? entities['sys-location'] .toString() ?>"
you will get a comma separated list of the locations returned.
#sys-location entity in System Entities extracts location from the conversation. (Note: Ensure that you have switched on that entity as shown below)
You can now see that location has been extracted from conversation
You can use the system entity for locations, #sys-location. You need to turn that capability on for your workspace. See the wizard for entity creations.
In your dialog node where you want to capture the input in a list, you can assign those countries to a context variable. Switch to the JSON editor to edit variables. Then do something like:
"context": {
"countries": "<? entities['sys-location'] ?>"
},
See my collection of examples for context processing for something similar.
Its Quite Simple. Use
"countries": "#sys-location.values"
It will list all #sys-location values in array form.

SAPUI5: How to create a control hierarchy?

I hope you can help me with this. After reading all the documentation several times, googling for days, etc I don't find the way to do what i'm going to explain in a clean way, and in think I'm missing something because it's a really basic scenario.
I'm working with oData models, in this case 2 named models, "Model1", "Model2". Now what I want is to show a "parent" ComboBox based on an oData path, and a table that changes its items depending on the selection, in other words.
Model1 { //JSON representation of the data.
Accounts:[
"account 1": {invoices: ["invoice1", "invoice2", "invoice3"]},
"account 2": {invoices:["invoice4", "invoice5"]}
]
}
Combo Box:
<... items={Model1>/Accounts} /> -- This works and shows Account 1, and Account2.
Table
<Table... items="{Model1>Invoices}">
..
<items>
....
</items>
</Table>
What I want is the table to change it's context to the account selected on the ComboBox. The point is that this works, but the first time it loads the view, as there is no account selected, it calls the wrong odata path MYSERVICE/Invoices, instead of doing nothing, as the Account is not set yet, and the path for the invoices, once selected the account, shoud be MYSERVICE/Account('Account1')/Invoices for example.
I know I can achieve this with code, but I'm sure there must be a clean way to do this.
Seriously, this is driving me crazy.
Thanks for your help.
Are you sure that
items="{Model1>Invoices}"
triggers odata call? Because this is a relative path (without leading slash), normally it should not do the call.
What you can do:
Handle ComboBox selectionChange event;
In this event handler, create a path that you will bound the table to. In your case the path could look like this: "/Account(Account1)" - "/{EntitySetName}({KEY})". You can make use of createKey method of ODataModel2;
Set the table's context using the path:
oTable.bindObject({
path: sPath,
model: "Model1",
parameters: {
$expand: "Invoices"
}
});
Once the context is set, the relative binding will start working automatically and table will get the "Invoices"
I assume that the Account and Invoices are linked via navigation property and one-to-many cardinality, that's why the $expand parameter will load the corresponding invoices.

enterprise architect api: Add element to a collection

I have few short questions regarding Enterprise architect.
My question is regarding the automation interface. When following the instructions provided on this page: http://www.sparxsystems.com/uml_tool_guide/sdk_for_enterprise_architect/colle... in order to add a new element to the collection ( and the .eap file) it does not add the element. I can get data from the elements, modify and even delete them, but adding a new element does not work?
Instructions provided:
Call AddNew to add a new item.
Modify the item as required.
Call Update on the item to save it to the database.
Call Refresh on the collection to include it in the current set.
my java example:
elements is a collection of all the elements in the model...
org.sparx.Element elementEa = elements.AddNew("Requirement", "non-functional");
elementEa.Update();
elements.Refresh();
With the api is it possible to change the id or guid of an element since there are no methods specified in org.sparx for that?
One last thing... Is it possible to create a custom element in EA, for example a requirement which will not have the standard properties like difficulty, priority etc.. , but will have others? (normal properties, not tagged values)
The arguments to AddNew() are Name and Type, so to create a Requirement element you should specify "SomeRequirementName" and "Requirement".
You can't change the ID or GUID through the API, and your models would crash and burn if you did (connectors would be left dangling, elements would vanish from diagrams, etc, etc).
With an MDG Technology you can create very detailed stereotyped elements if you like, with their own visual representations (shape scripts) etc, but if you're after creating an element type with its own properties dialog the answer is no; there is no hook for a custom dialog in the API.
Collection<Package> packageCollection = myPackage.GetPackages();
Package consolidatedCfsSpecPackage = packageCollection.AddNew("somePackageName", "");
if (!consolidatedCfsSpecPackage.Update()) {
System.err.println("Not Updated: somePackageName");
}
packageCollection.Refresh();
This works for me. I suggest you to check return value of elementEa.Update() method you called. If it returns false, you can get the reason by calling elementEa.GetLastError().

symfony form - delete embedded form object

I have a two Symfony forms:
ShoppingListForm
ShoppingListItemForm
I'm embedding the ShoppingListItemForm inside the ShoppingListForm many times. i.e. A shopping list contains many items.
So the ShoppingListItemForm consists of two widgets:
item_id (checkbox)
shopping_list_id (hidden - foreign key)
What I would like to do is delete the corresponding ShoppingListItem object if the object exists and the checkbox is left unchecked.
I'm not sure how this delete would occur? Would I use a post validator to see which fields have/haven't been checked? I'm a bit lost on this one.
I'd do this by over-riding the ShoppingListForm's updateObject method and putting your custom delete() etc calls in there (be sure to call parent::updateObject() within it).
Depending how you implement it, you may also need to remove the embedded forms and their values to ensure saving still works correctly for the remaining objects. Try without, but if you do, you need to clear the following:
unset($taintedValues['ShoppingListItem'][$key]);
unset($this->embeddedForms['ShoppingListItem'][$key]);
unset($this->validatorSchema['ShoppingListItem'][$key]);
unset($taintedFiles['ShoppingListItem'][$key]);
If you want to see a custom updateObject method to get an idea how to interact with values etc:
http://www.symfony-project.org/forms/1_2/en/11-Doctrine-Integration#chapter_11_sub_customizing_the_updateobject_method
personnally, I would loop through the existing list items to see whether the corresponding checkboxes are checked in the action, and call the delete() method on the items for which it is not the case. I don't think it is the purpose of a post validator, I would do this directly in the action.