Performing URL substitution in a JSON request.

252 views
Skip to first unread message

Eric

unread,
Feb 7, 2012, 9:28:56 AM2/7/12
to Amplify
Hello all, I am struggling with a scenario that looks like a
limitation of Amplify, I was hoping a developer could confirm if the
below behavior was intended and if there's a any type of better method
to accomplish the goal of sending a JSON request to a RESTful style
URL (where a URL segment needs to be substituted).

Here is the definition of the request.

amplify.request.define(
"update_group",
"ajax",
{
url: "/portal/v1/group/{groupId}",
dataType: "json",
contentType: "application/json",
type: "POST",
decoder: function (data, status, xhr, success, error) {
if (status === "success") {
success(data, status, xhr);
}
else {
error(data, status, xhr);
}
}
}
);

In this example the request body is formatted correctly as JSON, but
the URL substitution of { groupId } is not performed correctly.

amplify.request("update_group",
JSON.stringify({
groupId: 82,
id: 82,
description: "New Description",
active: true,
agencyId: 1
}),
function (data, status) {
},
function (data, status) {
}
);

In this example, the URL substitution is correctly performed, but the
request body is sent as a query string that looks like this...
id=82&description=New+Description&active=true&agencyId=1.

The service expects a JSON object in the request body.

amplify.request("update_group",
{
groupId: 82,
id: 82,
description: "New Description",
active: true,
agencyId: 1
},
function (data, status) {
},
function (data, status) {
}
);

Scott González

unread,
Feb 7, 2012, 10:31:53 AM2/7/12
to ampl...@googlegroups.com
Hi Eric,

This is a known issue. Amplify does not currently support sending data in other formats. This is something we plan to fix.

Jim Cowart

unread,
Feb 14, 2012, 11:51:19 PM2/14/12
to Amplify
Eric,
Scott and I were looking over this together, and a solution would
be to use the dataMap feature in amplify.request. (See for more info.)

Your request definition would look like this: amplify.request.define(
"update_group",
"ajax",
{
url: "/portal/v1/group/{groupId}",
dataType: "json",
contentType: "application/json",
type: "POST",
decoder: function (data, status, xhr, success, error)
{
if (status === "success") {
success(data, status, xhr);
}
else {
error(data, status, xhr);
}
}
dataMap: function(data) {
if(typeof data === 'object') {
return JSON.stringify(data);
}
return data;
}
}

Since the definition has a contentType of "application/json", the
assumption can be made that if the data member is still an object, we
can stringify it to get a valid JSON body for the request. The
dataMap function will fire *after* the url substitution has occurred,
so it will not interfere with that process.

Thanks!
Jim
Reply all
Reply to author
Forward
0 new messages