var params = {
ImageId: 'ami-23ebb513',
InstanceType: 't1.micro',
MinCount:1, MaxCount: 1
};
ec2.runInstances(params, function(err, data) {
})
This code is good to start with launch instances. But i am trying to customize the instance's security group, public key for ssh etc. How can we configure these params?
I see not much docs is available that lists out the params supported by aws-sdk.
You should be able to get most of what you want with params.
Params additions would be:
NetworkInterfaces: [{DeviceIndex:0, SubnetId: 'subnet-12345', AssociatePublicIpAddress:true, Groups: ['sg-12345']}],
KeyName: 'MyKey'
The only thing you can't really get with the ec2-runInstances is tag creation. That would come from a second api call within the first function, like so:
params = {Resources: [data['instanceId']], Tags: [
{Key: 'Name', Value: 'SomeName-' + data['instanceId']},
{Key: 'Project', Value: 'My Project'},
{Key: 'SubProject', Value: 'SpotInstanceAuto'},
{Key: 'Creator', Value: 'Jason Nichols'},
...
]};
ec2.createTags(params, function(err) {
console.log("Tagging instance", err ? "failure" : "success");
...
});
Related
Npm package: https://www.npmjs.com/package/dynamics-web-api
Version: 1.6.12
this.dynamicsWebApi.startBatch();
this.dynamicsWebApi.createRequest({
collection: 'accounts',
entity: createdAccountData,
contentId: '1',
});
this.dynamicsWebApi.createRequest({
collection: 'contacts',
entity: {
...contactData,
'parentcustomerid_account#odata.bind': '$1',
},
contentId: '2',
});
this.dynamicsWebApi.updateRequest({
collection: 'accounts',
key: '$1',
entity: {
'aw_Dashboard_Contact#odata.bind': '$2',
},
});
await this.dynamicsWebApi.executeBatch();
From the above code, I intend to create an account, a contact that links to the account, and finally, update the account to link to the contact.
CreateRequest 1 and 2 could execute successfully, but the updateRequest failed with the error message "DynamicsWebApi.executeBatch requires the request.key parameter to be of type String representing GUID or Alternate Key"
My question is that there is any way to use the contentId 1 as the key of the updateRequest?
You can use the deep insert to create account and contact record and link them.
I've created a model in backbone:
var app={};
app.pilot_id = $("#user_id").val();
app.Pilot = Backbone.Model.extend({
url: POST_SUBMITTER.root + 'pilotdata/v1/pilot/',
sync: function(method, model, options) {
return Backbone.sync(method, this, $.extend(options, {
beforeSend: function (xhr) {
xhr.setRequestHeader ('X-WP-NONCE', POST_SUBMITTER.nonce);
}
}))
},
defaults : {
lastName: 'Doe',
firstName: 'John'
},
initialize : function() {
this.fetch({ data: ({id: app.pilot_id})});
}
});
app.pilot = new app.Pilot();
{ after the fetch lastName will be 'Smith' and firstName will be 'Sue'
and I create a view with backform.js
app.PilotForm = Backform.Form.extend({
el: $("#personalInformation"),
events: {
"submit": function(e) {
e.preventDefault();this.model.save( {patch: true})
.done(function(req, status, err) {
alert( status + ', ' + err);
console.log(status, err);
})
.fail(function(req, status, err) {
alert( status + ', ' + err);
});
return false;
}
},
fields: [
{name: "id", label: "Id", control: "uneditable-input"},
{name: "firstName", label: "First Name", control: "input"},
{name: "lastName", label: "Last Name", control: "input"},
{control: "button", label: "Save to server"}
],});
new app.PilotForm({model: app.pilot}).render();
This is going to be a multi-page form. And only a few fields will need to be updated each time. So I would like to update the server with "PATCH" However ALL of the fields that have been pre-filled from the fetch are flagged at changed. Therefore everything is sent in the PATCH request.
After creating the new app.PilotForm... I've added
app.pilot.attributes={};
This does work; now when I change a field only that field is sent in the PATCH request. However, the documentation suggests it is bad to mess directly with the attributes hash. Is there a better way to do this?
You can use model method such as changedAttributes, previousAttributes etc to find the info you want to send to the server and then use that patch option of model.save:
If instead, you'd only like the changed attributes to be sent to the server, call model.save(attrs, {patch: true}). You'll get an HTTP PATCH request to the server with just the passed-in attributes.
Where attrs is whatever you want to be the payload
I've been over the docs quite a few times, but this aspect still isn't clear to me. It's entirely possible that I'm thinking backbone-relational does something that it doesn't.
I'm looking for the way to define relationships based on key to avoid all the boilerplate fetching nonsense.
Take the canonical Artists and Albums example:
An artist has many albums as defined by album.artist_id
/api/artist/62351 might return
{
id: 62351,
name:"Jimi Hendrix"
}
similarly /api/album?artist_id=62351 might return
[
{
id:5678,
name: "Are You Experienced?"
artist_id: 62351
},
{
id: 4321,
name: "Axis: Bold as love",
artist_id: 62351
}
]
How might I define Artist and Album relationships such that
var hendrixInstance = new Artist({id:62351});
hendrixInstance.get('albums');
would fetch and return a collection of albums based on the album foreign_key artist_id? It must just be some permutation of key/keySource/keyDestination that I've yet to try, or be a problem that backbone-relational isn't trying to solve, but my doc groking has failed and I think a concise answer to this on SO might help future Googlers.
var Artist = Backbone.RelationalModel.extend({
urlRoot: '/api/artist',
relations:[{
key: 'albums', //Docs say this is the foreign key name, but in practice it doesn't appear that way. Need keySource/Destination?
type: Backbone.HasMany,
reverseRelation: {
key: 'artist',
type: Backbone.HasOne
}
}]
});
var Album = Backbone.RelationalModel.extend({
urlRoot: '/api/album'
});
Bonus points to an example model that references its self adjacency list style with parent_id
So, #xzhang's method above kept me iterating on this problem. First off, I'd love to be proven wrong on this, but I haven't found a way that backbone-relational handles this problem without additional custom code. Since this in my mind is an incredibly basic example of a OneToMany relationship, I'm still holding out hope that I'm just not getting something obvious.
Here's what I ended up doing to handle the situation. Unfortunately it still does not automatically fetch from the server when someobject.fetch('somerelationship') is called, which is what I really want. The parse function won't be necessary for most people, but it's required for the api I'm calling.
First I set up a base collection from which to extend:
var BaseCollection = Backbone.Collection.extend({
initialize: function(models, options) {
if (_.isObject(options.relation)) {
this.url = '/api/'
+ options.relation.keySource
+ '?search.'+options.relation.reverseRelation.keySource
+ '=' + options.foreignId;
}
},
parse: function(res) { return res.success ? res.list : res },
});
Then a reusable helper function (could probably be rolled into BaseCollection) to assist with creating relationships
function collectionOptions(instance) {
return {"relation":this, "foreignId":instance.get('id') };
};
And finally, those relationships are told to use BaseCollection as their CollectionType, and the collectionOptions() helper is assigned to set collectionOptions.
var Form = BaseModel.extend({
urlRoot: '/api/form',
relations:[
{
key: 'fills',
keySource: 'fill',
relatedModel: Fill,
type: Backbone.HasMany,
collectionOptions: collectionOptions,
collectionType: BaseCollection,
reverseRelation: {
key: 'form',
keySource: 'form_id',
type: Backbone.HasOne
}
},{
key: 'children',
keySource: 'form',
relatedModel: 'Form',
type: Backbone.HasMany,
collectionOptions: collectionOptions,
collectionType: BaseCollection,
reverseRelation: {
key: 'parent',
keySource: 'parent_id',
type: Backbone.HasOne
}
}
]
});
This allows me to avoid changing the server side API to return a list of ids and then individually fetch those ids. Instead I can just:
var form = new Form({id:1});
form.get('children').fetch();
form.toJSON(); //now has {id:1, ..., ..., children:[child,child,child,...]}
An extension to autoFetch children on the first call to .get('children') would be just the ticket, but I haven't discovered how to do that without modifying backbone-relational itself.
I am facing the exactly problem (Backbone-relational hasmany best practices), after 2 days research and look into the source code, I don't think key/keySource/keyDestination will do the work (correct me if I am wrong).
So I end up with create my own relation type, so far works fine. This may not a good solution, but hope can help you.
var LazyMany = Backbone.HasMany.extend({
setRelated: function (related) {
var relation = this.options
, instance = this.instance
;
if (related && !_.result(related, 'url')) {
related.url = relation.relatedModel.prototype.urlRoot +
'?' + relation.reverseRelation.key + '=' + instance.id;
}
return LazyMany.__super__.setRelated.apply(this, arguments);
}
});
Then in your model:
var Album = Backbone.RelationalModel.extend({
urlRoot: '/api/album/'
});
var Artist = Backbone.RelationalModel.extend({
urlRoot: '/api/artist/',
relations:[{
key: 'albums',
type: LazyMany,
includeInJSON: false,
relatedModel: Album,
reverseRelation: {
key: 'artist',
// I didn't test this, I don't have artist_id, artist is "id" in my app
keySource: 'artist_id',
keyDestination: 'artist_id',
includeInJSON: 'id'
}
}]
});
So if you don't define a collectionType or your collection don't have a url field, LazyMany will create a collection with url: /api/album/?artist=62351.
Then you just need fetch the collection: artist.get('albums').fetch().
Hope this can help, and I am still looking for better solutions.
I would like to make a relation between two models User and Task using backbone-relational.
The relation between the two models is the following:
taskModel.creator_id = userModel.id
// TaskModel
var TaskModel = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
key: 'creator',
keySource: 'creator_id',
relatedModel: Users
}
],
// some code
});
// Task collection
var TaskCollection = Backbone.Collection.extend({
model: TaskModel,
// some code
});
// User Model
var User = Backbone.RelationalModel.extend({
// some code
});
Actually the problem is in the collection.models, please see the attached images:
Please check this jsfiddle: http://jsfiddle.net/2bsE9/5/
var user = new User(),
task = new Task(),
tasks = new Tasks();
task.fetch();
user.fetch();
tasks.fetch();
console.log(user.attributes, task.attributes, tasks.models);
P.S.:
Actually I am using requireJs to get the UserModel, so I cannot include quotes in relatedModel value.
define([
'models/user',
'backbone',
'relationalModel'
], function (User) {
"use strict";
var Task = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
key: 'creator',
keySource: 'creator_id',
relatedModel: User
}
],
});
);
Edit 2:
http://jsfiddle.net/2bsE9/13/
I updated the jsfiddle to reflect the changes I suggested below. As long as you are calling toJSON on your task, what gets to the server is a json object with the creator_id property set to the actual id of the user. The keyDestination here is redundant as the documentation states it is set automatically if you use keySource.
Edit:
https://github.com/PaulUithol/Backbone-relational#keysource
https://github.com/PaulUithol/Backbone-relational#keydestination
https://github.com/PaulUithol/Backbone-relational#includeinjson
The combination of the three above might solve your issue.
var Task = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
// The User object can be accessed under the property 'creator'
key: 'creator',
// The User object will be fetched using the value supplied under the property 'creator_id'
keySource: 'creator_id',
// The User object will be serialized to the property 'creator_id'
keyDestination: 'creator_id',
// Only the '_id' property of the User object will be serialized
includeInJSON: Backbone.Model.prototype.idAttribute,
relatedModel: User
}
],
});
The documentation also states that the property specified by keySource or keyDestination should not be used by your code. The property cannot be accessed as an attribute.
Please try this and comment if that fixes your issue.
Btw, here is a nice blog post that uses backbone-relational end to end.
http://antoviaque.org/docs/tutorials/backbone-relational-tutorial/
Edit
Updated jsfiddle
The problem is that Backbone-Relational explicitly deletes the keySource to 'prevent leaky abstractions'. It has a hardcoded call to unset on the attribute, in Backbone-Relational:
// Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
if ( this.key !== this.keySource ) {
this.instance.unset( this.keySource, { silent: true } );
}
You will need to overwrite the unset method in your Task model:
var Task = Backbone.RelationalModel.extend({
urlRoot: ' ',
relations: [
{
type: Backbone.HasOne,
key: 'creator',
relatedModel: User,
keySource: 'creator_id'
}
],
unset: function(attr, options) {
if (attr == 'creator_id') {
return false;
}
// Original unset from Backbone.Model:
(options || (options = {})).unset = true;
return this.set(attr, null, options);
},
sync: function (method, model, options) {
options.success({
id: 1,
name: 'barTask',
creator_id: 1
});
}
});
Obvious problems with this approach are that you will need to modify your code if either Backbone changes its Backbone.Model.unset method or Backbone-Relational changes its keySource behavior.
I have the following two models: User and Job.
Each user can have just one job.
The user.attributes and job.attributes look like these (1):
(1)
user.attributes = {
id: 1,
name: 'barName',
job_id: 5
}
job.attributes = {
id: 5,
name: 'fooJob'
}
Let's suppose I want to make a relation between these two models:
The foreign key should be job_id
(2)
User = Backbone.ModelRelation.extend({
relations: [
{
type: Backbone.HasOne,
key: 'job_id',
keyDestination: 'job',
relatedModel: User
}
]
});
Using the code (2) the result will be:
(3)
user.attributes = {
id: 1,
name: 'barName',
job: job.attributes
}
As you can see the job_id from user.attributes is lost.
So, if I make a PUT request to the server, the server complains about the missing job_id attribute.
Any ideas how can I fix (3) in order to keep the job_id in user.attributes like (4)?
(4)
user.attributes = {
id: 1,
name: 'barName',
job_id: 5
job: job.attributes
}
Reference:
Paul Uithol - Backbone-relational
The workaround for me was to change the way the server reads the JSON posed.
So the server would read {user:{job:{id:1}}} rather than {user:{job_id:1}}
Note that we include a sub-object with an id attribute rather than use the job_id flat attribute.
Depending on which server side framework this can be configured.