Google translate API not working in firebase functions - node.js

I am struggling to figure out whether google-translate-api stopped working in firebase functions. I have the following code which used to work but now all I get is locale Not Supported.
exports.translateNow = functions.database.ref('/Translate/lang'.onWrite(event => {
let loc='en';//event.data.val();
console.log("LOCA "+loc);
translateMessage('Ik spreek Engels',loc).then(function(result){
console.log("PYAM ",result);
}).catch(function(err){
console.log("ERR ",err);
});
return true;});
The locale is read from firebase database but I've hard coded en for English which is still not working.
Here is translateMessage
let translateMessage=function(text,loc){
let theLoc=loc;
if(theLoc=='ab'||theLoc=='aa'||theLoc=='ak'||theLoc=='an'||theLoc=='as'||theLoc=='av'||theLoc=='ae'||theLoc=='ay'||theLoc=='bm'||theLoc=='ba'||theLoc=='bh'||theLoc=='ce'||theLoc=='zh'||theLoc=='ki'){
theLoc='en'
}
return new Promise(function(resolve,reject){
translate(text, {from: 'en', to: theLoc}).then(res => {
resolve(res.text);
}).catch(function(result){
reject("Not Supported");
});
});};
Please someone help here's my include const translate = require('google-translate-api');

Related

Mongodb Nodejs Regex Search

Hey I am making a website which as a partial search form. Reference from:https://www.youtube.com/watch?v=ZC2aRON3fWw&t=42s But I couldnt understand why it doesnt work. I use pug instead of hbs.
And these are my codes:
app.get('/sonuc', function(req, res, next){
var q = req.query.q;
Article.find({
title : {
$regex: new RegExp(q)
}
}, {
_id:0,
__v:0
}, function(err, data){
res.render('sonuc', {data:data})
}).limit(10);
});
});
Then this is my layout pug:
.ui-widget
form.form-inline.my-2.my-lg-0
input.form-control.mr-sm-2(type='text', onkeyup='showResults(this.value)', placeholder='Search',action='/article/'+sorgu, aria-label='Search')
button.btn.btn-secondary.my-2.my-sm-0(type='submit')
#search-results(style='width:60px;top:-1px;position:relative')
In this layout pug I thing the onkeyup issue is not working. How can I implement that fu nction on that form?
And ths is my main.js whihc takes query from database and write it in html form:
var showResults = debounce(function(arg){
var value = arg.trim();
if(value == "" || value.length <= o){
$("#search-results").fadOut();
return;
}else{
$("#search-results").fadeIn();
};
var jqhr = $.get('/article/' + value, function(data){
})
.done(function(data){
if(data.length == 0){
$("search-resuts").append('<p classs="lead text-center mt-2">No Results</p>');
}else{
data.forEach(x => {
$("search-resuts").append('<p class="m-2 lead"><img style="width:60px;" src="images/supreme1.jpg">' + x.title +'</p>');
});
}
})
.fail(function(err){
console.log(err);
})
}); 200;
function debounce(func, wait, immediate){
var timeout;
return function(){
var context = this;
args = arguments;
var later = function(){
timeout= null;
if(!immediate)func.apply(context,args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if(callNow)func.apply(context,args);
};
};
I cannot understand these issues and why it doesnt work.As a summary, I want to make a search engine which works with regex and mongodb. İt will be partial that is shown in that youtoube video which is on the above of my article that I referenced. But the real issue is, I couldnt understand the code block of function showResults and I dont know how to translate this codes to my project. So that I am waiting your help. I cannot upload a video to this website so that if you can give me your facebook, instagram or email account I can send the issue which should be solved. I need your help. I have been making this project for a long time for my school but I cannot move on. Please I need your help.
I hope I could express myself well and your helps will solve it.
Yes I got it know. I have made lots of changes instead of using this code blockes.
I wathced : https://www.youtube.com/watch?v=9_lKMTXVk64
And also I documented : Fuzzy Searching with Mongodb?
These two documentations help me a lot. So that my code is almost approximately 90% same as shown in these documentations.
This is my app.js :
app.get('/sonuc', function(req, res){
if (req.query.search) {
const regex = new RegExp(escapeRegex(req.query.search), 'gi');
Article.find({ "title": regex }, function(err, articles) {
if(err) {
console.log(err);
} else {
res.render("index", {
articles: articles
});
}
});
}
});
This is my index.pug file :
extends layout
block content
body
br
br
br
ul.list-group
each article, i in articles
li.list-group-item
a(href="/article/" + article._id)= article.title
And this is my layout.pug file(But I will consider the text form)
form.form-inline.my-2.my-lg-0(action="/sonuc" method="GET")
input.form-control.mr-sm-2(type='text', name,="search", onkeyup='showResults(this.value)', placeholder='Search',action='/article/'+sorgu, aria-label='Search')
button.btn.btn-secondary.my-2.my-sm-0(type='submit')
Please look at:
https://github.com/nax3t/fuzzy-search
Because in my solution I didnt add the message that is applied when we cannot find the word. Or when there is no such a word which is searched by user. The noMatch query.
But after I will apply it to my project I will add it to here.

"array.forEach is not a fuction" after firebase deploy but works on firebase serve

After deployment my array does not seem to be defined and I get a "forEach is not a function" error:
textPayload: "TypeError: currencies.forEach is not a function
at currenciesMenuConfiguration (/srv/menu/currencies-menu.js:22:16)
Here's the code for the currencies array:
async function currenciesMenuConfiguration() {
currencies = await getCol("currencies")
currencies.forEach(element => {
return currenciesList[element[Object.keys(element)].id] = element[Object.keys(element)].current
});
}
This gets called right after being defined with currenciesMenuConfiguration()
getCol is defined as:
// Get all documents in collection from Firestore
async function getCol(colName) {
return fs.collection(colName).get()
.then(res => {
return res.docs.map(doc => {
var rObj = {};
rObj[doc.id] = doc.data();
return rObj;
})
})
.catch(err => {
return `Error getting collection: ${err}`;
});
}
As mentioned on firebase serve locally this works without an issue. After deployment, I get this error. Am I missing something about asynchronous code in the cloud?
Also, any tips on how I would go about debugging this myself would be much appreciated. #BeginngersLife.
// I have checked the questions on so about firebase serve vs deployment but they mostly deal with issues around deployment or don't address the issue I am facing. One question that might help me get further in this is: firebase serve and debugging functions?.
See comment below question: I did indeed not return an array but an object. Closing. Thanks for the hint #Frank van Puffelen.

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.
}))

validating lack of parameters in feathresjs

I've read the feathersjs documentation, but after doing a find method in a service I realized that if I don't give any query parameters, the service returns all the data, which is something I don't want. How can I define a hook to validate that there are at least one query parameter in order to proceed; otherwise, send back a 403 error (bad request).?
I have doubts in the way to do it I tried this:
app.service('myService')
.before(function(hook) {
if (hook.params.query.name === undefined){
console.log('There is no name, throw an error!');
}
})
.find({
query: {
$sort: {
year: -1
}
}
})
And I tried in hook file on hooks this (that seemed really desperate & | stupid):
function noparams (hook) {
if (hook.params.query.name === undefined){
console.log('There is no name, throw an error!');
}
}
module.exports = {
before: {
find: [ noparams(this) ] ...
}
}
but it does not compile (I don't know what to send as a parameter there), and the examples seemed to be for pre 2.0 version and on top of that the code I found seemed to be in the app.js, but all is differently coded using feathers-cli, so the examples, even in the book, aren't against the scaffolded version, which is confusing because they shows the code in a different file were should be.
Thanks.
I ended using a before hook, so the code used is this:
const errors = require('feathers-errors');
module.exports = function () {
return function (hook) {
if(hook.method === 'find'){
if (hook.params.query.name === undefined || hook.params.query.length == 0){
throw new errors.BadRequest('Invalid Parameters');
}else{
return hook;
}
}
}
};
If have used feathers-cli to generate your application (feathers v2.x) you don't need to do anything else. If is an earlier version you maybe need to add the Express error handler and it is pointed out in the documentation|Errors|REST.
Thanks.

Resources