I have created a method that grabs the image data based on another method. As you can see the uploadAvatar()
method stores the object back from Cloudinary into a constructor object this._userImage;
. Then my getUserImage()
method should return the user image data but instead it returns {}
that when I log it to the console :P.
ImageUploader.js
'use strict';
const cloudinary = require('cloudinary');
class ImageUploader {
constructor(imageObj) {
this.imageObj = imageObj;
this._apiKey = "key";
this._apiSecret = "secret";
this.config = cloudinary.config({
cloud_name: 'name',
api_key: this._apiKey,
api_secret: this._apiSecret
});
this._userImage = {}; // where user image object should be stored
}
* uploadAvatar(path) {
cloudinary.uploader.upload(path, (data) => {
this._userImage = data; // where I overwrite the constructor obj
});
}
getUserImage() {
return this._userImage; // this returns `{}` when I log it in UsersController.js
}
}
module.exports = ImageUploader;
UsersController.js
'use strict'
const Validator = require("../Helpers/ValidatorHelper.js");
const ImageUploader = require("../Helpers/ImageUploader.js");
class UsersController {
* registerView (request, response) {
yield response.sendView('users.register');
}
* register (request, response) {
const user = request.only('display_name', 'username', 'email', 'password', 'confirm_password', 'console');
var avatar = request.file('avatar');
let validator = new Validator(user, avatar);
let imageUpload = new ImageUploader(avatar);
let avatarStatus = yield validator.validateAvatar();
var img;
if (avatarStatus) { // is true
yield imageUpload.uploadAvatar(avatar.file.path);
} else { // is false
// pick a random avatar
}
console.log(imageUpload.getUserImage());
return response.status(200).json({
user: user,
avatar: imageUpload.getUserImage()
});
}
}
module.exports = UsersController