Found error while going to fetch using ripple lib function getTransactions(address,Options) - ripple

[MissingLedgerHistoryError(Server is missing ledger history in the specified range)] error found
options.minLedgerVersion = +req.query.minLedgerVersion;
options.maxLedgerVersion = +req.query.maxLedgerVersion;
options.types = ['payment'];
api.connect().then(() => {
/* begin custom code ------------------------------------ */
return api.getTransactions(req.query.address,options)
}).then(transaction => {
console.log("Transactions info ::: ",transaction);
res.status(200).json(formatter.simpleFormat(transaction,true,"success"));
}).catch(err => {
console.log(err);
res.status(500).json(formatter.simpleFormat(null,false,"error"));
});

You'd find your answer in the response returned by the server_info method.
Look for: result/info/complete_ledgers and see if your requesting ledgers are included

Related

Unable to get response from the library

I try to execute this code and receive current blockchain block number
nodeInteraction.currentHeight('https://nodes.wavesplatform.com/').then((res) => {
console.log(res);
});
I did not forget to import the library
import { invokeScript, broadcast, nodeInteraction, waitForTx } from '#waves/waves-transactions';
This code is executed correctly.
nodeInteraction.accountData(dappaddress, baseUri).then((v) => {
window.dAppData = v;
if (v) {
window.dAppDataKeys = Object.keys(v);
console.log("dApp Account data:");
console.log(v);
console.log(JSON.stringify(v));
}
});
I'm using below library
https://wavesplatform.github.io/waves-transactions/globals.html#currentheight
I find an answer) I forgot to re-build my React app. Sorry.

rxjs subscription returning duplicates

After making a subscription from Angular service, the returning results are bunch of duplicates. For every call, the number of duplicates increase by one.
I tried console logging the results at various stages of the app. The duplicates are returned immediately after the promise get rendered
Angular Service code:
GetUserPendingApprovals(userid: string) {
let approvalsPending: any[] = [];
this.http
.get<{message, approvals: any}>(`/api/approvals/${userid}`)
.subscribe(approvals => {
console.log(approvals.approvals);
approvalsPending = approvals.approvals;
this.approvalsUpdated.next(approvalsPending);
approvalsPending = [];
});
}
getUserPendingApprovalsUpdateListener() {
return this.approvalsUpdated.asObservable();
}
node end point:
app.get("/api/approvals/:userid", (req, res, next) => {
// const urlData = req.params.userId;
//console.log(urlData);
const query = datastore
.createQuery('approvals')
.filter('src', '=', req.params.userid);
query.run().then(approvals => {
approvals.forEach(approval => console.log(approval));
console.log(approvals[0].length);
res.status(200).json(
{
message: "Request was processed successfully!",
approvals: approvals[0]
}
);
})
})
The console logging on node endpoint returns a proper count value for the results being queries for. However, console logging of the same results on the Angular service code returns duplicates and the number of duplicates increase by one for every call. Example: 1st call - 2 duplicates, 2nd call - 3 duplicates, 3rd call - 3 duplicates and so on.
More information...
I am making nested subscription from my angular component. Something like below -
ngOnInit() {
this.activatedRoute.params
.subscribe(
(params: Params) => {
....some code goes here...
this.revenueService.GetUserInvoicesThisWeek(this.userid);
this.currentWeekInvoicesSub = this.revenueService.GetUserInvoicesThisWeekListener()
.subscribe((revenueInfo: Revenue[]) => {
....some code goes here...
});
this.currentDayInvoicesSub = this.revenueService.GetUserInvoicesTodayListener()
.subscribe((todayRevenueInfo: Revenue[]) => {
....some code goes here...
});
this.approvalsService.GetUserPendingApprovals(this.userid);
this.approvalsSub = this.approvalsService.getUserApprovalsUpdateListener()
.subscribe((approvalsPending: any[]) => {
....some code goes here...
});
});
}
The last subscription is where i am facing problems. But i am pretty sure the rendered promise right after the node endpoint call is returning duplicates. Something which i mentioned in the beginning of this question.
Doubts:
What would be the root cause for these duplicates?
How to resolve this issue?
You are subscribing everytime this function gets called, so you're making a duplicate subscription everytime you change your route.
GetUserPendingApprovals(userid: string) {
let approvalsPending: any[] = [];
this.http
.get<{message, approvals: any}>(`/api/approvals/${userid}`)
.subscribe(approvals => {
console.log(approvals.approvals);
approvalsPending = approvals.approvals;
this.approvalsUpdated.next(approvalsPending);
approvalsPending = [];
});
}
Subscribe in the component instead in the service to fix this issue.
GetUserPendingApprovals(userid: string) {
return this.http
.get<{message, approvals: any}>(`/api/approvals/${userid}`)
}
Component ts:
ngOnInit(){
this.aprovalSub = this.approvalsService.GetUserPendingApprovals(this.userid);
.subscribe(approvals => {
approvalsService.approvalsPending = approvals.approvals;
approvalsService.approvalsUpdated.next(approvalsPending);
});
}
ngOnDestroy(){
if(this.aprovalSub !== undefined) this.aprovalSub.unsubscribe()
}
Clean up subscriptions when component gets destroyed or they will stay in memory and you will have subscriptions taking up memory.

Sails.JS - Created user wont return user object

I have a function in my Sails 1.0 application that adds a new user to the MongoDB and then at the end should return the User object as JSON...
The User does get added to the collection but it throws an error when trying to get the _id of the new User object. When I attempt to console.log() the createdUser it comes back as Undefined. Trying to figure out how the user can get created in Mongo but not be returned as an object in the same function?
In short the Register() function does the following:
Validates some inputs
Checks for valid email address
Encrypts the password
Finds Gravatar URL if applicable
Inserts User into collection
Set user._id in req.session (ERROR IS OCCURRING HERE)
Return User object as JSON
Error:
info: ·• Auto-migrating... (alter)
info: Hold tight, this could take a moment.
info: ✓ Auto-migration complete.
warn: Ignored attempt to bind route (/resend-username) to unknown action :: UserController.resendUsername
info:
info: .-..-.
info:
info: Sails <| .-..-.
info: v1.0.0-37 |\
info: /|.\
info: / || \
info: ,' |' \
info: .-'.-==|/_--'
info: `--'-------'
info: __---___--___---___--___---___--___
info: ____---___--___---___--___---___--___-__
info:
info: Server lifted in `D:\Development\Sails\goknack-sails-1.0`
info: To shut down Sails, press <CTRL> + C at any time.
debug: -------------------------------------------------------
debug: :: Tue Sep 05 2017 18:08:33 GMT-0500 (Central Daylight Time)
debug: Environment : development
debug: Port : 1337
debug: -------------------------------------------------------
undefined
D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:123
process.nextTick(function() { throw err; });
^
TypeError: Cannot read property '_id' of undefined
at D:\Development\Sails\goknack-sails-1.0\api\controllers\UserController.js:259:47
at D:\Development\Sails\goknack-sails-1.0\node_modules\parley\lib\private\Deferred.js:232:16
at _afterTalkingToAdapter (D:\Development\Sails\goknack-sails-1.0\node_modules\waterline\lib\waterline\methods\create.js:282:22)
at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:223:16
at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:123:18
at Object.success (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\build-std-adapter-method.js:61:47)
at afterMaybeArtificiallyWaiting (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:406:21)
at maybeArtificiallyWait (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:220:20)
at afterPotentiallyCaching (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:240:11)
at _cacheIfAppropriate (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:98:18)
at Function._interceptExit [as success] (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:111:9)
at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\machines\create-record.js:99:22
at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:437:18
at handleCallback (D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:120:56)
at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:743:5
at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb-core\lib\connection\pool.js:461:18
^
I have tried switching id to _id since it is Mongo but no luck, when I try to console.log createdUser it is Undefined.
The record is being created in the database... Any help on where I might be screwing up would be appreciated.
The full Register function I am using:
register: function (req, res) {
if (_.isUndefined(req.param('first'))) {
return res.badRequest('A first name is required!');
}
if (_.isUndefined(req.param('last'))) {
return res.badRequest('A last name is required!');
}
if (_.isUndefined(req.param('phone'))) {
return res.badRequest('A phone number is required!');
}
if (_.isUndefined(req.param('email'))) {
return res.badRequest('An email address is required!');
}
if (req.param('email') !== req.param('emailConfirm')) {
return res.badRequest('Email addresses do not match!');
}
if (_.isUndefined(req.param('password'))) {
return res.badRequest('A password is required!');
}
if (req.param('password').length < 6) {
return res.badRequest('Password must be at least 6 characters!');
}
if (req.param('password') !== req.param('confirmPassword')) {
return res.badRequest('Passwords do not match!');
}
if (_.isUndefined(req.param('tos'))) {
return res.badRequest('You must review and accept the Goknack Terms of Service & Privacy policy.');
}
Emailaddresses.validate({
string: req.param('email'),
}).exec({
// An unexpected error occurred.
error: function (err) {
return res.serverError(err);
},
// The provided string is not an email address.
invalid: function () {
return res.badRequest('Doesn\'t look like an email address to me!');
},
// OK.
success: function () {
Passwords.encryptPassword({
password: req.param('password'),
}).exec({
error: function (err) {
return res.serverError(err);
},
success: function (result) {
var options = {};
// gravitar image for user, if present
try {
options.gravatarURL = Gravatar.getImageUrl({
emailAddress: req.param('email')
}).execSync();
} catch (err) {
return res.serverError(err);
}
options.email = req.param('email');
options.username = req.param('username');
options.encryptedPassword = result;
options.deleted = false;
options.deletedDate = '';
options.admin = false;
options.banned = false;
options.paypalEmail = '';
// validate that email address has not been used before
User.find({email: req.param('email')}).exec(function(err, user) {
if (err) {
return res.negotiate(err);
}
if (user.length > 0) {
return res.badRequest('Invalid email, this email address is already in use.');
} else {
// create new user
User.create(options).exec(function (err, createdUser) {
if (err) {
console.log('the error is: ', err.invalidAttributes);
return res.negotiate(err);
}
// Log the user in
console.log(createdUser);
req.session.userId = createdUser._id;
// NOTHING IS BEING RETURNED IN createdUser
return res.json(createdUser);
});
}
});
}
});
}
});
},
As of sails 1.0 you need to specify that you want that model to be returned from the create call. To do that chain you create with a fetch call.
let createdUser = await User.create({ name: "Some name" }).fetch();
Also, await is now preferred over callbacks.
More on this here: https://next.sailsjs.com/documentation/reference/waterline-orm/models/create
That seems really strange. But I see one possible culprit... when you check for email uniqueness using User.find(), I don't recognize your use of find. You are calling it like:
User.find({email: req.param('email')}, function(err, user) {
//...
});
But I don't think find accepts a second input. You probably mean exec:
User.find({email: req.param('email')}).exec(function(err, user) {
//...
});
I can't follow the exact logic that leads to your specific error, but if you are somehow executing a function parameter that is not meant to be there, fixing that is a place to start.
I had the same issue. I then tried findOrCreate which returned the new record. I think this is a bug of Sails 1.0 as I never had this issue with 0.12.
My answer is late, but this might help someone in the future. This syntax:
User.find({email: req.param('email')}, function(err, user) {
//...
});
is the syntax used by Mike McNeil in the book Sails.js in action. It actually does work, at least in V0.12.
Concerning the error, the only reason I could think of to cause this problem, where the record is created but not returned is if you have created your own create() method on the UserController and you do not return the object once created.
I don't know if anyone figured this out, I've been having the same problem with Sails v1.0 for HOURS today.
I finally gave up and installed v0.12, ported my controller and models, and it worked fine.
This must be a bug in v1.0 where neither .exec(function(err,result){...}) nor .then(function(result){...}).catch(function(err){...}) returns an object!
I can attest that the await/fetch() method DOES work in v1.0, but I'm not sure how to implement with file upload. So v0.12 it remains.
Try this:
User.create({...}, function(err, createdUser) {
//...
}, { fetch: true });
I hope this helps :) The problem is that in sails 1.0 waterline does not autmoatically fetch the created/updated object, you need to add { fetch: true } in order the get the created object.
This method can also be used with await:
var createdUser = await User.create({...}).fetch();
But if you want to use the traditional Node callbacks, then the previous example should work !
I thing that the problem is the new architecture of controllers in SailsJS v1.
It is recomended to use actions. I had the same error. I fixed it with classic actions
Specifically I used this code in the file "api/controller/user/create.js":
module.exports = async function create (req, res) {
var userData = {
/* pick from req.body... */
}
var user = await User.create(userData).fetch();
if(user){
/* ... code to process the user object ... */
}
I hope this help other.
Best regards !

Tile38 Near by query node call back function is not working

I'm building a small GEO application and it's using http://tile38.com/ and https://www.npmjs.com/package/tile38 node module. Everything working fine but I'm unable to get result from the NEARBY query from the node module. It looks like the call back function isn't working, I've spent lot of time but couldn't find a way out. What I want is get the result from the nearby query and assign to a variable.
Here is the code:
var Tile38 = require('tile38');
var client = new Tile38({host: 'localhost', port: 9851, debug: true });
// set a simple lat/lng coordinate
client.set('fleet', 'truck1', [33.5123, -112.2693])
// set with additional fields
client.nearbyQuery('fleet').distance().point(33.5123, -112.2693, 6000).execute((err, results) => {
console.log("########");
// this callback will be called multiple times
if (err) {
console.error("something went wrong! " + err);
} else {
console.log(results + "##########");
}
});;
but when I try the following simple query it's working fine.
client.get('fleet', 'truck1').then(data => {
console.log(data); // prints coordinates in geoJSON format
}).catch(err => {
console.log(err); // id not found
});
ALSO when I try the RAW query in the tile38-cli it's working fine.
NEARBY fleet POINT 33.5123 -112.2693 6000
Any help would appreciated.
Thanks in advance.
EDIT
I tried the following also but didn't work.
let query = client.nearbyQuery('fleet').distance().point(33.5123, -112.2693, 6000)
query.execute(function(results).then(results => {
console.dir(results); // results is an object.
}))
Receiving following error
query.execute(function(results).then(results => {
^
SyntaxError: Unexpected token .
the author of the node library for Tile38 here. Sorry for the trouble getting this working. I noticed a typo in the readme which may have thrown you off. I will correct this.
The execute() method returns a Promise, and (as you already figured out) the example should have stated
query.execute().then(results => {
console.dir(results);
});
instead of
query.execute(function(results).then(results => {
console.dir(results);
});
After long time debugging I found that following code is working:
let query = client.nearbyQuery('fleet').distance().point(33.5123, -112.2693, 6000)
query.execute().then(data => {
console.dir(results); // results is an object.
}))

Using .batch with list of parameters in pg-promise

I'm running nodejs and pg-promise, and would like to use the batch function for creating a transaction with a BEGIN and COMMIT surrounding the multiple UPDATEs.
This is my code:
db.tx(function (t) {
return this.batch(function() {
for (var i = 0; i < cars.length; i++) {
return db.any('UPDATE ... ', [car_id, cars[i].votes]);
}
});
})
However, it seems not to be working as nothing happens. Isn't it possible to create my batch-list for input like that?
Method batch does not take a function as parameter, it takes an array of promises to resolve.
And there are plenty of examples of how to use it (on StackOverflow also), starting from the official documentation: Transactions.
For a set of updates you would simply create an array of update queries and then execute them using batch:
db.tx(t => {
const queries = cars.map(c => {
return t.none('UPDATE ... ', [c.car_id, c.votes]);
});
return t.batch(queries);
})
.then(data => {
// success
})
.catch(error => {
// error
});
Extra
Multiple updates of the same type can be executed as a single query, for a much better performance. See Performance Boost and method helpers.update.

Resources