Variable inside a class is not defined NodeJS - node.js

I am develping an application to send emails with nodeJs 6.9 and express 4.
I am also using a library called powerdrill wich is the library that calls Mandrill APIs.
I am trying to use the message variable which is the varible that use the powerdrill library to create the object and send the email. I am using this variable inside a method but is throwing an error.
'use strict';
var config = require('config'),
queries = require('api/queries'),
Message = require('powerdrill').Message;
class MandrillService{
constructor(config, Message) {
this.config = config;
this.Message = Message;
}
welcome(){
//console.log(req.body);
message = new Message();
message.apiKey(config.mandrillKey)
.subject('Welcom')
.template('welcome-email')
.from(config.mandrilEmail)
.to('david#gmail.com')
.tag('complex')
.globalMergeVar('VERIFY_EMAIL','link')
.send(function(err, resp) {
});
}
}
module.exports = new MandrillService(config);
error:
Unhandled rejection ReferenceError: message is not defined
at MandrillService.welcome (/home/user/platform/services/mandrillService.js:28:17)
at /home/user/platform/services/notificationService.js:222:22
at Promise._execute (/home/user//platform/node_modules/bluebird/js/release/debuggability.js:303:9)
at Promise._resolveFromExecutor (/home/user/platform/node_modules/bluebird/js/release/promise.js:483:18)
I donĀ“t know what is the behavior inside a class but if I try to call the method using express inside a post method, and using it like follows the code works fine.
var express = require('express'),
router = express.Router(),
config = require('config'),
Message = require('powerdrill').Message;
router.post('/welcome',function(req,res,next){
message = new Message();
message.apiKey(config.mandrillKey)
.subject(req.body.subject)
.template(req.body.template)
.from(config.mandrilEmail)
.to(req.body.to)
.tag('complex')
.globalMergeVar('VERIFY_EMAIL',req.body.linkVefifyEmail)
.send(function(err, resp)
res.send(resp).end();
});
});

Related

Node.js Route to Controller not applying Controller constructor

I have an express.js application that uses the express.Router() to connect my endpoints to controllers.
My goal is to have an object newed up in the controller constructor so I can use it in all controller functions without having to new it up in each one.
The constructor runs correct, and the object is available within the constructor. But whenever I call any actions of the controller, the object is null.
Here is the router
const express = require('express');
const componentController = require('../controllers/component');
const router = express.Router();
// component routes
router.get('/components', componentController.getComponents);
module.exports = router;
And here is my controller.
const LogService = require('../services/logService');
class ComponentController {
constructor() {
this.logger = new LogService('ComponentController');
this.logger.logDebug('test1','test1');
}
async getComponents(req, res) {
const test = new LogService('ComponentController');
test.logDebug('test2','test2');
this.logger.logDebug('test3','test3')
res.json('');
}
}
module.exports = new ComponentController();
I want the LogService to be available in the controller actions. The first two logs work correctly, test1 and test2. But test3 throws an error saying logger is undefined.
Why is this.logger undefined in later functions? How can I fix this issue?
try to refactor getComponents to an arrow function.
Here is why: https://javascript.plainenglish.io/this-binding-in-es6-arrow-function-70d80e216238
You can also do this:
router.get('/components', componentController.getComponents.bind(componentController));

Shopify API Node/Express Cannot read properties of undefined (reading 'Rest')

Just starting off with Shopify, and trying to get an order. Following the Shopify API documentation, here is my code:
const Shopify = require('#shopify/shopify-api');
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
module.exports.getShopifyOrderById = async (orderId) => {
return await client.get({
path: `orders/${orderId}`,
});
}
I get the following error when I execute this code:
TypeError: Cannot read properties of undefined (reading 'Rest')
Can't seem to figure out what the issue is.
You need to use Object destructing to get the Shopify object or use default export like below.
const { Shopify } = require('#shopify/shopify-api');
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
OR
const Shopify = require('#shopify/shopify-api').default;
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
OR
const ShopifyLib = require('#shopify/shopify-api');
const client = new ShopifyLib.Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
This has to do with how ES6 modules are emulated in CommonJS and how you import the module. You can read about that here.

How to use module in my own node js module?

How I can use third party module in my own? For example if I have in app main file something like (using body-parser):
app.post("/dothis", (req,res)=>{
var name = req.body.name;
console.log(name);
};
This work fine. But when I want to have this in separate file (for example mod.js), and wrote like this:
exports.own = function(){
var name = req.body.name;
console.log(name);
}
Then in main file wrote:
const mod = require(__dirname + "/mod.js")
app.post("/dothis", (req,res)=>{
mod.own();
};
Then I get error like, req is undefined.
I am trying to add in mod.js file
const {req} = require ("http");
So then I got error that can't read value of name undefined.
There is the question, how i can transfer my code which is using body-parser, express and other modules to separate file or creating own module to get working module?
Thanks!
You are getting undefined because you are not passing the request.
Looking at your code, try this.
exports.own = function(req){ // use request
var name = req.body.name;
console.log(name);
}
const mod = require(__dirname + "/mod.js")
app.post("/dothis", (req,res)=>{
mod.own(req); // pass request
};

Testing Node Application with mocha

I have the following test application based on a template provided by openshift.
server.js:
var express = require('express');
exports.NodeTestApp = function () {
self.cache_get = function (key) {
return 'Would be a value here';
};
}
server_test.js:
var server = require('../server');
describe('Server', function(){
describe('Startup',function(){
it('sets up routes during startup',function(){
var app = server.NodeTestApp();
app.cache_get('/');
expect(app.routes.size).to.equals(5);
})
})
})
When I run this test I get an error message that cache_get is not defined.
TypeError: Cannot read property 'cache_get' of undefined
at Context.<anonymous> (test/server_test.js:7:16)
I would have thought that everything that is specified in the NodeTestApp function is available via variable app. IntelliJ even shows me the function as a valid call. Any idea why I get this error ?
Thanks in advance.
Oliver
I figured out the problem with above code. To instantiate the app variable the new keyword has to be used. I didn't think that this is required as I would have thought its purely a function call and not a constructor call, which requires the new keyword. Below is the working code for your reference.
var app = new server.NodeTestApp();

KOA POST parsing error

I'm trying to get the POST data using koa-body-parser but I get the following error :
SyntaxError: Unexpected token e
at Object.parse (native)
This error refer to
/co-body/node_modules/raw-body/index.js
I think that the library co-body is trying to use "parse" but in my node version this function is restricted.
I'm using node 0.11.13
This is a part of the app.js
var path=require('path');
var koa = require('koa');
var app = koa();
app.use(require('koa-body-parser')());
//enrutamiento
app.use(require('./configs/routes')(app));
This is the function that recibe the call:
function *(){
/*
var str = 'email=lopezchr%40gmail.com&password=123123';
console.log(JSON.parse(str));
*/
var self = this;
var attributes= this.request.body
var userModel = this.models.user;
userModel.create(this.request.body).exec(function(){
self.body={success:true,description:"user Created"}
});
}
Aditionally, when I try to do this:
var str = 'email=lopezchr%40gmail.com&password=123123';
console.log(JSON.parse(str));
I optain the same error..
update
In other post, I realized that string is not a JSON.. sooo... that is the problem...
I'm trying to do this:
$.post('/auth',$(form).serialize(),function(data){
console.log(data);
});
And I want to recibe the form data with koa-body-parce...What should I do?
For some reazon, the jquery function $.post was sending the message with type json.. so that caused the error.. now the message type is plain/text and works.. thanks

Resources