Here is the JSON Object which i need to form.
{
"Header1": {
"Login": {
"SiteId": "",
"UserName": "",
"UserPassword": "",
"UserAlias": ""
},
"Credential": {
"Login": "",
"Password": ""
}
},
"Header2": {
"DestinationID": "",
"UserID": "",
"SourceID": ""
}
}
On the click of login, i need to form this JSON and send to my service using backbone.js. I am just confused on where to form this in backbone.js
var Client = Backbone.Model.extend({
defaults: {
}
});
Should i add my JSON Object to defaults and use them?
The backbone model usually relates to a model or db table on the server side. With this in mind you can use #model.set(attributes) to set the value in the model and then use #model.save to send to the server. If you are storing objects on your server model just define them in backbone before setting in the model.
#model = new Client()
new_object = new Object()
new_object.site_id = ""
new_object.UserName = ""
etc..
#model.set(
Header1: new_object,
Header2: somethingelse
)
#model.save()
If this is not the case and the model doesn't correspond to a model or table on the server you might be better off just using JQuery Ajax call and manually construct the JSON you need as above. Hope this helps.
Related
I'm trying to create a custom graphql schema to use on my graphql yoga server. The graphql yoga server is just a proxy to another graphql API from which I have managed to retrieve a schema from in JSON format. Here is a preview of what that schema looks like:
{
"data": {
"__schema": {
"queryType": {
"name": "Query"
},
"mutationType": null,
"subscriptionType": null,
"types": [
{
"kind": "OBJECT",
"name": "Core",
"description": null,
"fields": [
{
"name": "_meta",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Meta",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "_linkType",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
I now want to take this generated JSON schema and use it to create a graphql schema to use in my graphql yoga server. I believe the correct way to do this is by using the new GraphQLSchema method from graphql along with a root query. Here is my code attempting this:
schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: schema.data.__schema
})
});
The above code gives me the following error:
Error: Query.mutationType field config must be an object
Not entirely sure where it's going wrong or if this is the proper approach to creating a graphql schema from generated JSON?
The JSON you have is the results of an introspection query. Unfortunately, introspection will not allow you to copy a remote schema. That's because while it does identify what fields exist in a schema, it does not tell you anything about how they should be executed. For example, based on the snippet you posted, we know the remote server exposes a _meta query that returns a Meta type -- but we don't know what code to run to resolve the value returned by the query.
Technically, it's possible to pass the results of an introspection query to buildClientSchema from the graphql/utilities module. However, the schema will not be executable, as the docs point out:
Given the result of a client running the introspection query, creates and returns a GraphQLSchema instance which can be then used with all GraphQL.js tools, but cannot be used to execute a query, as introspection does not represent the "resolver", "parse" or "serialize" functions or any other server-internal mechanisms.
If you want to create a proxy to another GraphQL endpoint, the easiest way is to use makeRemoteExecutableSchema from graphql-tools.
Here's the example based on the docs:
import { HttpLink } from 'apollo-link-http';
import fetch from 'node-fetch';
const link = new HttpLink({ uri: 'http://your-endpoint-url/graphql', fetch });
async function getRemoteSchema () {
const schema = await introspectSchema(link);
return makeRemoteExecutableSchema({
schema,
link,
});
}
The resulting schema is a GraphQLSchema object that can be used like normal:
import { GraphQLServer } from 'graphql-yoga'
async function startServer () {
const schema = await introspectSchema(link);
const executableSchema = makeRemoteExecutableSchema({
schema,
link,
});
const server = new GraphQLServer({ schema: executableSchema })
server.start()
}
startServer()
graphql-tools also allows you to stitch schemas together if you not only wanted to proxy the existing endpoint, but wanted to add on to it as well.
I am using MongoDB in my Sails setup to store my collections.
I am making a POST request through an API, whose request body looks like this :
**THE REQUEST BODY**
{
"name":"Martin",
"phone":"5447874787",
"comment":"This is a comment",
"campaign":{
"campaign_id":123454587,
"name":"Digital Marketing",
"category":"Marketing",
"sub_category":"Digital",
"product_name":"no product",
"product_id":5417
}
}
This record is to be stored in my mongodb collection named "leads". My "Leads" model looks like this:
module.exports = {
schema: true,
attributes:{
name:{
required:true,
type:"string",
unique: true
},
phone:{
type:"string"
},
comment:{
type:"string"
},
campaign:{
model: 'lead_campaign_detail',
// via: "lead_model"
}
}
};
The associated "Lead_campaign_detail" model is as following
module.exports = {
attributes:{
campaign_id:{
required:true,
type:'integer'
},
name:{
type:"string"
},
category:{
type:"string"
},
sub_category:{
type:"string"
},
product_name:{
type:"string"
},
product_id:{
type:"integer"
}
}
};
And My controller handler is:
create_lead_api:function(req, res){
Leads.create(params, function(err, resp){
if(err) return res.negotiate(err);
else return res.json(resp);
})
},
WHAT I HAVE TRIED
1> I tried using .native(). It creates a new record BUT it does not care about the attributes in the model "Leads" or the other one. It just saves as the request is.
2> Tried creating using the .create(). It does not stores the nested values of index "campaign" in the request: the stored value looks like this:
{ **IN MY DB it looks like**
"name": "martin",
"phone": "5447874787",
"comment": "This is a comment",
"campaign": "579083f049cb6ad522a6dd3c",
"id": "579083f049cb6ad522a6dd3d"
}
I WANT TO
1> Store the record in the same format as the requested am sending.
2> Make use of the waterline ORM function .create() to achieve the same if possible.
3> .native() is also in option if my Model-attributes:{} can be used to bring in between before storing the record. I want to store only values defined in attributes:{ }
Any help is appreciated, Google is failing me.
Thanks
If you want the document in 'leads' collection to look like your request body, then you should use:
campaign: {
type: "json"
}
in your 'Leads' model, rather than linking to 'lead_campaign_detail' collection. You can then do away with the 'lead_campaign_detail' model.
By saying model: 'lead_campaign_detail' you are essentially linking the "Leads" document to "lead_campaign_detail", See Waterline One-way association and populate() for more details.
UPDATE
Ok, so I am still getting into the world of Backbone. But I have an issue with adding in localStorage into the Model.
So this is sorta off working, but I do not know what is going on?
var Model = Backbone.Model.extend({
//localStorage: new Backbone.LocalStorage("SomeCollection"),
url: "/GetMyData",
defaults: {
"id": "",
"datatest1": "",
"test2": ""
}
});
var NewTest = new Model();
NewTest.fetch();
console.log ( NewTest ); //This as DB data
console.log ( NewTest.attributes ); //This is empty
How can the 'attributes' on the 1st console.log contain db data and then the second one be completely empty? The 1st console.log is also empty, if I uncomment the localStorage, so I am guesting I doing something wrong?
Ok, I am not sure what I am doing wrong, but I am using Backbone and on a fetch call, save that id using the LocalStorage plugin. Now I have the fetch call and LocalStorage working apart but can not get them working together.
So my LocalStorage Code
var Model = Backbone.Model.extend({
localStorage: new Backbone.LocalStorage("SomeCollection"),
defaults: {
"id": "",
"datatest1": "",
"test2": ""
}
});
var NewTest2 = new Model();
NewTest2.set({
"id": "99",
"datatest1": "TEST-1-Q22",
"test2": "TEST-2-CL22"
});
NewTest2.save();
So this works, no problems with that. Now I add in a collection, and fetch data form my database. So my fetch code, with collection
var Model = Backbone.Model.extend({
defaults: {
"id": "",
"datatest1": "",
"test2": ""
}
});
var Col = Backbone.Collection.extend({
model: Model,
url: "/GetMyData"
});
var NewTest3 = new Col();
NewTest3.fetch();
console.log( NewTest3 );
I should also say that I am using PHP Slim as the base. The /GetMyData path gets the data from a MySQL database via a PDO connection, which I then convert into a JSON object for Backbone.
Which I assume is good, as that all works, the console.log's list of attributes displays the right data form my DB.
Now when I put the two together, I can not seem to get it to work.
var Model = Backbone.Model.extend({
defaults: {
"id": "",
"datatest1": "",
"test2": ""
}
});
var Col = Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage("SomeCollection2"),
model: Model,
url: "/GetMyData"
});
var NewTest4 = new Col();
NewTest4.fetch();
console.log( NewTest4.save() );
This console.log returns, Uncaught TypeError: undefined is not a function. So I am not sure why? When I set the data in my 1st test, it works fine. Now I have also tried moving the localStorge var into the model but with the same effect.
The main aim for doing this is so I can log all the data coming from the server. When I set a few different data tests, I very much like the way in which this plugin saved the data.
Thanks.
*Please note, I am dyslexic, so I may not have explained myself right, please tell me if there is anything I can re-word to explain myself better. Thank you for your understanding.
Overview
I have a JSON object being passed to my backbone model. I have a parse function in the backbone model to convert some of the incoming attributes. The issue is when I fetch this model the attributes are not parsed and are just added to the model. The image at the bottom shows that instead of converting password to Password and deleting password it just adds password to the attributes of the object.
Here is my code:
JSON
When I use postman to call my web service I get the response:
{"type":null,"idTeacher":1,"name":"Sean","password":"tst","email":null,"dob":1392940800000}
Model:
window.Teacher = Backbone.Model.extend({
urlRoot: "http://localhost:8080/SIMS/resource/teacher",
defaults: {
"id": null,
"Name": "",
"Password": "",
"email": "",
"dob": "",
"type": ""
},
parse: function(response){
response.id = response.idTeacher;
response.Password = response.password;
response.Name = response.name;
delete response.name;
delete resoponse.password;
delete response.idTeacher;
return response;
}
});
window.TeacherCollection = Backbone.Collection.extend({
model: Teacher,
url: "http://localhost:8080/SIMS/resource/teacher",
parse: function(response){
return response;
}
});
Main.js // This is
before: function(callback) {
if (this.teacherList) {
if (callback) callback();
} else {
console.log('........................................javascript........');
this.teacherList = new TeacherCollection();
console.log('Loading List: Size: ' + this.teacherList.length);
this.teacherList.fetch({success: function() {
console.log('........... ftech success...........');
$('#contents').html( new TeacherListView({model: app.teacherList}).render().el );
if (callback) callback();
}});
}
}
If I debug my Backbone I can see that my parse did not parse any of the variable and the delete calls in the parse did not work either.
UDATE ANSWER
Thanks for the help. The fact that I hadn't the code in the collection class was an issue. But the second reason was that I wasn't looping through the collection to change each of the attributes.
That's because when you call the fetch method for your collection, the parse method that is called is the parse of the collection and not the parse of your teacher model.
When you call the fetch method from the collection the collections expects to receive an array of models and not just one teacher as you described
You are defining your parse method in your Model but calling your Collection fetch method.
In this case, only the parse method of your Collection will be called.
I have an application which uses backbone js and jquery. I need to generate templates dynamically based on what response i get from the server. The scenario is like this... I have a dropdown of templates which I can choose, after I select any template from the dropdown, an api is called for that template which provides me with a structure like this
items:[
{
"vars":
{
"name":
{
"required": false,
"default": "abc"
},
"address":
{
"required": false,
"default": "xyz"
}
}
"tables": {}
}]
So how can I create dynamic form elements using this kind of server response?
You could use the backbone-forms plugin, and map your server response to a form object. Something like:
var data = {};
var schema = {};
var item = _.first(items);
_.each(item.vars, function(value, key) {
data[key] = value.default;
schema[key] = {
type:"Text",
validators:value.required ? ['required'] : undefined
};
});
var form = new Backbone.Form({data:data, schema:schema}).render();
That's just a simple, untested example. Check out the backbone-forms documentation, and see if it can do what you need.