Restangular: impossible to post complex json parameters? - javascript

I would like to send complex json to a put route:
Restangular.one('model3ds', model.uuid).put(
api_key: "blabla"
model3d: { is_public: true }
)
But it does not seems possible with Restangular, since it send:
api_key: "blabla"
model3d: "{\"is_public:\":true}"
Anyone knows how to change this behavior ?
Note: I can do that, but it's not possible if i have a full object to send, not only a property.
Restangular.one('model3ds', model.uuid).put(
"model3d[is_public]": true
)

Ok I found the (very complicated !) answer:
All the magic is in the custom keyword ;)
Restangular.one('model3ds', model.uuid).customPUT(
api_key: "blabla"
model3d: { is_public: true }
)

Another way without using customPUT is to provide the object as the second parameter of put method. For example:
var object = {
api_key: "blabla"
model3d: { is_public: true }
};
Restangular.one('model3ds', model.uuid).put(null, object);
More info: https://stackoverflow.com/a/17184167/1852787

Related

NodeJS : Need Help To build object with some Brackets and Braces

In my project I use request lib () and i would like to use qsStringifyOptions for query parametre but it's to much complicated in my case :/
In their documentation they link qs module to use qsStringifyOptions like them
I would like to have this URL
http://127.0.0.1:80/endpoint?foo=bar[baz:3]&aaa=[{baa:X,caa:XX,daa:[{eaa:Z,faa:ZZ}]}]&data[B]=BB&data[C]=CC
but I have this URL:
http://127.0.0.1:80/endpoint?foo=bar[baz:3]&aaa=[%7B%22baa%22:%22X%22,%22caa%22:%22XX%22,%22daa%22:[%7B%22eaa%22:%22Z%22,%22faa%22:%22ZZ%22%7D]%7D]&data[B]=BB&data[C]=CC
With this solution, the 'foo' attribute and data[B] and data[C] work fine but 'aaa' attribut not at all :
{ // some standar param URI, methode ...
useQuerystring: false,
qsStringifyOptions : {encodeValuesOnly: true, encode: false, indices: false},
qs : {
foo: 'bar[baz:1]',
aaa:'[{"baa":"X","caa":"XX","daa":[{"eaa":"Z","faa":"ZZ"}]}]',
data: {B:'BB', C:'CC'}
}
}
what i'm doing wrong? i just want it not to parse the 'aaa' attribute
thank you in advance for your help and your time

Duplicate keys in a REST connector query in loopback

I would like to ask if you know how could I duplicate parameters in a loopback REST connector query.
I have the following code:
details: {
'template': {
'method': 'GET',
'debug': true,
'url': 'https://www.example.com/data',
'timeout': 10000,
'headers': {
'Authorization': 'Bearer {token}'
},
'query': {
q: 'PHOTOS'
q: 'DETAILS',
id: '{id}'
},
'options': {
'useQuerystring': true
},
'responsePath': '$'
},
'functions': {
'searchData': [
'token',
'id'
]
}
}
The problem for that it is that it seems that loopback override the value of the parameter q by the last one, because I get only information for the last parameter.
Any idea how to solve it?
Thank you in avance.
You just have to pass them as an array:
'query': {
q: ['PHOTOS', 'DETAILS'],
id: '{id}'
},
Note that the options key, is passed to request and here's the documentation for useQuerystring:
useQuerystring - If true, use querystring to stringify and parse querystrings, otherwise use qs (default: false). Set this option
to true if you need arrays to be serialized as foo=bar&foo=baz
instead of the default foo[0]=bar&foo[1]=baz.
So if you remove it you'll end with something like ?q[0]=PHOTOS&q[1]=DETAILS.
You can also another option there:
qsStringifyOptions - object containing options to pass to the qs.stringify method.
Alternatively pass options to the
querystring.stringify
method using this format {sep:';', eq:':', options:{}}. For example,
to change the way arrays are converted to query strings using the qs
module pass the arrayFormat option with one of
indices|brackets|repeat
So you can actually end up with the same thing adding this:
"options": {
"qsStringifyOptions": {
"arrayFormat": "repeat"
}
}
And if you want to have just the brackets(something like this ?q[]=PHOTOS&q[]=DETAILS) you can specify brackets option:
"options": {
"qsStringifyOptions": {
"arrayFormat": "brackets"
}
}

Sequelize: .createAssociation() or .setAssociation doesn't update the original object with created data

I've been stuck on this for a while. Take the following code as an example:
models.Summoner.findOne({
include: [{ model: models.RankedStats, as: 'SummonerRankedStats', required: true }],
where: { summonerId: summonerId, server: server }
}).then(function(summoner) {
models.RankedStats.create({
totalWins: 0,
totalLosses: 0
}).then(function(rankedStats) {
summoner.setSummonerRankedStats(rankedStats).then(function() {
console.log(summoner.SummonerRankedStats)
//This outputs undefined
summoner.getSummonerRankedStats().then(function(srs) {
console.log(srs)
//This outputs the RankedStats that were just created
})
models.Summoner.findOne({
include: [{ model: models.RankedStats, as: 'SummonerRankedStats', required: true }],
where: { summonerId: summonerId, server: server }
}).then(function(summoner) {
console.log(summoner.SummonerRankedStats)
//This outputs the SummonerRankedStats object
})
})
})
})
So, to put it simply... If I have a Summoner (var summoner) and perform a .setAssociation() or .createAssociation() on it, and then log summoner, the data created isn't there. If I fetch it again from the database (with .getAssociation() or by searching for that Summoner again) I can access it, but I was hoping to avoid that extra DB call.
Is there a way to add this information to the original object when using .create() or .set()? It can be achieved by doing something like:
summoner.dataValues.SummonerRankedStats = rankedStats
But that seems somewhat hacky :)
Is there a correct way to do it, or does it even make any sense?
Thanks in advance!

Creating an envelope from a template returning "UNSPECIFIED_ERROR"

When I try to create an envelope from a template I get a response of:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
Here's what I'm doing so far:
First I login, which returns
{ loginAccounts:
[ { name: '*****',
accountId: '*****',
baseUrl: 'https://demo.docusign.net/restapi/v2/accounts/******',
isDefault: 'true',
userName: '***** ********',
userId: '*******-*****-*****-*****-*********',
email: '********#*******.com',
siteDescription: '' } ] }
So then I take the baseUrl out of that response and I attempt to create the envelope. I'm using the hapi framework and async.waterfall of the async library, so for anyone unfamiliar with either of these my use of the async library uses the next callback to call the next function which in this case would be to get the url for the iframe, and with our usage of the hapi framework AppServer.Wreck is roughy equivalent to request:
function prepareEnvelope(baseUrl, next) {
var createEntitlementTemplateId = "99C44F50-2C97-4074-896B-2454969CAEF7";
var getEnvelopeUrl = baseUrl + "/envelopes";
var options = {
headers: {
"X-DocuSign-Authentication": JSON.stringify(authHeader),
"Content-Type": "application/json",
"Accept": "application/json",
"Content-Disposition": "form-data"
},
body : JSON.stringify({
status: "sent",
emailSubject: "Test email subject",
emailBlurb: "My email blurb",
templateId: createEntitlementTemplateId,
templateRoles: [
{
email: "anemailaddress#gmail.com",
name: "Recipient Name",
roleName: "Signer1",
clientUserId: "1099", // TODO: replace with the user's id
tabs : {
textTabs : [
{
tabLabel : "acct_nmbr",
value : "123456"
},
{
tabLabel : "hm_phn_nmbr",
value : "8005882300"
},
{
tabLabel : "nm",
value : "Mr Foo Bar"
}
]
}
}
]
})
};
console.log("--------> options: ", options); // REMOVE THIS ====
AppServer.Wreck.post(getEnvelopeUrl, options, function(err, res, body) {
console.log("Request Envelope Result: \r\n", JSON.parse(body));
next(null, body, baseUrl);
});
}
And what I get back is:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
From a little googling it look like 'Non-static method requires a target.' is a C# error and doesn't really give me much indication of what part of my configuration object is wrong.
I've tried a simpler version of this call stripping out all of the tabs and clientUserId and I get the same response.
I created my template on the Docusign website and I haven't ruled out that something is set up incorrectly there. I created a template, confirmed that Docusign noticed the named form fields, and created a 'placeholder' templateRole.
Here's the templateRole placeholder:
Here's one of the named fields that I want to populate and corresponding data label:
As a side note, I was able to get the basic vanilla example working without named fields nor using a template using the docusign node package just fine but I didn't see any way to use tabs with named form fields with the library and decided that I'd rather have more fine-grained control over what I'm doing anyway and so I opted for just hitting the APIs.
Surprisingly when I search SO for the errorCode and message I'm getting I could only find one post without a resolution :/
Of course any help will be greatly appreciated. Please don't hesitate to let me know if you need any additional information.
Once I received feedback from Docusign that my api call had an empty body it didn't take but a couple minutes for me to realize that the issue was my options object containing a body property rather than a payload property, as is done in the hapi framework.

Nested attributes with Angular.js

I have been racking my brain and google all morning trying to figure this out but I have come to the conclusion that I need to ask the experts! I am trying to do nested attributes with Sinatra and Angular, don't worry about the Sinatra side of things I am just trying to get the data to the server side in the correct manner at the moment. Please see the code below for an explanation of
My Input:
<input type="text" placeholder="{{item.placeholder}}" ng-model="question.possible_answer_attributes[$index][title]" class="form-control" />
My model object:
$scope.question = new Question({
poll_id: parseInt($routeParams.id),
title: '',
kind: 'open',
possible_answer_attributes: [] // I believe the issue may lie here
});
My factory:
.factory('Question', function($resource) {
return $resource('/api/questions/:id', { id: '#id' }, {
'update' : { method: 'PUT' },
'get_by_poll' : { method: 'GET', url: '/api/questions_by_poll/:id', isArray: true }
});
})
My object at time of running save function:
{"poll_id"=>1, "title"=>"123123", "kind"=>"multiple", "possible_answer_attributes"=>[{"undefined"=>"412312"}, {"undefined"=>"1234124"}, {"undefined"=>"234235234"}]}
I do not understand why my "possible_answer_attributes" keys are coming through as "undefined". It may be something very simple that I have missed, but any feedback would be great!
Thanks in advance!
In order to address the title property, you would need to use a string to index into the object:
ng-model="question.possible_answer_attributes[$index]['title']"
This should hold as long as possible_answer_attributes array looks like:
[{ title: 'my title' }]

Categories

Resources