Maybe I'm not understanding the way Promise.promisifyAll works. I'm trying to promisify coinbase package.
Basically, the client's functions are promisified but the accounts returned by those functions don't appear to have the Async version: [TypeError: acc.getTransactionsAsync is not a function].
I've tried passing {multiArgs:true} as options to Promise.promisifyAll() as suggested in an answer to a similar question, but it didn't solve the problem. Any suggestion is appreciated.
Normal way of using the package (works):
var Client = require('coinbase').Client
var client = new Client({
'apiKey': '<snip>',
'apiSecret': '<snip>',
'baseApiUri': 'https://api.sandbox.coinbase.com/v2/',
'tokenUri': 'https://api.sandbox.coinbase.com/oauth/token'
});
//Callbacks
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acc) {
acc.getTransactions(null, function(err, txns) {
txns.forEach(function(txn) {
console.log('txn: ' + txn.id);
});
});
});
});
Promisified version not working (getTransactionsAsync is undefined, but the getAccountsAsync returns the accounts correctly):
var Promise = require('bluebird');
var Client = require('coinbase').Client;
var client = new Client({
'apiKey': '<snip>',
'apiSecret': '<snip>',
'baseApiUri': 'https://api.sandbox.coinbase.com/v2/',
'tokenUri': 'https://api.sandbox.coinbase.com/oauth/token'
});
Promise.promisifyAll(client);
//Promises
client.getAccountsAsync({}) //Works perfectly, returns the accounts
.then(function(accounts) {
return Promise.map(accounts, function(acc) {
return acc.getTransactionsAsync(null); //This function call is throwing the TypeError
});
})
.then(function(transactions) {
console.log('Transactions:');
transactions.forEach(function(tx) {
console.log(tx);
});
})
.catch(function(err) {
console.log(err);
});
EDIT:
Looking through the package I want to promisify, I realized that the functions I'm trying to call are from the model objects returned by the package. I think promisifyAll only parses the client functions, and the models are not being processed. I'm just not that well versed on how the parsing is made :(
This is the index.js (module exported)
var Account = require('./lib/model/Account.js'),
Address = require('./lib/model/Address.js'),
Buy = require('./lib/model/Buy.js'),
Checkout = require('./lib/model/Checkout.js'),
Client = require('./lib/Client.js'),
Deposit = require('./lib/model/Deposit.js'),
Merchant = require('./lib/model/Merchant.js'),
Notification = require('./lib/model/Notification.js'),
Order = require('./lib/model/Order.js'),
PaymentMethod = require('./lib/model/PaymentMethod.js'),
Sell = require('./lib/model/Sell.js'),
Transaction = require('./lib/model/Transaction.js'),
User = require('./lib/model/User.js'),
Withdrawal = require('./lib/model/Withdrawal.js');
var model = {
'Account' : Account,
'Address' : Address,
'Buy' : Buy,
'Checkout' : Checkout,
'Deposit' : Deposit,
'Merchant' : Merchant,
'Notification' : Notification,
'Order' : Order,
'PaymentMethod' : PaymentMethod,
'Sell' : Sell,
'Transaction' : Transaction,
'User' : User,
'Withdrawal' : Withdrawal
};
module.exports = {
'Client' : Client,
'model' : model
};
EDIT 2:
The Client requires it's own model modules, so Promise.promisifyAll should as expected with the object's properties without having the previous edit interfering. At this point I think there might be no other option that making my own Promises for all functions I will need that don't live directly under the client.
I think promisifyAll only parses the client functions, and the models are not being processed.
Not exactly. This has nothing to do with how promisifyAll is looking through the methods and properties. Rather, you are explicitly passing only the client methods to be promisified:
var Client = require('coinbase').Client;
var client = new Client(…);
Promise.promisifyAll(client);
There's no link from client to the models. Rather try to call promisifyAll on the whole module, not only the Client class:
var Client = Promise.promisifyAll(require('coinbase')).Client;
or if that doesn't work, Call promisifyAll on both the Client class and the models collection of classes:
var coinbase = require('coinbase');
var Client = Promise.promisifyAll(coinbase.Client);
Promise.promisifyAll(coinbase.model);
So, instead of editing the question again I'm adding my temporary workaround (with a slightly different function call but that had the same problem of not having the Async function). This promisifies the model modules by it's own and I'll need to create them on demand whenever I need an promisified function on the non-promisified version of the models returned by the client.
It's not what I would like to do, since more memory allocation is needed for each model that I want to make a promisified function call. But I prefer this approach over creating new modules for grouping new Promise(...) functions.
If a better solution is suggested I'll still mark that as solved.
var Promise = require('bluebird');
var Client = require('coinbase').Client;
var cbModel = require('coinbase').model;
var client = new Client({
'apiKey': '<snip>',
'apiSecret': '<snip>',
'baseApiUri': 'https://api.sandbox.coinbase.com/v2/',
'tokenUri': 'https://api.sandbox.coinbase.com/oauth/token'
});
Promise.promisifyAll(client);
Promise.promisifyAll(cbModel);
//Promises
client.getAccountAsync('primary')
.then(function(account) {
account = new cbModel.Account(client, account);
return account.getTransactionsAsync(null);
})
.then(function(transactions) {
console.log('Transactions:');
transactions.forEach(function(tx) {
console.log(tx.id);
});
})
.catch(function(err) {
console.log(err);
});
Related
I am trying to get data from another database before reading data in the table. However, I can't seem to find a way to access it properly.
The best I've got so far is based on some other examples both on Microsoft's documentation and on StackOverflow but they all seem to fail.
table.read(function (context) {
var results = context.tables("table2").read();
var text = results[0].column;
context.query.where({ columnName: text });
return context.execute();
});
I get an error when doing this saying that column doesn't exist.
As per your description, if I do not misunderstand, you want to query table2 in table1 operations in EasyTables scripts.
we can leverage "use()" to custom middleware to specify middleware to be executed for every request against the table as the description on the document of azure-mobile-apps sdk at
E.G.
var queries = require('azure-mobile-apps/src/query');
var insertMiddleware = function(req,res,next){
var table = req.azureMobile.tables('table2'),
query = queries.create('table2')
.where({ TestProperty : req.body.testproperty });
table.read(query).then(function(results) {
if(results){
req.someStoreData = somehander(results); //some hander operations here to get what you want to store and will use in next step
next();
}else{
res.send("no data");
}
});
};
table.insert.use(insertMiddleware, table.operation);
table.insert(function (context) {
console.log(context.req.someStoreData);
return context.execute();
});
More example:
async function filterByAllowedDomain(context) {
var domains = await context.tables('domains')
.where({ allowed: true })
.read();
var categories = await context.tables('categories')
.where(function (ids) {
return this.domainId in ids;
}, domains.map(d => d.id))
.read();
context.query.where(function (ids) {
return this.categoryId in ids;
}, categories.map(c => c.id));
return context.execute(); }
The tables module in azure-mobile-apps-node sdk contains functionality for adding tables to an Azure Mobile App. It returns a router that can be attached to an express app with some additional functions for registering tables. Which actually leverage Azure SQL (SQL Server database service on Azure).
Hope it helps.
I have the following code that does not work currently.
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models.
//Alter table as needed but do NOT force the change. If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
models.users.create({
name: 'joe',
loggedIn: true
}).then( task => {
console.log("saved user!!!!!");
});
process.exit();//close the nodeJS Script
}).catch(function(error) {
console.log(error);
});
sequelize-lib.js
var Sequelize = require('sequelize');
exports.getSequelizeConnection = function(stage){
var argv = require('minimist')(process.argv.slice(2)); //If this file is being used in a script, this will attempt to get information from the argument stage passed if it exists
//Change connection settings based on stage variable. Assume localhost by default.
var dbname = argv['stage'] ? argv['stage']+"_db" : 'localdb';
var dbuser = argv['stage'] ? process.env.RDS_USERNAME : 'admin';
var dbpass = argv['stage'] ? process.env.RDS_PASSWORD : 'local123';
var dbhost = argv['stage'] ? "database-"+argv['stage']+".whatever.com" : 'localhost';
//If state variable used during require overide any arguments passed.
if(stage){
dbname = stage+"_db";
dbuser = process.env.RDS_USERNAME
dbpass = process.env.RDS_PASSWORD
dbhost = "database-"+stage+".whatever.com"
}
var connection = new Sequelize(dbname,dbuser,dbpass, {
dialect: 'mysql',
operatorsAliases: false, //This gets rid of a sequelize deprecated warning , refer https://github.com/sequelize/sequelize/issues/8417
host: dbhost
});
return connection;
}
exports.setModels = function(connection){
//Import all the known models for the project.
const fs = require('fs');
const dir = __dirname+'/../models';
var models = {}; //empty model object for adding model instances in file loop below.
//#JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
fs.readdirSync(dir).forEach(file => {
console.log(file);
//Split the .js part of the filename
var arr = file.split(".");
var name = arr[0].toLowerCase();
//Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
models[name] = connection.import(__dirname + "/../models/"+file);
})
//Showcase the final model.
console.log(models);
return models; //This returns a model with reference to the sequelize models
}
I can't get the create command to work however with this setup. My guess is the variables must not be passing through correctly somehow. I'm not sure what I'm doing wrong?
The create command definitely works because if in the sequelize-lib.js I modify the setModels function to this...
exports.setModels = function(connection){
//Import all the known models for the project.
const fs = require('fs');
const dir = __dirname+'/../models';
var models = {}; //empty model object for adding model instances in file loop below.
//#JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
fs.readdirSync(dir).forEach(file => {
console.log(file);
//Split the .js part of the filename
var arr = file.split(".");
var name = arr[0].toLowerCase();
//Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
models[name] = connection.import(__dirname + "/../models/"+file);
models[name].create({
"name":"joe",
"loggedIn":true
});
})
//Showcase the final model.
console.log(models);
return models; //This returns a model with reference to the sequelize models
}
Then it works and I see the item added to the database! (refer to proof image below)
Take note, I am simply running create on the variable at this point. What am I doing wrong where the model object is not passing between files correctly? Weird part is I don't get any errors thrown in the main file?? It's as if everything is defined but empty or something and the command is never run and nothing added to the database.
I tried this in the main file also and no luck.
models["users"].create({
name: 'joe',
loggedIn: true
}).then( task => {
console.log("saved user!!!!!");
});
The purpose of this all is to read models automatically from the model directory and create instances that are ready to go for every model, even if new one's are added in the future.
UPDATE::
So I did another test that was interesting, it seems that the create function won't work in the .then() function of the sync command. It looks like it was passing it correctly though. After changing the front page to this...
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.
models["users"].create({
"name":"joe",
"loggedIn":true
});
//Alter table as needed but do NOT force the change. If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
process.exit();//close the nodeJS Script
}).catch(function(error) {
console.log(error);
});
Doing this seems to get create to work. I'm not sure if this is good form or not though since the database might not be created at this point? I need a way to get it to work in the sync function.
Well I answered my question finally, but I'm not sure I like the answer.
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.
//Alter table as needed but do NOT force the change. If an error occurs we will fix manually.
connection.sync({ alter: false, force: false }).then( () => {
models["users"].create({
"name":"joe",
"loggedIn":true
}).then( user => {
console.log("finished, with user.name="+user.name);
process.exit();
}).catch( error => {
console.log("Error Occured");
console.log(error);
});
}).catch(function(error) {
console.log(error);
});
turns out that process.exit was triggering before create would occur because create happens async. This means that all my code will have to constantly be running through callbacks...which seems like a nightmare a bit. I wonder if there is a better way?
I am currently using Microsoft Visual Studio 2015 & Cordova for mobile development.
I tried by going through PouchDB documentation and use whatever they gave
function insertDB() {
var db = new PouchDB("todos");
var remoteDB = new PouchDB("http://localhost:5984/todos");
db.put({
_id: 'mydoc',
title: 'Heroes'
}).then(function (response) {
// handle response
}).catch(function (err) {
console.log(err);
});
PouchDB.sync('remoteDB', 'http://localhost:5984/todos');
}
I used a button to invoke the insertDB() function, but I have errors.
<button onclick="insertDB()">Click Me!</button>
I kept getting error saying localDB not defined, PouchDB not defined. I know I did wrong because I've very new to PouchDB and I've never used it before.
May I know where I did wrong in?
Solution:
I realized that I linked the min.js of pouchdb but it couldn't find the file, thus the error of undefined. I then used <script src="//cdn.jsdelivr.net/pouchdb/5.4.5/pouchdb.min.js"></script> and problem was solved.
not defined means your pouchdb package is not initilized correctly
use npm or cdn
const PouchDB = require('pouchdb').default;
Everything is correct expect below line (Your Syntax is wrong)
var db = new PouchDB("todos");
var remoteDB = new PouchDB("http://localhost:5984/todos");
PouchDB.sync('remoteDB', 'http://localhost:5984/todos');
Correction
var db = new PouchDB("todos");//localdb
var remoteDB = new PouchDB("http://localhost:5984/todos");
PouchDB.sync('db', 'http://localhost:5984/todos');
in pouchdb when you call below line ,db will create.if db is not present
it update db ,if already present
var db = new PouchDB("todos");
so the above single line is used to create or update data by using put function
(if u pass _id and _rev) it update your db
if not pass _id and _rev it insert the new line
import your pouchdb
const PouchDB = require('pouchdb').default;
then
function insertDB() {
var db = new PouchDB("todos");
var remoteDB = new PouchDB("http://localhost:5984/todos");
db.put({
_id: 'mydoc',
title: 'Heroes'
}).then(function (response) {
// handle response
}).catch(function (err) {
console.log(err);
});
PouchDB.sync('db', 'http://localhost:5984/todos');
}
I have an issue using mongoose.
The application I am writing consists in a file watcher that notifies clients about certain events via email and socketio messages.
I made an example that shows the problem:
basically, there is a class called mainFileWatcher that contains a submodule which in turn watches for new files or folders created in the script directory, emitting an "event" event when that happens. The mainFileWatcher listens for that event and calls a static method of a mongoose Client model.
If you run the script setting REPL=true you'll be able to access a watcher.submodule object and manually emit an "event" event.
Now, if you manually trigger the event, you'll see a statement that
says that the "event" event was triggered and an email address as a response.
Otherwhise, if you create a file or a folder in the script folder, you'll
just see that statement. Actually, if you run the script with REPL=true
you'll get the email only after pressing any key, nothing otherwise.
The fact that you don't get the email address as a response means to me that
the code in the promise in mongoose model doesn't get called for some reason.
Here is the code, sorry I couldn't make it shorter
// run
// npm install mongoose bluebird inotify underscore
//
// If you run the script with REPL=true you get an interactive version
// that has as context the filewatcher that emit events in my original code.
// It can be acessed through the watcher.submodule object.
// The watcher triggers a "event" event when you create a file or a folder in the script
// directory.
//
// If you emit manually an "event" event with the watcher.submodule in the repl, you should see a
// statement that "event" was triggered and
// an email address (that belongs to a fake client created by the bootstrap
// function at startup).
// If instead you create a file or a folder in the script folder (or whatever folder you have setted),
// you should see this time you'll have no email response. Actually, if you run with REPL=true,
// you'll have no email response untill you press any key. If you run without REPL, you'll
// have no email response.
'use strict';
var mongoose = require('mongoose');
//mongoose.set('debug', true);
mongoose.Promise = require('bluebird');
var Schema = mongoose.Schema;
var EventEmitter = require('events');
var util = require('util');
var _ = require("underscore");
var Inotify = require('inotify').Inotify;
var inotify = new Inotify();
// Schema declaration
var clientSchema = new Schema({
emails: {
type: [String]
}
}, {strict:false});
clientSchema.statics.findMailSubscriptions = function (subscription, cb) {
this.find({
subscriptions: {$in: [subscription]},
mailNotifications: true
}).exec().then(function (clients) {
if(!clients || clients.length === 0) return cb(null, null);
var emails = [];
clients.forEach(function (client) {
Array.prototype.push.apply(emails, client.emails)
});
return cb(null, emails);
}).catch(function(err){
console.error(err);
})
};
var clientModel = mongoose.model('Client', clientSchema);
// Mongoose connection
mongoose.connect('mongodb://localhost:27017/test', function (err, db) {
if (err) console.error('Mongoose connect error: ', err);
});
mongoose.connection.on('connected', function () {
console.log('Mongoose connected');
});
// bootstrap function: it inserts a fake client in the database
function bootstrap() {
clientModel.findOne({c_id: "testClient"}).then(function (c) {
if(!c) {
var new_c = new clientModel({
"name": "Notifier",
"c_id": "testClient",
"subscriptions": ["orders"],
"registeredTo": "Daniele",
"emails": ["email#example.com"],
"mailNotifications": true
});
new_c.save(function(err){
if (err) console.error('Bootstrap Client Error while saving: ', err.message );
});
}
});
}
// submodule of the main file watcher: it looks for new files created in the script dir
var submoduleOfFileWatcher = function() {
var _this = this;
var handler = function (event) {
var mask = event.mask;
var type = mask & Inotify.IN_ISDIR ? 'directory' : 'file';
if (mask & Inotify.IN_CREATE) {
_this.emit("event", event);
}
}
var watcher = {
path: '.', // here you can change the path to watch if you want
watch_for: Inotify.IN_CREATE,
callback: handler
}
EventEmitter.call(this);
this.in_id = inotify.addWatch(watcher);
}
util.inherits(submoduleOfFileWatcher, EventEmitter);
// Main File Watcher (it contains all the submodules and listensto the events emitted by them)
var mainFileWatcher = function () {
this.start = function() {
bootstrap();
_.bindAll(this, "onEvent");
this.submodule = new submoduleOfFileWatcher();
this.submodule.on("event", this.onEvent)
};
this.onEvent = function() {
console.log("event triggered");
clientModel.findMailSubscriptions("orders", function(err, mails) {
if (err) console.error(err);
console.log(mails); // THIS IS THE CODE THAT OUTPUTS ONLY IF YOU TRIGGER THE "event" EVENT manually
})
}
}
// Instantiate and start the watcher
var watcher = new mainFileWatcher()
watcher.start();
// start the repl if asked
if (process.env.REPL === "true") {
var repl = require('repl');
var replServer = repl.start({
prompt: 'filewatcher via stdin> ',
input: process.stdin,
output: process.stdout
});
replServer.context.watcher = watcher;
}
Just copy and paste the code, install deps and run it.
Things I tried:
I changed the mongoose Promise object to use bluebird promises, hoping that
I could intercept some exception.
I browsed Mongoose calls with node-inspector and indeed the find method gets called and it seems that it throws no exceptions. I really can't figure out what's happening because I don't get any errors at all.
It is not the database connection (I tried to open one just before the findMailSubscriptions call and got an exception for trying to open an already opened connection).
I figure it might be some issues with scopes or promises.
Is there something I am missing about mongoose, or is it just my code that causes this behaviour?
This is maddening, how do I get a hold of a loopback model so I can programmatically work with it ? I have a Persisted model named "Notification". I can interact with it using the REST explorer. I want to be able to work with it within the server, i.e. Notification.find(...). I execute app.models() and can see it listed. I have done this:
var Notification = app.models.Notification;
and get a big fat "undefined". I have done this:
var Notification = loopback.Notification;
app.model(Notification);
var Notification = app.models.Notification;
and another big fat "undefined".
Please explain all I have to do to get a hold of a model I have defined using:
slc loopback:model
Thanks in advance
You can use ModelCtor.app.models.OtherModelName to access other models from you custom methods.
/** common/models/product.js **/
module.exports = function(Product) {
Product.createRandomName = function(cb) {
var Randomizer = Product.app.models.Randomizer;
Randomizer.createName(cb);
}
// this will not work as `Product.app` is not set yet
var Randomizer = Product.app.models.Randomizer;
}
/** common/models/randomizer.js **/
module.exports = function(Randomizer) {
Randomizer.createName = function(cb) {
process.nextTick(function() {
cb(null, 'random name');
});
};
}
/** server/model-config.js **/
{
"Product": {
"dataSource": "db"
},
"Randomizer": {
"dataSource": null
}
}
I know this post was here a long time ago. But since I got the same question recent days, here's what I figured out with the latest loopback api:
Loopback 2.19.0(the latest for 12th, July)
API, Get the Application object to which the Model is attached.: http://apidocs.strongloop.com/loopback/#model-getapp
You can get the application which your model was attached as following:
ModelX.js
module.exports = function(ModelX) {
//Example of disable the parent 'find' REST api, and creat a remote method called 'findA'
var isStatic = true;
ModelX.disableRemoteMethod('find', isStatic);
ModelX.findA = function (filter, cb) {
//Get the Application object which the model attached to, and we do what ever we want
ModelX.getApp(function(err, app){
if(err) throw err;
//App object returned in the callback
app.models.OtherModel.OtherMethod({}, function(){
if(err) throw err;
//Do whatever you what with the OtherModel.OtherMethod
//This give you the ability to access OtherModel within ModelX.
//...
});
});
}
//Expose the remote method with settings.
ModelX.remoteMethod(
'findA',
{
description: ["Remote method instaed of parent method from the PersistedModel",
"Can help you to impliment your own business logic"],
http:{path: '/finda', verb: 'get'},
accepts: {arg:'filter',
type:'object',
description: 'Filter defining fields, where, include, order, offset, and limit',
http:{source:'query'}},
returns: {type:'array', root:true}
}
);
};
Looks like I'm not doing well with the code block format here...
Also you should be careful about the timing when this 'getApp' get called, it matters because if you call this method very early when initializing the model, something like 'undefined' error will occur.