Binding Model in nodejs with express-cassandra - express-cassandra

I just want to apply the Bind of the following tutorial and apply on my project:
http://express-cassandra.readthedocs.io/en/latest/usage/
My current model is on models directory called UserModel.js:
module.exports = {
fields:{
name : "text",
surname : "text",
age : "int",
created : "timestamp"
},
key:["name"]
}
And the index.js bind the last model:
var models = require('express-cassandra');
models.setDirectory( __dirname + '/models').bind(
{
clientOptions: {
contactPoints: ['127.0.0.1'],
protocolOptions: { port: 9042 },
keyspace: 'pop',
queryOptions: {consistency: models.consistencies.one}
},
ormOptions: {
defaultReplicationStrategy : {
class: 'SimpleStrategy',
replication_factor: 1
},
migration: 'safe'
createKeyspace:true
}
},
function(err) {
if(err) throw err;
}
);
module.exports{
models:models
}
It goes Ok with the connection, but after the succesfull connect to casandra db(localhost:9042), It show me a message :"Keyspace user_schema does not exist"
Can anyone give me an idea to fix that? may be doesnt load the model, But It seems ok, But before to load the model It doesnt recognise the Keyspace, And It is the right Keyspace of my db

I updated the express-cassandra and now It Works, issue was the compatibility

Related

Cannot read property 'udp' of undefined

I am trying to make a Chrome App to use UDP, but I can not pass simple UDP creation socket process. This is the error I get in the inspector window:
sockets.udp.create: TypeError: Cannot read property 'udp' of undefined
at Object.callback
The error is shown at this line:
chrome.sockets.udp.create({}, function(....
The manifest.json is this:
{
"manifest_version": 2,
"name" : "My App",
"description" : "My App Description",
"version" : "1.0",
"icons" : {
"16" : "icons/wl16.png",
"48" : "icons/wl48.png",
"128" : "icons/wl128.png"
},
"app" : {
"background" : {
"scripts": ["main.js"]
}
},
"sockets" : {
"udp" : {
"send" : ["*"],
"bind" : ["*"]
}
}
The main.js is as follows:
chrome.app.runtime.onLaunched.addListener(function() {
console.log('launched')
sendpack()
})
function sendpack() {
// Create the Socket
chrome.sockets.udp.create({}, function(socketInfo) {
// The socket is created, now we can send some data
var socketId = socketInfo.socketId;
chrome.socket.udp.bind(socketId, '127.0.0.1', 1345, function(result){
console.log('chrome.socket.bind: result = ' + result.toString());
});
var arrayBuffer=new ArrayBuffer(2);
arrayBuffer[0]=65;
arrayBuffer[1]=66;
chrome.sockets.udp.send(socketId, arrayBuffer,'127.0.0.1', 1337,function(sendInfo) {
console.log("sent " + sendInfo.bytesSent);
});
});
}
I copied everything from Chrome examples, but on the examples it works, on my app it doesnt.
If I print on the console the content of the object 'chrome.sockets.udp' it shows a valid object with 'create' method listed in it:
Object {onReceive: Event, onReceiveError: Event}
create: function()
What could be wrong?
I found the error, the bind call had bad object name:
chrome.socket.udp.bind
it should be in plural, "sockets"
chrome.sockets.udp.bind
I also mistakenly read the stack trace, from the bottom, not from the top.

Read and transmit JSON file from Express to Jade

I'm new to Express and Jade, can't find why Jade tells me the object is undefined.
I've a big JSON file about a collectionable card game, which structure is:
{
"LEA" : { /* set data */ },
"LEB" : { /* set data */ },
"2ED" : { /* set data */ },
...
}
and, for each set
"name" : "Nemesis",
"code" : "NMS",
"gathererCode" : "NE",
"oldCode" : "NEM",
"magicCardsInfoCode" : "ne",
"releaseDate" : "2000-02-14"
"border" : "black",
"type" : "expansion",
"block" : "Masques",
"onlineOnly" : false,
"booster" : [ "rare", ... ],
"cards" : [ {}, {}, {}, ... ]
I want to loop through the array of cards for a GETed set and display some informations about. This is my cards.js file
'use strict';
var express = require('express');
var router = express.Router();
var mtgjson = require('mtgjson');
router.get('/:set?', function(req, res){
var set = req.params.set;
if (set === undefined) {
res.send('respond with a resource');
} else {
mtgjson(function(err, data) {
if (err) return console.log(err);
res.render('cards', { selectedSet : data.set });
});
}
});
module.exports = router;
and this the jade template
extends layout
block content
h1 #{selectedSet.name}
ul
each card in selectedSet.cards
li #{card.rarity}
I'm getting
Cannot read property 'name' of undefined
Any suggestion will be much appreciated, I'm probably making some stupid error.
EDIT: New informations ------------------
When I console.log(data) I get the following, it seems right:
TOR:
{ name: 'Torment',
code: 'TOR',
magicCardsInfoCode: 'tr',
releaseDate: '2002-02-04',
border: 'black',
type: 'expansion',
block: 'Odyssey',
booster:
[ 'rare',
'uncommon',
...
'common' ],
cards:
[ [Object],
[Object],
[Object],
...
[Object],
[Object],
[Object] ] },
And if I console set It gives me the right string ( TOR in this example ).
Edit 2 -------------------------
If I pass the entire data object and the set variable to the jade template, I can achieve the final result but in a very sub-optimal way.
I've made something like this
block content
ul
each val, key in data
if key == set
li #{val.name}
each card in val.cards
p #{card.name}
SOLUTION ----
Just a stupid error: I just messed up with property accessors. I should use data[set] instead of data.set beacause var set is a literal.
See reference http://www.ecma-international.org/ecma-262/5.1/#sec-11.2.1
You need to use selectedSet.cards.rarity instead of cards.rarity. The only object you are passing to the template is your selectedSet object, and cards is nested within that.
I was using the wrong notation to access properties. I should use square brackets notation beacause the var set is a string literal, in this case the dot notation won't work.
See reference

Exception using a naming convention w/ Breeze Angular mySql Node Express stack

I'm able to successfully connect and query data from a mySql db via a Breeze/Angular client, following the todo-angular example. I switched out the db table and the GUI and was still ok. The problem starts when I try to use a naming convention. (I don't have control over the db that I have to connect to & I really don't want to use Uppercase_Underscored_Words in my client!)
I'm getting the following exception:
/Users/Sherri/Sites/awdb-web/node_modules/breeze-sequelize/node_modules/breeze-client/breeze.debug.js:1852
throw new Error("Unable to locate a registered object by the name: " + k
^
Error: Unable to locate a registered object by the name: NamingConvention.underscoreCamelCase
at Object.__config._fetchObject (/Users/Sherri/Sites/awdb-web/node_modules/breeze-sequelize/node_modules/breeze-client/breeze.debug.js:1852:13)
at MetadataStore.proto.importMetadata (/Users/Sherri/Sites/awdb-web/node_modules/breeze-sequelize/node_modules/breeze-client/breeze.debug.js:6517:40)
at new module.exports.MetadataMapper (/Users/Sherri/Sites/awdb-web/node_modules/breeze-sequelize/MetadataMapper.js:19:8)
at SequelizeManager.importMetadata (/Users/Sherri/Sites/awdb-web/node_modules/breeze-sequelize/SequelizeManager.js:46:24)
at createSequelizeManager (/Users/Sherri/Sites/awdb-web/server/routes.js:114:8)
at /Users/Sherri/Sites/awdb-web/server/routes.js:23:27
When I take the "namingConvention": "camelCase" line out of the metadata.json file, the error goes away, but of course, the database property is not able to be correctly converted.
Here is the relevant code I use to set up the Entity Manager: (EDIT: I'm pretty sure my problem is server side and has nothing to do with this code, though)
var namingConvention = new UnderscoreCamelCaseConvention();
namingConvention.setAsDefault();
breeze.core.config.initializeAdapterInstance("uriBuilder", "json");
var serviceName = 'breeze/awdb';
var manager = new breeze.EntityManager(serviceName);
// Take any server property name and make it camelCase for the client to use.
// also, save it so that we can convert from the client back to the server's name
function UnderscoreCamelCaseConvention() {
var serverNames = {
netPoints: 'netPoints',
netPointsSpent: 'netPointsSpent'
}; // every translated server name
return new breeze.NamingConvention({
name: 'underscoreCamelCase',
clientPropertyNameToServer: clientPropertyNameToServer,
serverPropertyNameToClient: serverPropertyNameToClient
});
function clientPropertyNameToServer(clientPropertyName) {
return serverNames[clientPropertyName];
}
function serverPropertyNameToClient(serverPropertyName) {
var clientName = _.camelCase(serverPropertyName);
serverNames[clientName] = serverPropertyName;
return clientName;
}
}
And here is a snippet of my metadata.json file:
{
"metadataVersion": "1.0.5",
"namingConvention": "underscoreCamelCase",
"localQueryComparisonOptions": "caseInsensitiveSQL",
"dataServices": [
{
"serviceName": "breeze/awdb/",
"hasServerMetadata": true,
"jsonResultsAdapter": "webApi_default",
"useJsonp": false
}
],
"structuralTypes": [
{
"shortName": "person",
"namespace": "AWdb.Models",
"autoGeneratedKeyType": "Identity",
"defaultResourceName": "people",
"dataProperties": [
{
"name": "Person_ID",
"dataType": "Int32",
"isNullable": false,
"defaultValue": 0,
"isPartOfKey": true,
"validators": [
{
"name": "required"
},
{
"min": -2147483648,
"max": 2147483647,
"name": "int32"
}
]
},
{
"name": "Household_ID",
"dataType": "Int32",
"validators": [
{
"min": -2147483648,
"max": 2147483647,
"name": "int32"
}
]
},
....
]
}
],
"resourceEntityTypeMap": {"people": "person:#AWdb.Models"}
}
EDIT:
Here is code from my routes.js file that gets the metadata.
var fs = require('fs');
var breezeSequelize = require('breeze-sequelize');
var SequelizeManager = breezeSequelize.SequelizeManager;
var SequelizeQuery = breezeSequelize.SequelizeQuery;
var SequelizeSaveHandler = breezeSequelize.SequelizeSaveHandler;
var breeze = breezeSequelize.breeze;
var EntityQuery = breeze.EntityQuery;
var dbConfig = {
host: 'localhost',
user: 'xx',
password: 'xx',
dbName: 'xx'
};
var _sequelizeManager = createSequelizeManager();
// _sequelizeManager.sync(true).then(seed).then(function(){
// console.log('db init successful');
// });
exports.init = init;
function init(app) {
app.get('/breeze/awdb/Metadata', function (req, res, next) {
try {
var metadata = readMetadata();
res.send(metadata);
} catch(e){
next(e);
}
});
function createSequelizeManager() {
var metadata = readMetadata();
var sm = new SequelizeManager(dbConfig);
sm.importMetadata(metadata);
return sm;
}
function readMetadata() {
var filename = "server/AWdbMetadata.json";
if (!fs.existsSync(filename)) {
filename = "AWdbMetadata.json";
if (!fs.existsSync(filename)) {
throw new Error("Unable to locate file: " + filename);
}
}
var metadata = fs.readFileSync(filename, 'utf8');
return JSON.parse(metadata);
}
Any ideas? Should I be able to use a custom naming convention when I'm on a node.js server, using a metadata.json file instead of a .net entity framework?
If I'm looking at this correctly, then I think your issue is the metadata on the server. If I understand correctly, your table and column names follow the Uppercase_Underscored_Word pattern. The Breeze/Sequelize stack on the server currently doesn't have the ability to convert names, so you must use the names of entities and properties exactly as they are in the DB schema. Otherwise, the Breeze to Sequelize translation will fail. You can still use a naming convention on the client to turn the underscored server names into whatever you want them to be on the client.
So, you need two metadata files. One for the server that is used by the Breeze/Sequelize stack and that uses names exactly as they are in the DB and then a separate metadata file for the client, where you can do the translation.

check the json data for comparing in extjs

I created a simple login page using extjs MVC to understand MVC architecture of extjs. As you can see below, I am trying to get the json data into the store and then I will check each username and password in that data with the entered login credentials. The thing in which I am confused right now is that, how to check the username and password from the retrieved json data present in store folder into the view folder? (Below code is only the related code with the problem)
I aware that this could invoke security threats, as I am checking on client side.
'view' folder --> Code.js
function checkJson(username, password){
//if matched, return true.
//else, return false.
}
'model' folder --> Code.js
Ext.define('AM.model.User', {
extend: 'Ext.data.Model',
fields: ['name', 'email']
});
'store' folder --> Code.js
Ext.define('LoginPage.store.Code', {
extend: 'Ext.data.Store',
model: 'LoginPage.model.Code',
autoLoad: true,
proxy: {
type: 'ajax',
api: {
read: 'data/loginResponse.json',
update: 'data/checkCredentials.json' //Contains: {"success": true}
},
reader: {
type: 'json',
root: 'loginResponse',
successProperty: 'success'
}
}
});
loginResponse.json
{
"form": {
"login": [
{
"username": "venkat",
"password": "123"
},
{
"username": "admin",
"password": "345"
}
]
}
You should put your checking part of the code to the Controller (views are for presentation). In view define some form with login and password fields. In Controller catch click event on form OK (Login) button, get form values (login + password), then use Ext.data.Store.query() method to find wether credentials fits or not like:
Look here for examples how to use controllers in MVC to catch events;
In your Controller put:
init: function() {
this.control({
'#form_ok_button': { // this is the `id` property of your form's Login button
click: function(button) {
var fValues = button.up('form').getValues(); // Assume your button is bound to the form
// Or you can use `Controller.refs` property (http://docs.sencha.com/ext-js/4-1/#!/api/Ext.app.Controller-cfg-refs) to get form
var matched = store.query('username', fValues.username);
if(matched.length && matched[0].get('password') === fValues.password) {
// login OK!
}
}
}
});
},
How to use refs (in Controller):
refs: [
{ ref: 'usernameField', selector: '#username_field' }, // username field id is "username_field"
{ ref: 'passwordField', selector: '#password_field' }, // password field id is "password_field"
],
init: function() {
this.control({
'#form_ok_button': {
click: function() {
// with `refs` autogetters are created for every `ref`:
var username_field = this.getUsernameField();
var password_field = this.getPasswordField();
}
}
})
}
You can read about referencing here.
For every Store in Ext.app.Controller.stores array autogetters are created too (in your case for Code store use this.getCodeStore() inside controller).
Here is the flow:
You get username and password field values with this.getUsernameField() and this.getPasswordField();
You query() store for username
If username exist in store, you check if password fits.

How to make a store with jsonreader using metadata in Extjs 4?

Is it possible to create a store that will read json, and use fields specified in the metadata in the json as a model?
I want to say something like:
var store = new Ext.data.Store({
autoLoad: {
params: {
metaNeeded: true
}
},
reader: new Ext.data.JsonReader({fields:[]}),
proxy: new Ext.data.HttpProxy({
api: {
url: 'php/chart-data.php'
}
})
});
I've tried a number of combinations however I cannot seem to get it to work.
I currently get the error "Cannot call method 'indexOf' of undefined". I've had others including "object has no read method".
The json I am sending is:
{
metadata:{
root:"rows",
sortInfo:{
field:"date",
direction:"ASC"
},
fields:[ {
name:"date"
}, {
name:"flow"
},{
name:"limit"
}
],
idProperty:"date"
},
success:true,
rows: << snip >>
}
Is it possible to have the store's model configured by the data that it receives, so I could use the same store later with different fields (e.g. date, flow, limit and temperature)?
I have gotten it to work with the following:
var store = new Ext.data.Store({
proxy: {
type: 'ajax',
url: 'php/chart-data2.php',
reader: new Ext.data.JsonReader({
fields:[]
})
}
});
And the php that sends the json:
'{"metaData":{
"root":"rows",
"fields": [
{"name":"date",
"type":"number",
"convert": function(val, rec) {
return val*1000
} },
{"name":"flow"},
{"name":"limit"}
]
},
"totalCount":'.count($chart).',
"success":true,
"rows":' . json_encode($chart) . '
}'
This now allows the server to specify the data (that's getting displayed in a chart), and can add in series dynamically. I don't know if it is good, but it works. I am kind of disappointed in the lack of documentation about this.