Getting 'method not exist' error for PeristedModel.findOrCreate() - loopbackjs

I am trying to use the method Model.findOrCreate in loopback using the mongodb connector
Country.findOrCreate({where: {iso2a: iso2a}}, {
"iso2a": iso2a,
"polygon": polygon
}, function(err, obj){
if(err){
console.log("Error finding and/or creating:", err);
}else{
obj.iso2a = iso2a;
obj.polygon = polygon;
obj.save(function(err, obj){
if(err){
console.log("Error saving");
}else{
console.log("Success saving");
}
});
}
});
But I keep getting the error that the function does not exists...
I guess I am doing something pretty basic wrong, ohh yeah and I checked that the model is "loaded".
Thanks.

I've read the docs here for PersistedModel.findOrCreate(where, data, callback). Now you see the first argument only accepts where clause, so you don't have to specify it explicitly. Here's the corrected code:
Country.findOrCreate(
{ iso2a: iso2a }, //adding where clause is not required.
{
"iso2a": iso2a,
"polygon": polygon
},
function(err, obj) {
if(err) {
console.log("Error finding and/or creating:", err);
} else {
obj.iso2a = iso2a;
obj.polygon = polygon;
obj.save(function(err, obj) {
if(err) {
console.log("Error saving");
} else {
console.log("Success saving");
}
});
}
});
Hope it solves your problem.

Related

Setting quality in JIMP always gives the same result

When I set the quality for a PNG or JPEG in JIM (number from 1 - 99) I always get the same result. I don't see any difference in between quality or the final size. Here is my code:
function lossy(buffer, quality){
return new Promise(function(resolve, reject){
Jimp.read(buffer, function(err, image) {
let extension = image.getExtension();
if(image){
image.quality(quality)
.getBase64(extension, (err, data) => {
if(data){
resolve(data)
}
if(err){
console.log(err)
}
})
}
if(err){
reject(err)
}
});
})
}
Thank you for the advice!

TypeError: AWS.PinpointSMSVoice is not a constructor

I am using "aws-sdk": "^2.302.0" in my node api.
Please find my code below
var pinpointsmsvoice = new AWS.PinpointSMSVoice({apiVersion: '2018-09-05'});
var params = {
Content: {
SSMLMessage: {
LanguageCode: "en-US",
Text: <MY_Template>,
VoiceId: "Matthew"
}
},
DestinationPhoneNumber: <destinationNumber>,
OriginationPhoneNumber: <OriginationPhoneNumber>
};
//Try to send the message.
pinpointsmsvoice.sendVoiceMessage(params, function (err, data) {
if (err) {
log.error(err);
} else {
log.info("Voice Message is sent successfully");
}
});
Earlier it was working now I am getting an error as TypeError: AWS.PinpointSMSVoice is not a constructor
Can some help me anything missed?
It's working with the latest aws-sdk version.

How to set middleware in loopback js?

I need to set data in session just after authentication/login so i have set middleware like this.
middleware.json
{
"initial": { },
"session": {
"express-session": {
"params": {
"secret": "mysceret",
"saveUninitialized": true,
"resave": true
}
}
},
"auth:before": {},
"auth": {
"loopback#token": {}
},
"auth:after": {
"./middleware/store-current-user": {}
},
"parse": { }
}
in my store-current-user.js :
module.exports = function (options) {
console.log(" it is working here");
return function storeCurrentUser(req, res, next) {
console.log(" it is not working here");
if (!req.accessToken) {
return next();
}
app.models.User.findById(req.accessToken.userId, function (err, user) {
if (err) {
return next(err);
}
if (!user) {
return next(new Error('No user with this access token was found.'));
}else{
console.log(' ok '); // it is not working.
req.session.user = user;
next();
}
});
};
};
Express-session : "express-session": "^1.15.6".
Loopback version : "loopback": "^3.0.0"
Where I am missing ? I am unable to it figure out.
Please some help.
Try something like this?
module.exports = function () {
console.log(" it is working here");
return function storeCurrentUser(req, res, next) {
console.log(" it is not working here");
if (!req.accessToken) {
next();
}
app.models.User.findById(req.accessToken.userId, function (err, user) {
if (err) {
next(err);
}
if (!user) {
next(new Error('No user with this access token was found.'));
}else{
console.log(' ok '); // it is not working.
req.session.user = user;
next();
}
});
};
};
remove the options (add it back later if you need it)
don't call return next(), just next() alone
also, are you defining app somewhere?

How to use graph API with react-native-fbsdk?

I read the document, both on github and Facebook developers docs.
There is only sample, nothing more. No API document.
The code to make a Graph API request is
const infoRequest = new GraphRequest(
'/me',
null,
this._responseInfoCallback,
);
And the callback
_responseInfoCallback(error: ?Object, result: ?Object) {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
alert('Success fetching data: ' + result.toString());
}
}
And here is the function to make a Graph API request
testRequestGraphAPI(){
const infoRequest = new GraphRequest(
'/me',
null,
this._responseInfoCallback,
);
new GraphRequestManager().addRequest(infoRequest).start();
}
However, I can't find any further document. I have no idea what each parameters do.
The result for these codes above is this.
I also don't know how to get the result.
However, when I try to modify '\me' to 'me?fields=id,name', It failed.
Although I have asked for permission
<LoginButton
publishPermissions={["publish_actions,user_birthday, user_religion_politics, user_relationships, user_relationship_details, user_hometown, user_location, user_likes, user_education_history, user_work_history, user_website, user_managed_groups, user_events, user_photos, user_videos, user_friends, user_about_me, user_status, user_games_activity, user_tagged_places, user_posts, user_actions.video, user_actions.news, user_actions.books, user_actions.music, user_actions.fitness, public_profile, basic_info"]}
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
meow_accesstoken = data.accessToken
alert(meow_accesstoken.toString())
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
But it does not print out what error, just object Object.
So, the problem is that I don't understand the sample code which Facebook provide with no explanation.
Here is my question that I really need you help me:
First at all, please check the javascript code that I currently looking at?
How to use graph API in react-native-fbsdk to retrieve some user information (example: full name) and successfully display it (use alert) ?
What each parameters in GraphRequest() do ?
What is the structure of error object and result object in _responseInfoCallback ?
SOLUTION
Thanks to #Samuel answer, I have updated my code
testRequestGraphAPI: function(){
const infoRequest = new GraphRequest(
'/me',
{
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name' // what you want to get
},
access_token: {
string: meow_accesstoken.toString() // put your accessToken here
}
}
},
this._responseInfoCallback // make sure you define _responseInfoCallback in same class
);
new GraphRequestManager().addRequest(infoRequest).start();
}
And the callback
_responseInfoCallback: function(error: ?Object, result: ?Object) {
alert("meow response");
if (error) {
alert('Error fetching data: ' + error.toString());
console.log(Object.keys(error));// print all enumerable
console.log(error.errorMessage); // print error message
// error.toString() will not work correctly in this case
// so let use JSON.stringify()
meow_json = JSON.stringify(error); // error object => json
console.log(meow_json); // print JSON
} else {
alert('Success fetching data: ' + result.toString());
console.log(Object.keys(result));
meow_json = JSON.stringify(result); // result => JSON
console.log(meow_json); // print JSON
}
}
*Note: For console.log(), you need to use "Debug JS remotely" then open Chrome developer tools to see the log.
Unfortunately the react-native-fbsdk documentation is not updated and the examples do not work well.
I got the same problem and I solved it by try and error.
To solve your problem you'll need to change your GraphRequest adding params and fields to it like this:
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
You'll need to enable the Remote JS Debug to see the console.log() info.
https://facebook.github.io/react-native/docs/debugging.html
And probably you need to get some permissions to get more info than names and email so it's a good idea to look the Facebook Graph API Documentation: https://developers.facebook.com/docs/graph-api/overview/
Reference:
https://github.com/facebook/react-native-fbsdk/issues/105#issuecomment-206501550
Here is an example of a custom button if you want to make one :)
FbLoginButton() {
LoginManager
.logInWithReadPermissions(['public_profile'])
.then(function (result) {
if (result.isCancelled) {
alert('Login cancelled');
} else {
AccessToken
.getCurrentAccessToken()
.then((data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest('/me', {
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
}, responseInfoCallback);
// Start the graph request.
new GraphRequestManager()
.addRequest(infoRequest)
.start()
})
}
}, function (error) {
alert('Login fail with error: ' + error);
});
}
Thank you #Samuel.
I finally succeed to get user information from Facebook login because of your help!
But I struggled to figure out how can I get username and email literally from the result object cause I am a newbie in React & Javascript.
P.S. result["name"] is the point because it is object!!
So I added some code to yours for other people like me.
If you don't like using your code, just tell me that.
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
// Here's my code
alert('Success fetching data: ' + result["name"].toString() +
", " + result["email"].toString());
/*
if(your DB already got this email or something unique) {
// SignIn()
}
// when your DB doesn't have this email
else {
// Do signUp() with this infomation and SignIn()
}
*/
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
My code was not retriving the user email, if you are having the same problem, just put 'email' in parameter's logInWithPermission
Not Working
LoginManager.logInWithPermissions(['public_profile']).then(...)
Working
LoginManager.logInWithPermissions(['public_profile', 'email']).then(...)
All Function
loginWithFacebook = () => {
LoginManager.logInWithPermissions(['public_profile', 'email']).then(
login => {
if (login.isCancelled) {
console.log('Login Cancelado');
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
const accessToken = data.accessToken.toString()
this.getInfoFromToken(accessToken)
})
}
},
error => {
console.log('Erro no login ', console.error(error)
)
}
)
}
getInfoFromToken = token => {
const PROFILE_REQUEST_PARAMS = {
fields: {
string: 'id, name, first_name, last_name, birthday, email'
},
}
const profileRequest = new GraphRequest('/me', { token, parameters: PROFILE_REQUEST_PARAMS },
(error, result) => {
if (error) {
console.log('Login Info has an error:', error)
} else {
console.log(result)
}
},
)
new GraphRequestManager().addRequest(profileRequest).start()
}
try this
import { GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
export const GetInfoUSer = () => {
return new Promise((resolve, reject) => {
const infoRequest = new GraphRequest('/me', null, ((error, result) => {
if (error) {
reject(error)
} else {
resolve(result)
}
}))
new GraphRequestManager().addRequest(infoRequest).start();
})
}
and then
onLoginConFacebook = () => {
LoginManager.logInWithReadPermissions(['public_profile']).then(result => {
if (result.isCancelled) {
console.log(':(')
} else {
AccessToken.getCurrentAccessToken().then((data) => {
let myAccessToken = data.accessToken.toString();
GetInfoUSer().then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
}
).catch(error => {
console.log(':(')
})
}
})
}

search a string in another file and replace it with another string in node js

I have searched enough for this matter and found most of the answers for java same problem but for me the problem arise in a node js program.
I want to search for,
.made-easy-theme{
color:black;
}
in a css file and replace its 'black' with another color which I recieve from the client side of the program. Here is what I have tried, I have tried 3 ways, but none of them are working.
First concept I have tried is,
var main = 'temp/' + userId + '/templates/' + appId + '/css/main.css';
var color = req.body.color;
function replaceThemecolor(color) {
fs.readFile(main, 'utf-8',
function (err, data) {
if (err) {
return console.log(err)
}
else {
var str = '.made-easy-theme{color:black;}';
if (str.search("black") != -1) {
var result = data.replace(/black/g, themecolor.color);
fs.writeFile(mainCss, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
}
console.log(result);
}
});
}
});
The second concept I have tried is,
fs.readFile(main, 'utf-8',
function (err, data) {
if (err) {
return console.log(err)
}
else {
var ex = '.made-easy-theme{color:black;}'.includes('black');
if (ex == true) {
var result = data.replace(/black/g, color);
fs.writeFile(main, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
console.log(result);
}
}
The third concept I have tried is,
else if (data.indexOf('.made-easy-theme{color:black;}') > 0) {
console.log(data);
var result = data.replace('black', themecolor.color);
fs.writeFile(mainCss, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
};
Noone of these are working for me, please help to resolve this problem
I have found the answer
function replaceThemecolor(color) {
fs.readFile(main, 'utf-8',
function (err, data) {
var searchStr = ".made-easy-theme{color:black}";
var result = searchStr.replace(new RegExp('black', ''), color);
fs.writeFile(main, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
});
}
but the problem is that it clears the full content of the css file and replace only the
.made-easy-theme{
color:black;
}
the other content which was in the css file is erased. I want to keep them and replce what I want to replace
Here is a way to do it, although not the best way. This code is coupled, makes bad use of string concatenation, doesn't do enough error checking and should probably use a file stream. But it will give you an idea.
Plus, it's just a dangerous thing to do.
var fs = require('fs');
var infile = 'test.css';
var outfile = 'temp.css';
var flag = false;
var color = 'green';
var out = '';
fs.open(infile, 'r', function(err, fd){
changeLine(fd);
});
function changeLine(fd){
var buf = new Buffer(1024);
buf.fill(0);
fs.read(fd, buf, 0, 1024, null, function(err, bytesRead, buffer){
if(bytesRead === 0){
writeCSS(out);
return;
}
var str = buffer.toString('utf8', 0, bytesRead);
if(/made-easy-theme/.exec(str)){
flag = true;
}
if (/color:/.exec(str) && flag){
str = str.replace('black', color);
flag = false;
}
out += str;
changeLine(fd);
});
}
function writeCSS(str){
fs.writeFile(outfile, str, function(err, written, buffer){
fs.rename(outfile, infile);
});
}