Error in NuxtJS: Cannot Convert Undefined or Null to Object - javascript

I am getting the following error (it won't even get to the console.log part of my code):
ERROR error in cloudinary module Cannot convert undefined or null to object 09:05:40
at Function.keys (<anonymous>)
at setSignature (modules\cloudinary\index.js:15:14)
Here is my code:
modules/cloudinary/index.js:
export default function () {
this.nuxt.hook('render:setupMiddleware', (app) => {
app.use('/api/cloudinary/signature', setSignature)
})
function setSignature(req, res) {
try {
const payload = []
Object.keys(req.body).forEach((key) => {
payload.push(`${key}=${req.body[key]}`)
})
console.log(payload)
} catch (error) {
console.error('error in cloudinary module', error)
}
}
}
Something going on with the Object here. Anyone spot anything?
Updated:
Doing the following console.log gives me undefined on the req.body:
export default function () {
// const config = this.options.privateRuntimeConfig.cloudinary
this.nuxt.hook('render:setupMiddleware', (app) => {
app.use('/api/cloudinary/signature', setSignature)
})
function setSignature(req, res) {
try {
console.log(req.body)

Related

Node JS Global Variables is not working after call

I'm trying to call my global variables in my controller but i got an error variable is not defined. Please see the code below for your reference. Hoping to solve my problem. Thank you Guys
**server.js **
const serverConfig = require('./config/server.config')
const app = require('fastify')({ logger: true })
require('./models/response.model')
const mongoose = require('mongoose')
const conn = require('./config/monggo.config')
require('./routes/dbm.routes')(app)
const connect = async () => {
try {
await mongoose.connect(conn.uri)
console.log('Connected to Mongoose!')
} catch (error) {
console.log(error)
}
}
connect();
app.listen(serverConfig.port, '::', (err, address) => {
if (err) {
app.log.error(err)
process.exit(1)
}
console.log('Listening at', address)
})
response.model.js
module.exports = function () {
global.successModel = {
status: 'sucess',
statusCode: 0,
isSuccess: true,
message: ''
}
global.failModel = {
status: 'failed',
statusCode: 1,
isSuccess: false,
message: 'Error encountered while processing request.'
}
}
**monggo.controller.js
**
exports.getProducts = async (req, res) => {
//find Products in the databse
Product.find({}, (err, product) => {
//send error message if not found
if (err) {
res.send(err);
}
//else pass the Products
res.send(successModel);
})
await res;
}
Hoping to solve my problem. Thank you
The './models/response.model' file exports a function that you need to call to "install" your globals.
- require('./models/response.model')
+ require('./models/response.model')()
As a suggestion, you should avoid to use globals, in fastify you can use:
decorator to add to your app instance useful data such as configs
Moreover, your mongoose connection is unrelated with Fastify, you can encapsulate it into a plugin to be sure that fastify is starting after connecting to the database:
const fp = require('fastify-plugin')
app.register(fp(async function connect (instance, opts) {
await mongoose.connect(conn.uri)
}))

In jest I can't access to my exported module

For example, I can't access to this module, why ?
let nodeCacheClient;
module.exports = {
initNodeCache: () => {
const NodeCache = require("node-cache");
nodeCacheClient = new NodeCache();
return nodeCacheClient;
},
insertToCacheWithTtl: (key, obj, ttl) => {
return nodeCacheClient.set(key, obj, ttl);
},
getCache: (key) => {
return nodeCacheClient.get(key);
},
deleteKey: (key) => {
return nodeCacheClient.del(key);
},
};
when I run this test I get this : TypeError: Cannot read property 'get' of undefined Error
test("login a user", async () => {
try {
const response = await axiosInstance.post("users/login", {
email: "test#gmail.com",
password: "144847120",
otpCode: getCacheClient.getCache("test#gmail.com")
});
console.log(response.data);
expect(response.data.status).toBe("success");
} catch (error) {
console.log(error + " Error");
expect(error);
}
});
It’s totally normal!
Actually you got access to your module, and the error is coming into your module where the “nodeCacheClient” is undefined since it was not defined!
Your error is coming from your “getCache()” function, in this syntax:
return nodeCacheClient.get(key);
Where in your test you didnt call for the “initNodeCache()” method which will do
nodeCacheClient = new NodeCache();
So, for your test scope, the nodeCacheClient is undefined, and that’s why
nodeCacheClient.get(key);
Will return the
typeError: Cannot read property 'get' of undefined Error

Mocking lambda-log options.meta using jest

In my util.ts I am importing and using lambda-log:
util.ts
import * as logger from 'lambda-log';
export async function prepareMessage(req){
try {
logger.options.meta.clientId = req.clientId;
if (!req.templateId) {
throw new Error(`template is missing`);
}
} catch(error){
logger.error('error occured', error);
}
}
I want to test in my util.test.ts that logger.error contains clientId I set in options.meta.clientId.
This is what I got so far, but it is not working:
util.test.ts
import * as logger from 'lambda-log';
jest.mock('lambda-log', () => ({
...jest.requireActual('lambda-log'),
error: jest.fn()
}));
it('sets clientId in logger.options.meta from request payload', async () => {
const record = { clientId: 'client-test' };
const optionsSpy = jest.spyOn(logger, 'error');
try {
await prepareMessage(record);
} catch (err) {
expect(optionsSpy).toHaveBeenCalled();
expect(optionsSpy).toHaveBeenCalledWith(
expect.objectContaining({
clientId: 'client-test'
})
);
}
}
Does anyone know how to spy lambda-log and how to accomplish this?

Can't get data via filter () in mongodb

I am trying to find the tasks assigned to the user through this
router.get('/all', auth, async (req, res) => {
try {
const assignments_raw = await Assignment.find({listP: listP.indexOf(req.user.userId)})
res.json(assignments_raw)
} catch (e) {
res.status(500).json({ message: 'Something went wrong, try again' })
}
})
Specifically, this line should have found all the tasks that have an element corresponding to the user ID inside the listP field
const assignments_raw = await Assignment.find({listP: listP.indexOf(req.user.userId)})
But this causes an error, why?
below is an excerpt from Mango
You can do like this
router.get('/all', auth, async (req, res) => {
try {
const assignments_raw = await Assignment.find()
let assignments = []
assignments_raw.map(assignment => {
if (assignment.listP.indexOf(req.user.userId) !== -1) {
assignments.push(assignment)
}
}
)
res.json(assignments)
} catch (e) {
res.status(500).json({ message: 'Something went wrong, try again' })
}
})

Receiving the error object in mocha afterEach

In my mocha testframework, I have an it-block that might throw an error. How do I obtain this error in the afterEach-hook that is called afterwards? Is there any workaround if it is not directly passed?
...
afterEach(async function () {
var testObject = {
title: this.currentTest.title,
state: this.currentTest.state,
duration: this.currentTest.duration,
timedOut: this.currentTest.timedOut,
error: this.currentTest.err // I want the error object here
}
});
it('my title', () => {
try {
doSomethingThatMightThrowError();
} catch (err) {
throw new Error(err)
}
});
....

Categories