Update in MySql DB - mysql

I have to save the user permissions when the admin, in the user management page, choose what every user can (or can't) see.
After doing the cshtml page to show all the available pages, I have to save the changes through a typescript page:
Core.compatibility.ready(() => {
let editGestioneUtenti = document.getElementById("edit-gestioneRuoli");
if (editGestioneUtenti)
editGestioneUtenti.addEventListener("click", async ev => {
let id = Route.get("gestioneRuoli");
await edit(gestioneutenti, "/api/GestionePermessi/gestioneruoli/{Id}", id);
});
let salvaPermessi = document.getElementById("btn-save-permessi");
if (salvaPermessi)
salvaPermessi.addEventListener("click", async ev => {
ev.preventDefault();
let menu = [];
let tab = [];
let func = [];
const data = {
_id: val,
_menu: idmenu,
_tab: idtab,
_func: idfunc
};
var val = $("#Username").val();
$(".combomenu").each(function () {
menu.push($(this).val());
})
var idmenu = $("#menu").val();
$(".combomenu").each(function () {
menu.push($(this).val());
})
var idtab = $("#tab").val();
$(".combotab").each(function () {
tab.push($(this).val());
})
var idfunc = $("#func").val();
$(".combofunc").each(function () {
func.push($(this).val());
})
})
try {
await Core.compatibility.fetch("/api/gestionepermessi/gestioneruoli/", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}).then(response => {
if (!response.ok) {
throw new Error(response.statusText)
} else {
$(".combomenu").each(function () {
jQuery.each(_menu, function (i, val) {
$("#" + val).remove();
})
})
}
}).then(response => {
$(".combotab").each(function () {
jQuery.each(_tab, function (i, val) {
$("#" + val).remove();
})
})
}).then(resp => {
$(".combofunc").each(function () {
jQuery.each(_func, function (i, val) {
$("#" + val).remove();
})
});
})
} catch (e) {
SwalWrapper.fire({
type: "error",
title: "Errore",
text: e
});
};
});
This part of code contains some errors, indeed the compiler show me this messages:
cannot find name 'data'
cannot find name '_menu'
cannot find name '_tab'
cannot find name '_func'
but I've declared at line 18 of the code I've posted. How can I fix it?

Related

Nodejs: Can't post a string filed and image on the same request with Express and Mysql

I am using mutler to upload image with post request and also string data.
When I upload only the image with Postman or React, it is working, but when I send also the strings, it shows this:
undefined
TypeError: Cannot read properties of undefined (reading 'filename')
The string got saved to MySQL but not the image.
That's my code for the Multer:
let storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/images/')
},
filename: (req, file, callBack) => {
const mimeExtension = {
'image/jpeg': '.jpeg',
'image/jpg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
}
callBack(null, file.originalname)
}
})
let upload = multer({
storage: storage,
fileFilter: (req, file, callBack) => {
// console.log(file.mimetype)
if (file.mimetype === 'image/jpeg' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/png' ||
file.mimetype === 'image/gif') {
callBack(null, true);
} else {
callBack(null, false);
req.fileError = 'File format is not valid';
}
}
});
And that's my post request:
router.post('/', upload.single('image'), async (req, res) => {
try {
if (!req.file) {
console.log("You didnt upload a picture for your project");
}
const { title, about_the_project, project_link, user_id } = req.body
const projectnum = await SQL(`INSERT into project(title,about_the_project,project_link,user_id)
VALUES('${title}','${about_the_project}','${project_link}',${user_id}) `)
console.log(projectnum.insertId);
console.log(req.file && req.file.filename)
let imagesrc = 'http://127.0.0.1:5000/images/' + req.file && req.file.filename
await SQL(`UPDATE project SET image = '${imagesrc}' WHERE projectid = ${projectnum.insertId}`)
res.send({ msg: "You add a new project" })
} catch (err) {
console.log(err);
return res.sendStatus(500)
}
})
On React that's the code:
const PostNewProject = async () => {
let formData = new FormData()
formData.append('image', imgsrc)
const res = await fetch(`http://localhost:5000/project`, {
headers: { 'content-type': 'application/json' },
method: "post",
body: JSON.stringify({ title, about_the_project, project_link, languages, user_id }),formData,
// credentials: "include"
})
const data = await res.json()
if (data.err) {
document.getElementById("err").innerHTML = data.err
} else {
console.log(data);
document.getElementById("err").innerHTML = data.msg
}
}
And the input for the image upload
<Input
type='file'
name='image'
sx={{ width: '25ch' }}
onChange={(e) => setImgsrc(e.target.files[0])}
/>
Thank you for your help!
You did not write a comma after the filename and before the callback function in the Multer.
I think you should check you exports too.

Unable to show blob url in "pdf-viewer" => "ng2-pdf-viewer" in Angular 10

I have an API which is returning uploaded file as blob. When I try to bind src with blob URL then it does not show anything, however, when I try to bind direct URL then it can show PDF file. Here is my code given below.
My TS code
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
},
(err: Error) => {
},
() => {
const blob: Blob = new Blob([this.tempBlob], { type: this.contentType });
const fileName: string ='ilvsna.pdf';
this.myBlobURL = URL.createObjectURL(blob);
}
);
}
HTML
<pdf-viewer [src]="myBlobURL"
[render-text]="true"
[original-size]="false"
style="width: 400px; height: 500px"
></pdf-viewer>
Note: if I set myBlobURL URL to 'https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf' then it can display
I think I have a solution for you. You can use ArrayBuffer. #N.F. Code is correct, however, you said that you got error in the line => this.pdfSrc = new Uint8Array(fileReader.result);
So, change the line into => this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);.Finally, your ts code should look like below=>
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
const fileReader = new FileReader();
fileReader.onload = () => {
this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);
};
fileReader.readAsArrayBuffer(this.tempBlob);
},
(err: Error) => {
}
);
}
Try this.
ts
pdfSrc: Uint8Array;
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
const fileReader = new FileReader();
fileReader.onload = () => {
this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);
};
fileReader.readAsArrayBuffer(this.tempBlob);
},
(err: Error) => {
}
);
}
html
<pdf-viewer [src]="pdfSrc"
[render-text]="true"
[original-size]="false"
style="width: 400px; height: 500px"
></pdf-viewer>
I resolve with window.URL.createObjectURL of my return blob file from service:
-- ts file
this.obuService.getObuDocument(obuId, fileId).subscribe(
(data: HttpResponse<Blob>) => {
const url = window.URL.createObjectURL(data.body);
this.src = url;
this.viewPDF = true;
}
);
-- service
getObuDocument(obuId: number, fileId: number): Observable<any> {
const options = {
observe: 'response' as 'body',
Accept: 'application/pdf',
responseType: 'blob' as 'blob'
};
return this.http.get(this.apiUrl + '/' + obuId + '/upload/' + fileId, options)
.pipe(catchError(err => { throw err; }));
}

What's the best way to mock a nested function?

consider a function
exports.projectNotifyLaunch = (admin, functions) => {
return functions.database.ref("/projects/{pid}").onCreate(snap => {
const { title } = snap.val();
const notification = {
title: `${title} just launched!`,
body: `We just heard about a new cryptocurrency project called ${title}`
};
return admin.messaging().sendToTopic("premium", { notification });
});
};
How should I mock deeply nested functions such as
functions.database.ref("/projects/{pid}").onCreate(snap => {});
or
admin.messaging().sendToTopic("premium", { notification });
in Jest? I want to fire off the snap=>{} callback and assert against the value of notification.
I was able to make this work
This works but it's quite verbose. I'm wondering if there is a better way, or a type of testing I'm not aware of with Jest.
describe("send notification to premium users on new project", () => {
// INPUTS
const snap = {
val: () => ({
title: "Test Title"
})
};
const functions = {
database: {
ref: () => ({
onCreate: callback => callback(snap)
})
}
};
// outputs
let topicStub = null;
let notificationStub = null;
const admin = {
messaging: () => ({
sendToTopic: (topic, notification) => {
topicStub = topic;
notificationStub = notification;
}
})
};
projectNotifyLaunch(admin, functions);
test("title is correct", () => {
expect(notificationStub.notification.title).toBe(
"Test Title just launched!"
);
});
test("topic is premium", () => {
expect(topicStub).toBe("premium");
});
});

mysql node: can't set headers after they are sent

I am trying to get a list of movies in a directory, parse titles, get movie information on TMDB than check if movie info is stored in mysql database and if not stored, insert info into the database.
I am using NodeJS/Express and mysql.
Here is my code so far:
exports.checkForMovies = function (req, res, next) {
const testFolder = './test/';
var movieList = [];
var movieResultsPromise = [];
var movieResults = [];
fs.readdirSync(testFolder).forEach(file => {
movieList.push(tnp(file));
});
movieList.forEach(movie => {
var waitPromise = searchTMDB(movie.title);
movieResultsPromise.push(waitPromise);
});
Promise.all(movieResultsPromise).then(result => {
movieResults = result;
movieResults.forEach(movie => {
checkMoviesInDB(movie.id, (err, data) => {
if (err) {
console.log(err)
}
if (data && data.update === true) {
var movieObj = {
m_tmdb_id: movie.id
};
insertMoviesToDB(movieObj, (resp, err) => {
if (err) {
console.log(err);
} else {
return res.json(resp);
}
});
} else {
return res.json(data);
}
});
});
});
}
function checkMoviesInDB(id, cb) {
var sql = "SELECT * FROM ?? WHERE m_tmdb_id = ?"
var table = ['movie', id];
sql = mysql.format(sql, table);
connection.query(sql, function (err, rows) {
if (err) {
return cb(err);
}
if (rows.length > 0) {
return cb(null, {
success: true,
update: false,
message: 'Movies up to date!'
})
} else {
return cb(null, {
update: true,
message: 'Updating database!'
})
}
});
}
function insertMoviesToDB(movie, cb) {
var sql = "INSERT INTO ?? SET ?";
var table = ['movie', movie];
sql = mysql.format(sql, table);
connection.query(sql, function (err, rows) {
if (err) {
return cb(err);
} else {
return cb(null, {
success: true,
message: 'Movie database updated!'
})
}
});
}
function searchTMDB(title) {
return new Promise((resolve, reject) => {
https.get(config.tmdbURL + title, response => {
var body = "";
response.setEncoding("utf8");
response.on("data", data => {
body += data;
});
response.on("end", () => {
body = JSON.parse(body);
resolve(body.results[0]);
});
response.on("error", (err) => {
reject(err);
});
});
});
}
After code execution it inserts movie info in the database or responses with "Movies up to date" but I am getting this error and NodeJS crashes:
Error: Can't set headers after they are sent.
Any help is appreciated, thanks!
EDIT!
This is the new code and I am still getting the same error...
exports.checkForMovies = function (req, res) {
const testFolder = './test/';
var movieList = [];
var movieResults = [];
fs.readdirSync(testFolder).forEach(file => {
movieList.push(tnp(file));
});
var movieObj = movieList.map(movie => {
var tmp = [];
return searchTMDB(movie.title).then(data => {
tmp.push(data);
return tmp
});
});
var checkDB = Promise.all(movieObj).then(moviesData => {
moviesData.map(movieData => {
checkMoviesInDB(movieData[0]).then(checkResponse => {
if (!checkResponse.movieToInsert) {
res.json(checkResponse);
} else {
var insertArray = checkResponse.movieToInsert;
var inserting = insertArray.map(movie => {
var movieObject = {
m_tmdb_id: movie.id,
m_name: movie.title,
m_year: movie.release_date,
m_desc: movie.overview,
m_genre: undefined,
m_poster: movie.poster_path,
m_watched: 0
};
insertMoviesToDB(movieObject).then(insertResponse => {
res.json(insertResponse);
});
});
}
});
});
});
}
function checkMoviesInDB(movie) {
var moviesToInsert = [];
return new Promise((resolve, reject) => {
var sql = "SELECT * FROM ?? WHERE m_tmdb_id = ?"
var table = ['movie', movie.id];
sql = mysql.format(sql, table);
connection.query(sql, function (err, rows) {
if (err) {
return reject(err);
}
if (rows.length === 0) {
moviesToInsert.push(movie);
resolve({
success: true,
movieToInsert: moviesToInsert
});
} else {
resolve({
success: true,
message: 'No movie to insert'
});
}
});
});
}
function insertMoviesToDB(movie) {
return new Promise((resolve, reject) => {
var sql = "INSERT INTO ?? SET ?";
var table = ['movie', movie];
sql = mysql.format(sql, table);
connection.query(sql, function (err, rows) {
if (err) {
return reject(err);
} else {
resolve({
success: true,
message: 'Movie added!'
});
}
});
});
}
function searchTMDB(title) {
return new Promise((resolve, reject) => {
https.get(config.tmdbURL + title, response => {
var body = "";
response.setEncoding("utf8");
response.on("data", data => {
body += data;
});
response.on("end", () => {
body = JSON.parse(body);
resolve(body.results[0]);
});
response.on("error", (err) => {
reject(err);
});
});
});
}
Auth.js
const config = require('./config');
const jwt = require('jsonwebtoken');
module.exports = function (req, res, next) {
var token = req.body.token || req.params.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, config.secret, function (err, decoded) {
if (err) {
return res.json({
success: false,
message: 'Failed to authenticate token.'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'Please login in to countinue!'
});
}
};
Hope this helps:
// Bad Way
const checkForMovies = (req, res) => {
const movieList = ['Braveheart', 'Highlander', 'Logan'];
movieList.forEach(movie => {
res.json(movie); // Will get Error on second loop: Can't set headers after they are sent.
})
}
// Good Way
const checkForMovies = (req, res) => {
const movieList = ['Braveheart', 'Highlander', 'Logan'];
const payload = { data: { movieList: [] } };
movieList.forEach(movie => {
payload.data.movieList.push(movie);
});
// send res once after the loop with aggregated data
res.json(payload);
}
/* GET home page. */
router.get('/', checkForMovies);

How to set nodejs to work synchronously?

var job = new cronJob('* * * * * *', function () {
Draft.find().then(data => {
var finalData = data;
finalData.forEach(function(item2) {
if (item2.scheduledTime === 'now') {
finalData.forEach(function (item) {
var psms = {
phoneno: item.senderdata,
sender: item.senderName,
message: item.message
}
var obj = psms;
var finalpostsms = obj.phoneno.split("\n").map(s => ({ ...obj,
phoneno: +s
}));
Profsms.bulkCreate(finalpostsms).then(function (data) {
if (data) {
console.log("successfully moved in profsms mysql");
} else {
console.log("failed");
}
})
});
} else {
console.log('Better you be in drafts..manual input');
}
//delete from draft
if (item2.scheduledTime === 'now') {
Draft.findOneAndRemove({
_id: item2._id
}, function (err, employee) {
if (err)
console.log('err');
console.log('Successfully deleted from draft');
});
} else {
console.log('You cant delete from drafts hahaha because no sendnow statement');
}
});
});
}, function () {
console.log('DelCron Job finished.');
}, true, 'Asia/Calcutta');
This above code, working as asynchronously.
I want the above code to be work as synchronous, need some answers. I am a newbie for JS development
Is it possible to do with async await? i dont know how to write async await code.
Your callback should be
async function(){
let data = await Draft.find();
...process data;
}
This is an async await sample code, you can modify based on your need. But first you need to use Node that support async syntax. I believe node 8 LTS is already have async/await feature.
function get() {
// your db code block
return Promise.resolve(7);
}
async function main() {
const r = await get();
console.log(r);
}
main();