I can't create a file download controller - javascript

When I try to use the .pipe() function in my controller I get an error and I don't know why. Attached my code below, thank you very much for the help in advance
const fs =require('fs');
module.exports={
inputs:{
name_file:{
type:"string",
required:true
}
},
exits: {
success: {
description: "Return matching data.",
},
defaultError: {
description: "It catches any error.",
responseType: "defaultError",
},
},
fn:function (inputs,exits){
//Comprobamos si el fichero viene en la peticion
if (!inputs.name_file) return exits.defaultError("No se ha adjuntado el nombre del archivo")
var nameFile=inputs.name_file
//Creamos ruta completa del fichero
var URL_FILE=process.cwd()
URL_FILE= URL_FILE.concat("\\.tmp\\uploads\\",nameFile,'.csv')
//Comprobamos si el fichero existe
fs.access(URL_FILE,fs.constants.F_OK,(err)=>{
return "El fichero no existe"
})
var response={}
var SkipperDisk = require('skipper-disk');
var fileAdapter = SkipperDisk(/* optional opts */);
// Stream the file down
var filedown=fileAdapter.read(URL_FILE)
filedown.on('error', function (err){
return exits.defaultError(err);
})
filedown.on('line',(linea)=>{
console.log(linea)
})
filedown.pipe(exits.success(response))
}
}
TypeError: Cannot read property 'on' of undefined```

Related

How could I cast to DateTimeInterface from String?? Symfony Ajax

My real problem is that I am sending an Ajax Jquery Request to an API of mine, the server response is 'Argument #1 of ::setDate() must be DateTimeInterface, string given'
I tried to cast but it was useless.
My Ajax at JQUERY:
$.ajax({
type: "PUT",
url: "/api/distribucion",
data: JSON.stringify(dist),
dataType: "json",
success: function (response) {
console.log("mesa " + response.id + " actualizada");
}
});
My API at PHP (Symfony's controller):
public function putDistribucion(ManagerRegistry $mr, Request $request): Response
{
$datos = json_decode($request->getContent());
$datos = $datos->distribucion;
// Cogemos el ID de el Distribucion a editar
$id = $datos->id;
// Obtenemos el Distribucion
$distribucion = $mr->getRepository(Distribucion::class)->find($id);
// Cambiamos todos sus campos
$distribucion->setPosicionX($datos->pos_x);
$distribucion->setPosicionY($datos->pos_y);
$distribucion->setFecha($datos->fecha);
$distribucion->setMesaId($datos->mesa_id);
$distribucion->setAlias($datos->alias);
$distribucion->setReservada($datos->reservada);
$manager = $mr->getManager();
try {
// Lo mandamos a actualizar
$manager->persist($distribucion);
$manager->flush();
} catch (PDOException $e) {
$this->json(['message' => $e->getMessage(), "Success" => false], 400);
}
# Creado con éxito => Devolvemos la ID
return $this->json(
[
"message" => "Éxito al editar la distribucion " . $id,
"Success" => true
],
202 // Aceptado
);
}
The Object I'm sending:
Your entity Distribucion probably has a setter that look like this:
public function setFecha(DateTimeInterface $fecha): self
{
$this->fecha = $fecha;
return $this;
}
The setter is typehinted with DateTimeInterface so you need to use a DateTime object and not a string.
You may create a DateTime easily with DateTime::createFromFormat
So $distribucion->setFecha($datos->fecha); will turn into something like:
$distribucion->setFecha(DateTime::createFromFormat('YYYY-MM-DD HH:ii:ss.u', $datos->fecha));
You may want to verify the date format I used as the first parameter of DateTime::createFromFormat
public static DateTime::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null)

Ionic modal fires twice

My ionic app fires a modal twice when hitting ion-button.
I cannot figured why it is happening.
<ion-button (click)="editProduct(p.id)" fill="clear">
<ion-icon name="cloud-upload"></ion-icon>
</ion-button>
editProduct(id) {
// obter dados do produto pelo seu id
this.afs.collection("products").doc(id)
.valueChanges()
.subscribe(data => {
this.product = data
// chamar o modal e enviar o id do produto
this.modalProduct(id);
});
}
async modalProduct(id) {
const modal = await this.modalCtrl.create({
component: AdminProductPage,
componentProps: {
'id': id,
'title': this.product.title,
'description': this.product.description,
'price': this.product.price,
'image': this.product.image
}
});
await modal.present();
}
I figured out by myself.
I need to use a pipe from rxjs to prevent double execution of editProduct() subscrive method.
editProduct(id) {
// obter dados do produto pelo seu id
this.afs.collection("products").doc(id)
.valueChanges()
.pipe(
first()
)
.subscribe(data => {
this.product = data
// chamar o modal e enviar o id do produto
this.modalProduct(id);
});
}

How to extract text from a carousel with puppeteer?

I want to get the text of this webpage and the following when clicking on the Oui or Non button, which will be at the same place, and store them as a json file :
I am open to solutions in javascript and python. I tried teh following one:
'use strict';
const puppeteer = require('puppeteer');
(async function main() {
try {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.goto('http://www.leparisien.fr/elections/municipales/municipales-a-paris-notre-simulateur-pour-savoir-quel-candidat-vous-correspond-le-mieux-05-03-2020-8273238.php');
const pollFrame = page.frames().find(
frame => frame.url() === 'https://livemixr-assets.s3-eu-west-1.amazonaws.com/quel-candidat/index.html'
);
// getting first question
const data = await pollFrame.evaluate(
() => document.querySelector('html > body > div > div > div > div > div:nth-child(5) > h4').innerText
);
console.log(data);
// clicking on an answer
await page.$x('/html/body/div/div/div[1]/div/div[5]/div/div/label[1]')
const elements = await page.$x('/html/body/div/div/div[1]/div/div[5]/div/div/label[1]')
await elements[0].click()
// getting second question
const data2 = await pollFrame.evaluate(
() => document.querySelector('html > body > div > div > div > div > div:nth-child(5) > h4').innerText
);
console.log(data2);
await browser.close();
} catch (err) {
console.error(err);
}
})();
Which get the first text, click on one button, get the second text.
But got the following error:
C:\Users\antoi\Documents\Programming\Scraping>node scraper.js
Faut-il accélérer l’automatisation du métro ?
TypeError: Cannot read property 'click' of undefined
at main (C:\Users\antoi\Documents\Programming\Scraping\scraper.js:24:23)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
So how to extract text from a webpage with puppeteer?
This selector is located inside an iframe, so you need to find this frame first.
While you are not so experienced in puppeteer, it would be easier to just use page.evaluate() (or frame.evaluate()) to get document data by executing web API code in the browser context.
For example:
'use strict';
const puppeteer = require('puppeteer');
(async function main() {
try {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.goto('http://www.leparisien.fr/elections/municipales/municipales-a-paris-notre-simulateur-pour-savoir-quel-candidat-vous-correspond-le-mieux-05-03-2020-8273238.php');
await page.waitForSelector('iframe[src="https://livemixr-assets.s3-eu-west-1.amazonaws.com/quel-candidat/index.html"]');
const pollFrame = page.frames().find(
frame => frame.url() === 'https://livemixr-assets.s3-eu-west-1.amazonaws.com/quel-candidat/index.html'
);
const data = await pollFrame.evaluate(() => {
const texts = [];
while (document.querySelector('div.ant-modal-content') === null) {
texts.push(document.querySelector('div:nth-child(5) > h4').innerText);
document.querySelectorAll('input[type="radio"]')[1].click();
// or: document.querySelector('input[type="radio"][value="Non"]').click();
}
return texts;
});
console.log(data);
await browser.close();
} catch (err) {
console.error(err);
}
})();
Output:
[
'Faut-il accélérer l’automatisation du métro ?',
'Faut-il faire payer le stationnement des deux-roues ?',
'Faut-il interdire les bus de tourisme dans la capitale ?',
'Faut-il piétonniser les quatre arrondissements centraux de la capitale ?',
'Faut-il réduire le nombre de places de stationnement en surface ?',
"Faut-il rendre le Vélib' gratuit ?",
'Faut-il renforcer la vidéoverbalisation ?',
'Faut-il rouvrir à la circulation les voies sur berges ?',
'Faut-il interdire les trottinettes électriques ? (free floating)',
'Le périphérique doit-il...',
'Les transports doivent-ils être rendus gratuits...',
"Faut-il demander l'annulation des Jeux olympiques ?",
'Faut-il mettre fin à la pratique du tirage au sort pour le conservatoire ?',
'Faut-il augmenter le nombre de caméras de vidéo-surveillance dans la rue ?',
'Faut-il créér une police municipale ?',
'Le future police municipale doit-elle être armée ?',
"Faut-il augmenter le montant des amendes (jets de mégots, urine, dépôt d'ordures...) ?",
'Faut-il privatiser le ramassage des déchets ?',
'À Paris, la société Airbnb doit-elle être ...',
'Faut-il baisser le nombre de nuitées autorisées à la location sur Airbnb (120 jours actuellement) ?',
"Faut-il maintenir l'encadrement des loyers?",
"En priorité, l'accès au logement social doit-il être attribué ...",
'Faut-il accroître le nombre de logements sociaux ?',
'En matière de finances, faut-il ...',
'Faut-il interdire les animaux sauvages dans les cirques ?',
'Faut-il proposer une alternative végétarienne tous les jours dans les cantines ?',
'Faut-il piétonniser les abords des écoles ?',
"Quelle est la priorité pour améliorer l'environnement ?",
'En cas de grèves, faut-il un service minimum pour les crèches et les écoles ?',
'Faut-il revenir à la semaine de 4 jours dans les écoles ?',
'Les tarifs des cantines scolaires doivent-ils ... ?',
'Faut-il étendre le travail du dimanche ?'
]

Symfony form validation from an AJAX render

I'm new to symfony, I render forms throughout a JSON so whenever I click on an icon it shows different forms (to change firstname, lastname...).
I return thoses forms as a JSON :
public function profileSettings()
{
$user = $this->getUser();
// Formulaire d'informations concernant le compte
$formAccountSettings = $this->createForm(AccountSettingsType::class, $user, [
'userEmail' => $user->getEmail(),
'userUsername' => $user->getUsername(),
]);
// Formulaire d'informations personnel
$formPersonnalSettings = $this->createForm(PersonnalSettingsType::class, $user, [
'userFirstname' => $user->getFirstname(),
'userLastname' => $user->getLastname(),
]);
// Retour en format JSON des 3 requêtes sous tableau
return $this->json(
[
'formAccountSettingsView' =>
$this->render('user/_accountSettings.html.twig', [
'form' => $formAccountSettings->createView(),
]),
'currentUser' => $user,
'formPersonnalSettingsView' => $this->render('user/_accountSettings.html.twig', [
'form' => $formPersonnalSettings->createView(),
]),
]
);
}
Here is how I display this :
$('#settings-user li').on('click', function (e) {
$.ajax({
type: 'GET',
url: "/website-skeleton/public/index.php/json/profile",
success: function (response) {
if ($(e.target).hasClass('profile')) {
$('.display').empty().append(
`
<p id="welcome">Bonjour, <em><strong>${response['currentUser']['username']}</strong></em> vous êtes enregistré sous le nom de <strong>${response['currentUser']['firstname']} ${response['currentUser']['lastname']}</strong>.
<br>
Votre adresse email est : <strong>${response['currentUser']['email']}</strong>.
<br>
Pour modifiez vos informations veuillez cliquez sur le menu de navigation.
</p>`);
} else if ($(e.target).hasClass('security')) {
$('.display').empty().append(response['formAccountSettingsView']['content']);
} else if ($(e.target).hasClass('informations')) {
$('.display').empty().append(response['formPersonnalSettingsView']['content'])
}
}
})
});
The problem now is that I don't know how to handle thoses forms from another controller and validate it with the constraints I set on my entity User this is how I validate :
public function editCredentials(Request $request, UserPasswordEncoderInterface $encoder)
{
$user = $this->getUser();
$formPersonnalSettings = $this->createForm(PersonnalSettingsType::class, $user);
if ($request->isMethod('POST')) {
if ($request->request->has('personnal_settings')) {
if ($formPersonnalSettings->isSubmitted() && $formPersonnalSettings->isValid()) {
$user->setFirstname($request->request->get('personnal_settings')['firstname']);
$user->setLastname($request->request->get('personnal_settings')['lastname']);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('personnal_success', 'Vos informations personnels ont bien été enregistrées !');
return $this->redirectToRoute('user_profile');
}
}
Is that a good method? should I handle everything with ajax ? Thanks for your time !
You should use the handlerequest which automatically sets the values in the form to the entity added to it once the form has been submitted.
$form = $this->createCreateForm($entity); // private function to create the form
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
}
}
return $response;
Once handled you just need to return an ok response, or return the form back to the view if something has gone wrong.
If I remember well, the asserts set on the entity are also automatically processed with the handleRequest(), it depends on how you declared them.
Yo can also add other errors after the submit, just add them between the isSumbmitted() and isValid(). Documentation
I leave you here some documentation that may help.
Handle request
Validation
Validation in the form itself

Getting json from an URL and displaying specific data

I got a problem when I try to get the json from an URL in my reverse geocoding method :
I tried this based on a solution found on stackoverflow.
When I try to show the json in my alert it shows: undefined
adressReverseGeoCode(item: any, elementId: any) {
var getJSON = (url: any, callback: any) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = () => {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('http://nominatim.openstreetmap.org/reverse?format=json&lat=' + item.latitude + '&' + 'lon=' + item.longitude + '&addressdetails=1',
(err: any, data: any) => {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
alert(data.result);
}
});
}
I want to get the "display_name" from the json in order to put it in a text input later.
You can try this link to see the json file
{
"place_id":"154253419",
"licence":"Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright",
"osm_type":"way",
"osm_id":"424211755",
"lat":"-23.56183",
"lon":"-46.6598392",
"display_name":"Alameda Ministro Rocha Azevedo, Jardim Paulista, São Paulo, Microrregião de São Paulo, RMSP, Mesorregião Metropolitana de São Paulo, São Paulo, Southeast Region, 01410-001, Brazil",
"address":{"road":"Alameda Ministro Rocha Azevedo","suburb":"Jardim Paulista","city_district":"Jardim Paulista","city":"São Paulo","county":"Microrregião de São Paulo","state_district":"Mesorregião Metropolitana de São Paulo","state":"São Paulo","postcode":"01410-001","country":"Brazil","country_code":"br"},
"boundingbox":["-23.5642064","-23.5601209","-46.662319","-46.6580485"]
}
Thank you in advance for any help you can give me !
There is not data.result! thats why it is undefined. Your data is the JSON. so just do data.display_name. Probably!
var obj = JSON.parse(data); // as suggested by #charlietfl
console.log(obj.display_name);
alert(obj.display_name);

Categories