ExtJs:Initialize variable from Store - extjs4

Hi i am using ExtHs 4.
I have a global variable which needs to be initialized from the store.
var cp=0;
Ext.onReady(function(){
Ext.define('Init', {
singleton: true,
cp: 0
});
Ext.define('loggedUserList', {
extend: 'Ext.data.Model',
fields: ['id','name']
});
loggedUser = Ext.create('Ext.data.Store', {
model: 'loggedUserList',
autoLoad: true,
proxy: {
type: 'ajax',
url : url+'/lochweb/loch/users/getLoggedUser',
reader: {
type: 'json',
root: 'provider'
}
},
listeners: {
load:function(loggedUser){
Init.cp = loggedUser.getAt(0).data.id;
}
}
});
});
i am using the value of cp in another url as follows,
Ext.define('vocbList', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', mapping: 'id' },
{ name: 'code', mapping: 'code' },
{ name: 'loinc', mapping: 'loinc.loincNumber' }
]
});
var vocabulary = Ext.create('Ext.data.Store', {
model: 'vocbList',
autoLoad: true,
proxy: {
type: 'ajax',
url : url+'/lochweb/loch/vocabulary/getVocabularyByProvider?providerId='+Init.cp,
reader: {
type: 'json',
root: 'Vocabulary'
}
}
});
but its value is still 0.How to assign its value form store so that it can be reused for other purpose.
Thanks

What you need is a callback.
Store call is being done asynchronously so that the browser will not freeze while the store get the data from the database.
me.vocabulary.load({
scope: this,
callback: function (records, operation, success) {
//here the store has been loaded so records are not empty
}
});

In your Ext.onReady, define a global class like this:
Ext.define('Init', {
singleton: true,
cp: 0
});
Then you can get or set cp anywhere you want:
Init.cp = 'some';
var myCp = Init.cp;

Related

Relay mutation for React native returning 400 bad request?

I have been having SO much trouble trying to get a mutation to work.
Given this GraphQL Schema, can anyone PLEASE help me create a simple create User mutation? I don't understand what I am missing. I got it to a point where it throws a 400 error from the GraphQL server and it does not fire the resolve function.
var userType = new GraphQLObjectType({
name: 'User',
description: 'User creator',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLString),
description: 'The id of the user.'
},
email: {
type: GraphQLString,
description: 'The email of the user.'
},
business: {
type: GraphQLString,
description:
'The name of the business of the user as the app refers to it.'
},
businessDisplayName: {
type: GraphQLString,
description: 'The name of the business of the user as they typed it in.'
},
trips: {
type: new GraphQLList(tripType),
description: 'The trips of the user, or an empty list if they have none.',
resolve: (user, params, source, fieldASTs) => {
var projections = infoToProjection(fieldASTs)
return Trip.find(
{
_id: {
// to make it easily testable
$in: user.trips.map(id => id.toString())
}
},
projections,
function(err, docs) {
return docs
}
)
}
}
})
})
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'root',
fields: {
trips: {
type: new GraphQLList(tripType),
resolve: function() {
return Trip.find({})
}
},
users: {
type: new GraphQLList(userType),
resolve: function() {
return User.find({})
}
},
user: {
type: userType,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }, source, fieldASTs) => {
return User.findOne(
{ _id: id },
infoToProjection(fieldASTs),
function(err, doc) {
return doc
}
)
}
},
trip: {
type: tripType,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }, source, fieldASTs) => {
var projections = infoToProjection(fieldASTs)
return Trip.findOne({ _id: id }, projections, function(err, doc) {
return doc
})
}
}
}
}),
// mutation
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
createUser: {
name: 'createUser',
type: userType,
args: {
input: { type: new GraphQLInputObjectType({
name: 'user',
fields: {
business: { type: GraphQLString },
email: { type: GraphQLString },
businessDisplayName: { type: GraphQLString }
}
})
}},
resolve: (parentValue, args) => {
let user = new User({ ...args.input })
user.save()
return user
}
}
})
})
export var getProjections = infoToProjection
export default schema
This works with GraphiQL using the following queries or mutations:
mutation {
createUser(input:{business:"business", email: "e#mai.l", businessDisplayName: "businessDN"}) {
id
email
business
businessDisplayName
}
}
fragment UserFragment on User {
id
business
businessDisplayName
trips{
title
}
}
{
hideya: user(id: "someid") {
...UserFragment
}
}
I finally fixed the problem. Tried to understand the source of the problem so I used a new NetworkLayer to enable appropriate logging and meaningful error messages. Then threw the an error when my mutation failed. The error message was : "Cannot query field clientMutationId". Looked that up and found that to be able to mutate objects you need to have that field on your GraphQL type. So I added it.
Lesson learned: I highly recommend using react-relay-network-layer.
More details:
Here is my code for it:
import {
RelayNetworkLayer,
urlMiddleware,
batchMiddleware,
} from 'react-relay-network-layer';
Relay.injectNetworkLayer(new RelayNetworkLayer([
batchMiddleware({
batchUrl: 'http://localhost:3000/graphql',
}),
urlMiddleware({
url: 'http://localhost:3000/graphql',
}),
]));
Note: This enables logging and by default it's a simple console.log.
Here is how I threw the error:
const params = {
email: email.toLowerCase(),
businessDisplayName: business,
business: business.toLowerCase()
}
var onSuccess = () => {
console.log('Mutation successful!')
}
var onFailure = transaction => {
var error = transaction.getError() || new Error('Mutation failed.')
console.error(error)
}
Relay.Store.commitUpdate(new FindOrCreateUser({ user: { ...params } }), { onFailure, onSuccess })
And of course you always need to clean your cache and restart your packager.

How can I override builtin login method in Loopback?

I've created a new User model, based on builtin one. I'm trying this:
module.exports = function(TiUser) {
TiUser.on('dataSourceAttached', function(obj) {
var login = TiUser.login;
TiUser.login = function(credentials, include, cb) {
var result = login.apply(this, credentials);
// Do my stuff
cb(null, my_data);
};
});
};
But I can't get it working... What is wrong? or how could this be done right?
Thanks
You may want to consider adding an afterRemote() hook to login(). Now you can achieve to add role( using Role model ) to user. For example:
TiUser.afterRemote('login', function(ctx, next) {
//add role to the user.
next();
});
At the end I've created a new method instead of overriding a current one:
module.exports = function(TiUser) {
TiUser.auth = function(credentials, include, fn) {
var self = this;
self.login(credentials, include, function(err, token) {
authInfo = {
token: token
};
fn(err, authInfo);
});
};
TiUser.remoteMethod(
'auth',
{
description: 'Login method with Role data information embedded in return',
accepts: [
{arg: 'credentials', type: 'object', required: true, http: {source: 'body'}},
{arg: 'include', type: ['string'], http: {source: 'query' },
description: 'Related objects to include in the response. ' +
'See the description of return value for more details.'}
],
returns: {
arg: 'accessToken', type: 'object', root: true,
description: 'User Model'
},
http: {verb: 'post'}
}
);
};

i can load the model using direct but not from other server

**I am getting result for the below coding**
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['id', 'name', 'age'],
proxy: {
type: 'rest',
url : 'http://localhost:8085/sencha-touch-2.0.1.1-gpl/sencha-touch-2.0.1.1/docs/guides/data/examples/model_with_proxy/data/users/',
reader: {
type: 'json',
root: 'users'
}
}
});
**But when i try to get from other server i can't.I have tried this coding given below**
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['id', 'name', 'age'],
proxy: {
type: 'jsonp',
url : 'http://docs.sencha.com/touch/2-1/guides/data/examples/model_with_proxy/data/users/',
reader: {
type: 'json',
root: 'users'
}
}
});
var userStore;
Ext.require('Ext.data.Store');
Ext.onReady(function() {
// Uses the User Model's Proxy
userStore = Ext.create('Ext.data.Store', {
model: 'User',
autoLoad: true
});
// Gives us a reference to the User class
var User = Ext.ModelMgr.getModel('User');
var ed = Ext.create('User', {
name: 'Ed Spencer',
age : 25
});
// We can save Ed directly without having to add him to a Store first because we
// configured a RestProxy this will automatically send a POST request to the url data/users
ed.save({
success: function(ed) {
console.log("Saved Ed! His ID is "+ ed.getId());
}
});
// Load User 1 and do something with it (performs a GET request to /users/1)
User.load(1, {
success: function(user) {
console.log("Loaded user 1: " + user.get('name'));
}
});
});
I am getting the error
Uncaught TypeError: Object [object Object] has no method 'writeRecords' ext-all.js:18
Resource interpreted as Script but transferred with MIME type text/html: "http://docs.sencha.com/touch/2-1/guides/data/examples/model_with_proxy/data/users/?_dc=1352957198178&page=1&start=0&limit=25&callback=Ext.data.JsonP.callback1". ext-all.js:18
Uncaught SyntaxError: Unexpected token :
If anyone knows can share with me

How to use api attribute on proxy

I would like to know how to use the api attribute of a proxy in ST2
For now, I have this in my proxy configuration:
api: {
create : App.urls.create_object,
read : App.urls.load_object,
update : App.urls.update_object,
destroy : App.urls.destroy_object
}
But then, I don't know how to use it.
For instance, when I wanted to create a new object, I created an Ext.Ajax.request with these parameters :
url: App.urls.create_object,
params: {
'object': object
},
But now, how could I do the same with the api attribute ?
Could you help ?
Assuming you have a model like this:
Ext.define('User', {
fields: ['name', 'email'],
proxy: {
type: 'ajax',
api: {
create: 'my_create_url',
read: 'my_read_url',
update: 'my_update_url',
destroy: 'my_destroy_url'
}
}
});
create
var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed#sencha.com'});
user.save(); // will POST to the create url
update
var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed#sencha.com'});
user.save({
success: function(user) {
user.set('name', 'Robert Dougan');
user.save(); // will PUT update URL
}
});
read
Using a store:
var store = Ext.create('Ext.data.Store', {
model: 'User'
});
store.load(); // will GET to read URL
Using the model:
// will GET the read URL with the specified ID.
User.load(12, {
success: function(user) {
console.log(user);
}
});
destroy
var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed#sencha.com'});
user.save({
success: function(user) {
user.destroy(); // will DELETE destroy URL
}
});
There is more information about this on the Rest proxy in the Sencha Docs: http://docs.sencha.com/touch/2-0/#!/api/Ext.data.proxy.Rest
sync
You can also use the store sync method to batch create/update/destroy all the records in your store.
var store = Ext.create('Ext.data.Store', {
model: 'User'
});
store.add({ name: 'Robert Dougan', email: 'rob#sencha.com' });
store.sync(); // will batch update all the needed records

Sencha2 JsonP push variable to Panel

I am upgrading my app from Sencha 1 to Sencha 2 due to the fact that it handles JSONP a lot better.
I have my app set up and need to find out how I can push my JSONP results.
Here is my JSON request
var tweet = Ext.data.JsonP.request({
url: 'https://api.twitter.com/1/statuses/user_timeline.json',
params: {
'include_entities': true,
'screen_name': 'NynasBo',
'count': 1
},
callbackKey: 'callback',
success: function(data) {
Ext.each(data, function(i, item) {
var tweet = i.text;
});
}
});
And here is the function I am trying to push it too.
var contact = Ext.define('Nynas.view.Contact', {
extend: 'Ext.Panel',
xtype: 'contactcard',
config: {
title: 'Contact',
styleHtmlContent: true,
html: '' + tweet.success.tweet
},
});
But currently if I view my app I just get a undefined response.
I have verified the query and also made sure that it works, by simpling switching this line from
var tweet = i.text;
to
console.log(i.text);
You can see it will have a verified result
Remember, in an asynchronous environment, the callback will affect your value only after it has been used. So something like this should work:
Ext.define('Nynas.view.Contact', {
extend: 'Ext.Panel',
xtype: 'contactcard',
config: {
title: 'Contact',
styleHtmlContent: true,
html: ' '
},
});
var contact = Ext.create('Nynas.view.Contact');
var tweet = Ext.data.JsonP.request({
url: 'https://api.twitter.com/1/statuses/user_timeline.json',
params: {
'include_entities': true,
'screen_name': 'NynasBo',
'count': 1
},
callbackKey: 'callback',
success: function(result) {
contact.setHtml(result.data.text);
}
});