why ID is not defined? - javascript

When i send DELETE request i got message error
ReferenceError: id is not defined
at Object.removeOne (...\services\user.js:16:38
I have no idea what id about in \services\user.js, and why it is not defined...
./generalRepository.js
function Repository() {}
Repository.prototype.findAndRemoveById = findAndRemoveById;
function findAndRemoveById(id, callback) {
var model = this.model;
var query = model.deleteOne({
_id: id
});
query.exec(callback);
}
module.exports = Repository;
.routers/user.js
const router = require("express").Router();
const userService = require("../../services/user");
router.delete("/:id", (req, res, next) => {
userService.removeOne(String(req.params.id), (err, data) => {
if (!err) {
res.send('success delete query');
} else {
console.log("wrong delete query");
res.status(400);
res.end();
}
});
});
module.exports = router;
.services/user.js
const UserRepository = require("../repositories/UserRepository");
module.exports = {
removeOne: () => {
UserRepository.findAndRemoveById(id, (err, data) => {
callback(err, data);
});
}
};

You need to update removeOne function to following by expecting arguments (id and callback) to be passed when it is being called.
const UserRepository = require("../repositories/UserRepository");
module.exports = {
removeOne: (id, callback) => {
UserRepository.findAndRemoveById(id, (err, data) => {
callback(err, data);
});
}
};

Maybe you should be like this:
module.exports = {
removeOne: (id) => {
UserRepository.findAndRemoveById(id, (err, data) => {
callback(err, data);
});
}
};

Related

How to make the program wait for the if statement to finish before continuing in javascript?

I'm new to Javascript. I want to make this block run after the if statement is finished (asynchronous). The reason I want that is that I want to make some changes to update them if it falls into the if statement
let params = {
TableName: "storepedia-test",
Item: updatedItem
};
docClient.put(params, function (err, data) {
if (err) {
console.log(err);
} else {
res.redirect('/devices');
}
});
Here is my whole code
const { id } = req.params;
const file = req.file;
let updatedItem = { ...req.body};
updatedItem.id = id;
if (file !== undefined){
const deleteParams = {
Key: updatedItem.image,
Bucket: bucketName
}
s3.deleteObject(deleteParams, async (err, data) => {
if (err) {
console.log(err)
} else {
const result = await uploadFile(file);
console.log('result', result);
await unlinkFile(file.path);
updatedItem.image = result.Key;
let params = {
TableName: "storepedia-test",
Item: updatedItem
};
docClient.put(params, function (err, data) {
if (err) {
console.log(err);
} else {
res.redirect('/devices');
}
});
}
})
}
let params = {
TableName: "storepedia-test",
Item: updatedItem
};
docClient.put(params, function (err, data) {
if (err) {
console.log(err);
} else {
res.redirect('/devices');
}
});
Just to run something after the if? I think this is the best spot:
docClient.put(params, function(err, data) {
if (err) {
console.log(err);
} else {
// run async code here.
// when done do the redirect.
// for example:
s3.do_something(function(err, data) {
if (err) {
console.log(err)
} else {
console.log(data)
res.redirect('/devices');
}
})
}
});

Why am I getting an error code 500 on patch request for Express backend?

My angular frontend is sending a patch request to my express backend and all routes are working except for my patch routes. The error is: Error: No default engine was specified and no extension was provided. Do I need to do something with the results parameter in the arrow functions of the updateQuote and updatePhrase functions in the backend service?
//quotes.service.ts (angular)
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { Quote } from '../models/quote.model';
import { Phrase } from '../models/phrase.model';
#Injectable({
providedIn: 'root'
})
export class QuotesService {
constructor(private http: HttpClient) { }
getQuotes(): Observable<any> {
return this.http.get('http://localhost:3000/quotes');
}
postQuote(quote: Array<Quote | Phrase>) {
return this.http.post('http://localhost:3000/quotes', quote).subscribe((data) => {
});
}
deleteQuote(quoteid: any) {
return this.http.delete(`http://localhost:3000/quotes/delete/${quoteid}`);
}
updateQuote(quoteid: any, payload: any) {
return this.http.patch(`http://localhost:3000/quotes/update/${quoteid}`, payload);
}
}
//quotes.controller.js (express)
var express = require('express');
var router = express.Router();
const db = require('../services/quotes.service')
router.get('/', db.getQuotes);
router.get('/phrases', db.getPhrases);
router.post('/', db.createQuote);
router.delete('/delete/:quoteid', db.deleteQuote);
router.patch('/update/:quoteid', db.updateQuote);
router.patch('/phrases/update/:phraseid', db.updatePhrase);
module.exports = router;
//quotes.service.js (express)
const Pool = require('pg').Pool
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'leaquotesapp',
password: 'password',
port: 5432,
});
const getQuotes = (request, response) => {
pool.query('SELECT * FROM quotes ORDER BY quoteid ASC', (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
});
}
const getPhrases = (request, response) => {
pool.query('SELECT * FROM phrases ORDER BY phraseid ASC', (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
});
}
const createQuote = (request, response) => {
let quote = request.body[0];
pool.query(`INSERT INTO quotes (title, context, speakers)
VALUES ('${quote.title}', '${quote.context}', '${quote.speakers}') RETURNING quoteid`, (error, results) => {
if(error) {
throw error;
}
//Insert phrases...
let quoteid = results.rows[0].quoteid;
for(let i = 1; i < request.body.length; i++) {
request.body[i].quoteid = quoteid;
createPhrase(request.body[i]);
}
response.status(201).send();
});
}
function createPhrase(phrase) {
pool.query(`INSERT INTO phrases (sequence, speaker, text, quoteid)
VALUES (${phrase.sequence}, '${phrase.speaker}', '${phrase.text}', ${phrase.quoteid})`, (error, results) => {
if(error) {
throw error;
}
});
}
const deleteQuote = (request, response) => {
let quoteid = request.params.quoteid;
pool.query(`DELETE FROM quotes WHERE quoteid = ${quoteid}`, (error, results) => {
if(error) {
throw error;
}
});
pool.query(`DELETE FROM phrases WHERE quoteid = ${quoteid}`, (error, results) => {
if(error) {
throw error;
}
});
response.status(200).json({'Delete': 'Success'});
}
const updateQuote = (request, response) => {
let quoteid = request.params.quoteid;
let column = request.body.keys[0];
let value = request.body.column;
pool.query(`UPDATE quotes SET ${column} = ${value} WHERE quoteid = ${quoteid}`, (error, results) => {
if(error) {
throw error;
}
});
response.status(200).json({'Update': 'Success'});
}
const updatePhrase = (request, response) => {
let phraseid = request.params.quoteid;
let column = request.body.keys[0];
let value = request.body.column;
pool.query(`UPDATE phrases SET ${column} = ${value} WHERE phraseid = ${phraseid}`, (error, results) => {
if(error) {
throw error;
}
});
response.status(200).json({'Update': 'Success'});
}
module.exports = {
getQuotes,
getPhrases,
createQuote,
deleteQuote,
updateQuote,
updatePhrase
}
Please provide your app.js file. Maybe you have not set the view engine or the view engine used is not configured well and that is what causing the error.
Your app.js file would reveal more.

SINON - an issue mocking a middleware

I have the following middleware in a Node.js REST API
const Authorized = (req, res, next) => {
if (!req.headers["authorization"]) {
res.status(401).send("Unauthorized");
} else {
jwt.verify(req.headers["authorization"], PRIVATE_KEY, (err, decoded) => {
if (err) {
res.status(403).send("Forbidden");
} else {
req.businessId = decoded.businessId;
req.roleId = decoded.roleId;
next();
}
});
}
};
As you can see I'm adding to variables to the request object
In the mockup of my tests I'm trying to do this:
sandbox = sinon.createSandbox();
sandbox.stub(Authorized, "Authorized")
.callsFake(async (req, res, next) => {
req.businessId = businessAux.id;
return next();
});
But this doesn't work and my actual function to be tested needs this variable:
listPermissionAndRolesByPk() {
this.app.get(`${config.API_PATH}/permissionrolebypk`, Authorized.Authorized, async (req, res) => {
const id = req.query.id;
const businessId = req.businessId;
if (!id) return res.status(400).send(messages[23].message.replace("${object}", "Permission Id"));
try {
const permission = await PermissionDAO.getPermissionAndRolesByPk(id, businessId ? businessId : 0);
if (permission) {
return res.status(200).json(permission);
} else {
return res.status(404).send(messages[8].message.replace("${object}", "Permission"));
}
} catch (error) {
return res.status(error.httpCode).send(error.message);
}
});
}
Any help will be appreciated.

findandupdate return null with promise all - mongoose

I am trying to create a nodejs API separated by controllers and routes. I am trying to findandupdate in multiple collections and then put them in multiple promises to return a single response but i get just a null what am i doing wrong below ?
controller.js
var x = (req, res, next, userID, product) => {
let query = {
uid: userID
}
let update = {
$push: {
product: product,
}
}
let options = {
safe: true,
new: true,
upsert: true
}
Model.findOneAndUpdate(query, update, options).exec()
.then(result => {
return true
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
})
};
module.exports = x;
Route.js
const controller = require('./user-product')
router.post('/api', function (req, res, next) {
var p1 = controller(req, res, next, userID, product)
var allDone = Promise.all([p1])
allDone
.then(function (e) {
res.send(e) //this is null
})
.catch(function (e) {
console.log(e);
})
});
You are not returning promise from the controller function. You are just returning the result and the error
So, Instead you should return the promise inside the controller function
Route.js
const controller = require('./user-product')
router.post('/api', function (req, res, next) {
var p1 = controller(req, res, next, userID, product)
var allDone = Promise.all([p1])
allDone.then(function (e) {
res.send(e)
})
.catch(function (e) {
console.log(e);
})
})
controller.js
var x = (req, res, next, userID, product) => {
let query = { uid: userID }
let update = { $push: { product: product }}
let options = {
safe: true,
new: true,
upsert: true
}
return Model.findOneAndUpdate(query, update, options).exec()
}
module.exports = x;
And probably easier with the async await syntax
Route.js
const controller = require('./user-product')
router.post('/api', async(req, res, next) => {
try {
const p1 = await controller(req, res, next, userID, product)
console.log(p1)
} catch (err) {
console.log(err)
}
})
controller.js
var x = async(req, res, next, userID, product) => {
let query = { uid: userID }
let update = { $push: { product: product }}
let options = {
safe: true,
new: true,
upsert: true
}
return Model.findOneAndUpdate(query, update, options).exec()
}
module.exports = x;

getModel() is not defined - but it was defined

I am creating file upload functionality on Cloud Storage. Here's the backend code:
const Storage = require('#google-cloud/storage')
const storage = Storage({
projectId: 'a-1485'
})
const bucket = storage.bucket('a-1485.appspot.com')
function getPublicUrl (filename) {
return 'https://storage.googleapis.com/a-1485.appspot.com/${filename}'
}
function sendUploadToGCS (req, res, next) {
if (!req.file) {
return next()
}
const gcsname = Date.now() + req.file.originalname
console.log(gcsname)
const file = bucket.file(gcsname)
const stream = file.createWriteStream({
metadata: {
contentType: req.file.mimetype
}
})
stream.on('error', (err) => {
req.file.cloudStorageError = err
next(err)
})
stream.on('finish', () => {
req.file.cloudStorageObject = gcsname
req.file.cloudStoragePublicUrl = getPublicUrl(gcsname)
next()
})
stream.end(req.file.buffer);
}
module.exports = {
getPublicUrl,
sendUploadToGCS
}
In my app.js file:
app.post('/upload-image', multer.single('image'), images.sendUploadToGCS, (req, res, next) => {
let data = req.body
console.log(data)
if (req.file && req.file.cloudStoragePublicUrl) {
data.imageUrl = req.file.cloudStoragePublicUrl
}
getModel().create(data, (err, savedData) => {
if (err) {
next(err)
return
}
res.redirect(`${req.baseUrl}/${savedData.id}`);
})
}
)
However, when I upload an image I get an error thrown saying 'getModel()' is not defined. But as you can see above it is defined. What is the problem?

Categories

Resources