I have a question regarding node orm2 hasMany association, my model definition is like this.
schemas/Channel.js
var model = db.define('channels', Channel, ChannelOptions);
var Channel = {
channel_name : String,
channel_email : String,
channel_id : String,
views : Number
};
var ChannelOptions = {
id : "channel_id",
methods: {
my_details : function (err) {
return this.channel_id +' '+ this.channel_name + ' ' + this.views;
}
}
};
schemas/network.js
var model = db.define('networks', Network, NetworkOptions);
var Channel = require('../schemas/Channel')(db);
model.hasMany('channels', Channel, {}, {autoFetch:true});
model.sync()
db.sync(function(){
console.log('DB SYNCHED');
});
var Network = {
network_id : Number,
name : String,
username : String,
logo : String,
website : String
};
var NetworkOptions = {
id : "network_id",
methods: {
}
};
It created a networks_channels table and I have filled it with a networkID and channelID. it is responding with the property (channels) but it is empty.
Is there something missing?
Just figured out what was wrong.
Its becauset I have set up the database table definitions before doing db.sync(). Turns out that its doing all the work for me. Clearing up the tables and refilling it with data did the trick.
Related
actor {
type Post = {
id : Int;
creater : String;
};
stable var Posts : [Post] = [];
func addPost(id : Int, creater : String) : () {
Posts.push(id, creater);
};
};
How can I push an object in that mutable array that is defined as Posts?
It seems that you are looking for Array.append, however as it is deprecated, you should use Buffers with preupgrade and postupgrade instead of the following:
import Array "mo:base/Array";
actor {
type Post = {
id : Int;
creator : Text;
};
stable var Posts = Array.init<Post>(1, { id = 0; creator = "" });
func addPost(id : Int, creator : Text) : () {
let NewPosts = Array.init<Post>(1, { id; creator });
Posts := Array.thaw(Array.append(Array.freeze(Posts), Array.freeze(NewPosts)));
};
};
I am not able to get response back if the email is already exist in DB.
I tried below example code. But I am getting null in response(see image)
Here is my api
{"query": "mutation authenticateUser($Phone: String!,$Email: String!, $type: String!, $otp: Int!) { authenticateUser(Phone : $Phone,Email: $Email,type : $type, otp : $otp) { status } }", "variables" : this.authenticateUserObj}
and Backend code :
router.post('/graphql', express_graphql(request => {
return {
schema: schema,
rootValue: root,
graphiql: true
}
}));
var root = {
authenticateUser : authenticateUser
};
var schema = buildSchema(`
type Mutation {
authenticateUser(Phone: String, Email: String,type: String,otp: Int,status: String): Authenticate
}
type Authenticate {
Phone : String
Email : String
Type : String
otp : Int
status: String
}
`);
var authenticateUser = function({Phone, Email, type, otp}) {
db.cypher({
query: "MATCH (n:userNodes) where n.Email='"+Email+"' RETURN count(*) as total",
}, function (err, results) {
if(results[0]['total'] > 0)
{
return {status: "Email already exist"};
}
});
}
do you get value in results[0] ? is it object or array ?
So i am building an application that takes contact information from the address book and stores it into a Titanium Model for use later on in the user journey.
All other information is storing and returning correctly however the image of the contact always comes back blank for some reason.
The code for storing the address book information is as follows
if (Ti.Contacts.contactsAuthorization == Ti.Contacts.AUTHORIZATION_AUTHORIZED){
var people = Titanium.Contacts.getAllPeople();
var totalContacts = people.length;
var addressbook = [];
Alloy.Collections.contactsModel.numberOfContacts();
Ti.API.info(numberOfContacts);
if(totalContacts > 0){
var phoneContacts = [];
for (var index = 0; index < totalContacts; index++){
var person = people[index];
phoneContacts.push({
name:person.fullName,
phoneNumber:person.phone,
profileImage:person.image,
contactID:person.identifier
});
}
Alloy.Collections.contactsModel.reset(phoneContacts);
Alloy.Collections.contactsModel.each(function(_m) {
_m.save();
});
}
} else if (Ti.Contacts.contactsAuthorization == Ti.Contacts.AUTHORIZATION_UNKNOWN){
Ti.Contacts.requestAuthorization(function(e){
//Authorization is unknown so requesting for authorization
if (e.success) {
} else {
}
});
} else {
}
}
The model definition is as follows
exports.definition = {
config: {
columns: {
"friendID": "INTEGER PRIMARY KEY AUTOINCREMENT",
"contactID": "string",
"name": "string",
"phoneNumber": "string",
"emailAddress": "string",
"profileImage": "blob"
},
adapter: {
type: "sql",
collection_name: "contactsModel",
idAttribute:"friendID"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
collection.trigger('sync');
},
}
}
*/
});
return Collection;
}
};
The image was working fine when collecting it from the address book and putting it into a list view. However when it's saved and then i attempt to retrieve it and put it into a list view where the problem occurs.
Thanks guys.
Something to consider is not to put all the information in the database. The reason is that when it changes on the device, those changes will not reflect in the records you've stored.
Here's how I approach it:
var db = Ti.Database.open( 'person' );
db.execute( "CREATE TABLE IF NOT EXISTS people( " +
"id INTEGER PRIMARY KEY, identifier TEXT, pid INTEGER);" );
var person = db.execute( 'SELECT id, identifier, pid FROM people' );
while( person.isValidRow( ) ) {
var contact,
contact_id;
if( OS_IOS ) {
contact_id = person.fieldByName( 'identifier' );
}
if( OS_ANDROID ) {
contact_id = person.fieldByName( 'pid' );
}
contact = Ti.Contacts.getPersonByIdentifier( contact_id );
var p_image = contact.image || "/images/user";
...
}
Essentially, I store the contact's ID in the database and then use that identifier to retrieve the user's info.
Note that the user's record does not always have an image, so it is a good idea to provide a default.
We have observed that at certain times accessing the JSONStore API's hangs for long time, to make it work we have to call the function again or app has to be taken to background & bring to foreground again.
NOTE : when application faces this issue, behaviour is same until we reinstall the app or reboot the device.
There doesn't appear to be any proper scenarios for this, we have searched many articles but did not find any solution, any solutions are welcome.
We observed this issue on Android devices like S5 and S4.
Here is my code Snippet:
function getWidgets(w_id, getWidgetsSuccessCallback, getWidgetsFailureCallback) {
var query = { user_id : w_id };
var options = {};
WL.JSONStore.get(StorageCollections.widgets).find(query, options)
.then(function(arrayResults) {
var count = arrayResults.length;
Logger.debug("getWidgets: success, count: " + count);
...
getWidgetsSuccessCallback(widgets);
})
.fail(function(errorObject) {
Logger.error("getWidgets: failed, error: " + JSON.stringify(errorObject));
getWidgetsFailureCallback(errorObject);
});}
Logs when everything works fine http://pastebin.com/NVP8ycTG
Logs when accessing JSON store hangs, it will work only when app taken to background & bring back to foreground again http://pastebin.com/eYzx57qC
JSON store is initialised as below
var collections = {
// User
user: {
searchFields: {
user_id : 'string',
user_name : 'string',
first_name : 'string',
last_name : 'string',
}
}
}};
// Storage encryption
var options = {};
if (key) {
options.password = key;
options.localKeyGen = true;
}
// Open the collection
var promise = WL.JSONStore.init(collections, options)
.then(function() {
Logger.debug("initializeAppStorage: " + JSON.stringify(collections) + " completed");
initAppStorageSuccessCallback(true);
return true;
})
// Handle failure
.fail(function(errorObject) {
Logger.error("initializeAppStorage: failed, error: " + errorObject.toString());
initAppStorageFailureCallback(errorObject.toString());
return false;
});
return promise;
Thanks.
Try this one :
function getWidgets(w_id, getWidgetsSuccessCallback, getWidgetsFailureCallback) {
var query = { key : w_id };
var options = {};
WL.JSONStore.get(StorageCollections.widgets).find(query, options)
.then(function(arrayResults) {
var count = arrayResults.length;
Logger.debug("getWidgets: success, count: " + count);
...
getWidgetsSuccessCallback(widgets);
})
.fail(function(errorObject) {
Logger.error("getWidgets: failed, error: " + JSON.stringify(errorObject));
getWidgetsFailureCallback(errorObject);
});}
I've got the below bit of code which pull back a list of the users facebook contacts along with their profile picture, however the images are not loading for each user, it is only showing the images for a few users.
fb.requestWithGraphPath('me/friends', {
fields : 'first_name,last_name,id,installed,picture.width(120).height(120),gender'
}, 'GET', function(e) {
if (e.success) {
var d = JSON.parse(e.result);
var pData = [];
var iData = [];
var row = d.data;
row = row.sort(sortByName)
for (var i = 0; i < d.data.length; i++) {
var img = row[i].picture.data.url
if (row[i].installed) {
pData.push({
properties : {
title : row[i].first_name + " " + row[i].last_name,
id : row[i].id,
image : img,
gender : row[i].gender,
accessoryType : Ti.UI.LIST_ACCESSORY_TYPE_DISCLOSURE
},
template : Ti.UI.LIST_ITEM_TEMPLATE_DEFAULT
});
} else {
iData.push({
properties : {
title : row[i].first_name + " " + row[i].last_name,
id : row[i].id,
image : img,
accessoryType : Ti.UI.LIST_ACCESSORY_TYPE_DISCLOSURE
},
template : Ti.UI.LIST_ITEM_TEMPLATE_DEFAULT
});
}
}
var play = Ti.UI.createListSection({
headerTitle : 'Play with Facebook Friends',
items : pData
});
var invite = Ti.UI.createListSection({
headerTitle : 'Invite Facebook Friends',
items : iData
});
var listView = Ti.UI.createListView({
sections : [play, invite],
});
self.add(listView)
} else {
alert("Facebook Error");
}
})
The images are stored in var img = row[i].picture.data.url and pushed into the data array as part of image : img but not all images are loading.
Is there a way to force the images to load? and show a default image whilst they are loading?
Here is a link to complete example to do exactly what you are trying to accomplish abaove
http://www.clearlyinnovative.com/blog/post/34758524584/alloy-listview-facebook-friends#.UgexZGRATrg