How to simplify a javascript function into clean readable code? - javascript

here i have created a function , it is framing a object by getting two values as arguments. It is working fine. But in the code wise is not simple. It is not readable. Here i am sharing the code of what i have done. Please suggest me where i have to modify the code. In order to make it more clear and readable.
import uuid from 'uuid/v4';
const questionsObject = {};
const finalDndDataFormat = {};
let value = [{"groups":[{"notes":"","questions":[{"name":"loanAmount"}]},{"questions":[{"name":"loanReason"}]},{"questions":[{"name":"email","type":"email"}]},{"questions":[{"name":"title","required":true}]},{"questions":[{"name":"firstName"},{"name":"lastName"}]}],"id":"my-needs"},{"groups":[{"questions":[{"name":"phone"},{"name":"isCellPhone"}]},{"questions":[{"name":"dateOfBirth","options":[]}]},{"questions":[{"name":"residenceStatus","options":[],"label":"q_ownRent_text","type":"radio","required":true}]},{"questions":[{"name":"addressLine1"},{"name":"addressLine2"},{"name":"city"},{"name":"province","options":[]},{"name":"postalCode"}],"title":"q2_supporting_2"},{"questions":[{"name":"employmentStatus","options":[]}]}],"id":"a-bit-about-me"},{"groups":[{"questions":[{"name":"residenceDuration","options":[]}]},{"questions":[{"name":"previousAddressLine1"},{"name":"previousAddressLine2"},{"name":"previousCity"},{"name":"previousProvince"},{"name":"previousPostalCode"}],"title":"q2_supporting_2"},{"questions":[{"name":"previousResidenceDuration"}]},{"questions":[{"name":"residenceStatus"}]},{"questions":[{"name":"principalResidence"}]},{"questions":[{"name":"residenceType"}]},{"questions":[{"name":"propertyValue"}]},{"questions":[{"name":"monthlyMortgagePayments"}]},{"questions":[{"name":"mortgageBalance"}]}],"id":"my-home"},{"groups":[{"questions":[{"name":"employmentDuration"}]},{"questions":[{"name":"previousEmploymentDuration"}]},{"questions":[{"name":"paycheckAmount"}]},{"questions":[{"name":"paycheckFrequency"}]},{"questions":[{"name":"hasAdditionalIncome"},{"name":"additionalIncomeSource"}]},{"questions":[{"name":"hasChildTaxCredit"},{"name":"childTaxCreditMonthlyAmount"},{"name":"numberOfDependentsChildTaxCredit"}]},{"questions":[{"name":"sinNumber"}]}],"id":"my-income"},{"groups":[{"questions":[{"name":"hasPaydayLoan","options":[]},{"name":"paydayLoanAmountOwing"}]},{"questions":[{"name":"hasOtherLiabilities","options":[]},{"name":"otherLiabilitySource","options":[]}]},{"questions":[{"name":"isEasyHomeCustomer","options":[]},{"name":"easyhomePaymentsLiabilityMonthlyAmount"}]}],"id":"liabilities"},{"groups":[{"notes":"","questions":[{"name":"agreeTermsConditionsAndPrivacyPolicy","options":[],"links":[]}]}],"id":"t-and-c"}]
let appPages = ["my-needs", "a-bit-about-me", "my-home", "my-income", "liabilities", "t-and-c"]
const setDndDataStructure = (value, appPages) => {
const dndFormat = value?.map((data) => {
appPages.forEach((pages) => {
switch (data?.id) {
case pages:
const questions = data?.groups || {};
questions.map((obj) => {
obj.id = uuid();
const uniqueQuestionName = obj?.questions?.map((questionsField) => questionsField?.name);
obj.unique = uniqueQuestionName[0];
});
const dndDataFormat = { [pages]: { name: pages, items: questions } };
Object.assign(questionsObject, dndDataFormat);
Object.assign(finalDndDataFormat, questionsObject);
break;
default:
break;
}
});
});
return finalDndDataFormat;
};
setDndDataStructure( value , appPages )
Result:
{"my-needs":{"name":"my-needs","items":[{"notes":"","questions":[{"name":"loanAmount"}],"id":"1b356c8f-0087-4929-8894-2a929aa25c6c","unique":"loanAmount"},{"questions":[{"name":"loanReason"}],"id":"59a57164-d945-4747-a429-763a38da61d5","unique":"loanReason"},{"questions":[{"name":"email","type":"email"}],"id":"d526fb2f-8612-4313-a4be-b1779817ccd2","unique":"email"},{"questions":[{"name":"title","required":true}],"id":"420028a5-a280-4fb4-96f6-a3fa464ad531","unique":"title"},{"questions":[{"name":"firstName"},{"name":"lastName"}],"id":"fe2f12e9-5c66-4b6b-ab82-ec7d3fe50226","unique":"firstName"}]},"a-bit-about-me":{"name":"a-bit-about-me","items":[{"questions":[{"name":"phone"},{"name":"isCellPhone"}],"id":"d74a5ba2-30a8-473b-8db9-bf82b3f2a6e9","unique":"phone"},{"questions":[{"name":"dateOfBirth","options":[]}],"id":"86ae162d-beb7-4f1a-a74b-c161515f3144","unique":"dateOfBirth"},{"questions":[{"name":"residenceStatus","options":[],"label":"q_ownRent_text","type":"radio","required":true}],"id":"0e5b151d-46f8-460d-862a-3e75aa6438df","unique":"residenceStatus"},{"questions":[{"name":"addressLine1"},{"name":"addressLine2"},{"name":"city"},{"name":"province","options":[]},{"name":"postalCode"}],"title":"q2_supporting_2","id":"31120f92-771d-4136-b465-ad7abf944718","unique":"addressLine1"},{"questions":[{"name":"employmentStatus","options":[]}],"id":"03796c7b-7ff9-4abb-9fe3-f01db45de4f3","unique":"employmentStatus"}]},"my-home":{"name":"my-home","items":[{"questions":[{"name":"residenceDuration","options":[]}],"id":"65ce7da7-005e-4f62-ba5a-0768afa01111","unique":"residenceDuration"},{"questions":[{"name":"previousAddressLine1"},{"name":"previousAddressLine2"},{"name":"previousCity"},{"name":"previousProvince"},{"name":"previousPostalCode"}],"title":"q2_supporting_2","id":"e9682e67-8e03-4ffd-b695-a8bc50dca98d","unique":"previousAddressLine1"},{"questions":[{"name":"previousResidenceDuration"}],"id":"f473e302-469b-4196-aa1a-00da1bdb4cf6","unique":"previousResidenceDuration"},{"questions":[{"name":"residenceStatus"}],"id":"c3f4f424-9619-458f-9e20-343247835ecd","unique":"residenceStatus"},{"questions":[{"name":"principalResidence"}],"id":"6c6d9aa8-e693-40f4-b805-b1333c6e97f1","unique":"principalResidence"},{"questions":[{"name":"residenceType"}],"id":"1946d5fd-86ae-4c18-aeb6-7f03d2cfc3e1","unique":"residenceType"},{"questions":[{"name":"propertyValue"}],"id":"27ed276a-e42c-4a9a-923e-fdf953ef4e56","unique":"propertyValue"},{"questions":[{"name":"monthlyMortgagePayments"}],"id":"38b306c2-4328-4c10-9281-e736348c4047","unique":"monthlyMortgagePayments"},{"questions":[{"name":"mortgageBalance"}],"id":"b67b7f19-caef-4404-9592-0c4293d92c4d","unique":"mortgageBalance"}]},"my-income":{"name":"my-income","items":[{"questions":[{"name":"employmentDuration"}],"id":"ad78527d-c5d9-42f3-879e-79c78c10c72d","unique":"employmentDuration"},{"questions":[{"name":"previousEmploymentDuration"}],"id":"596d9c81-5549-4e98-935d-faf65cd91b8d","unique":"previousEmploymentDuration"},{"questions":[{"name":"paycheckAmount"}],"id":"076827a0-1e77-4455-bfb5-d0d7c59fd34c","unique":"paycheckAmount"},{"questions":[{"name":"paycheckFrequency"}],"id":"709704d6-5451-4fcb-93d1-c11090d789b4","unique":"paycheckFrequency"},{"questions":[{"name":"hasAdditionalIncome"},{"name":"additionalIncomeSource"}],"id":"a17cde6c-6a3f-4792-bfc6-bafa2237cf1c","unique":"hasAdditionalIncome"},{"questions":[{"name":"hasChildTaxCredit"},{"name":"childTaxCreditMonthlyAmount"},{"name":"numberOfDependentsChildTaxCredit"}],"id":"a138e279-712b-4e0a-9adb-30c4b89f754f","unique":"hasChildTaxCredit"},{"questions":[{"name":"sinNumber"}],"id":"ab5e04ac-3cd7-431f-adbf-a63ecf410af0","unique":"sinNumber"}]},"liabilities":{"name":"liabilities","items":[{"questions":[{"name":"hasPaydayLoan","options":[]},{"name":"paydayLoanAmountOwing"}],"id":"6aedc455-1204-4dfb-8f76-97c4bdc0b66b","unique":"hasPaydayLoan"},{"questions":[{"name":"hasOtherLiabilities","options":[]},{"name":"otherLiabilitySource","options":[]}],"id":"fda26736-db4f-4a38-b122-dd6a898be9df","unique":"hasOtherLiabilities"},{"questions":[{"name":"isEasyHomeCustomer","options":[]},{"name":"easyhomePaymentsLiabilityMonthlyAmount"}],"id":"fda94364-9b90-4a93-80ac-698415a5207d","unique":"isEasyHomeCustomer"}]},"t-and-c":{"name":"t-and-c","items":[{"notes":"","questions":[{"name":"agreeTermsConditionsAndPrivacyPolicy","options":[],"links":[]}],"id":"b7c74dce-1251-4831-8066-65cb73a598c7","unique":"agreeTermsConditionsAndPrivacyPolicy"}]}}
Above code is the sample i have done.
Thanks in advance

Just add a few comments
//At the end, setDnDStructure will leave x structured as y
const setDndDataStructure = (value, appPages) => {
const dndFormat = value?.map((data) => { // mapping x to y so that z
appPages.forEach((pages) => {
switch (data?.id) {
case pages:
const questions = data?.groups || {};
questions.map((obj) => {
obj.id = uuid();
const uniqueQuestionName = obj?.questions?.map((questionsField) => questionsField?.name);
obj.unique = uniqueQuestionName[0];
});
const dndDataFormat = { [pages]: { name: pages, items: questions } };
Object.assign(questionsObject, dndDataFormat);
Object.assign(finalDndDataFormat, questionsObject);
break;
default:
break;
}
});
});
return finalDndDataFormat;
};
The comments I've added should give you an idea of how you can make this more readable. Outline what you are trying to achieve at the end, and use comments in your function to outline what each step is doing

Related

How to get each item from a filtered array, without using a map for each item

I'm taking an array and filtering the value in a context:
const { responsible } = useResponsible()
const [ids, setIds] = useState([])
const filteredResponsible = responsible?.filter((resp) =>
ids.includes(resp.id)
)
The problem is that I need to make a map to get the corresponding value of each id, one by one. This ends up making the code too long:
const { filteredResponsible } = useResponsible
const responsibleName = filteredResponsible.map((resp) => resp.name)
const responsibleEmail = filteredResponsible.map((resp) => resp.email)
const responsibleAddress = filteredResponsible.map((resp) => resp.address)
...
And so on with each item in the array.
I'm using the React Hook Form's setValue to set the value in the inputs:
useEffect(() => {
setValue('name', `${responsibleName}`)
setValue('email', `${responsibleEmail}`)
setValue('address', `${responsibleAddress}`)
setValue('cep', `${responsibleCep}`)
setValue('district', `${responsibleDistrict}`)
setValue('city', `${responsibleCity}`)
setValue('state', `${responsibleState}`)
setValue('phone', `${responsiblePhone}`)
setValue('sex', `${responsibleSex}`)
}, [])
How can I make these maps smaller? Without having to make a map to get each item in the array?
There doesn't seem to be any reason to do those map calls on every render and to do them anywhere other than where you need them, since you only show using the result in a mount-only effect. Just do them there:
const { filteredResponsible } = useResponsible; // Is there really no `()` needed here?
useEffect(() => {
setValue("name", `${filteredResponsible.map(({name}) => name)}`);
setValue("email", `${filteredResponsible.map(({email}) => email)}`);
setValue("address", `${filteredResponsible.map(({address}) => address)}`);
// ...
}, []);
If you really need those distinct arrays on every render, unless you can change your data structures to be more amenable to your output I don't see you have a lot of options. You can at least avoid multiple loops through filteredResponsible:
const { filteredResponsible } = useResponsible; // ()?
const responsibleName = [];
const responsibleEmail = [];
const responsibleAddress = [];
for (const { name, email, address } of filteredResponsible) {
responsibleName.push(name);
responsibleEmail.push(email);
responsibleAddress.push(address);
}
And if that's really the case, you may want to avoid doing it on every render:
const { filteredResponsible } = useResponsible; // ()?
const { responsibleName, responsibleEmail, responsibleAddress } = useMemo(() => {
const responsibleName = [];
const responsibleEmail = [];
const responsibleAddress = [];
for (const { name, email, address } of filteredResponsible) {
responsibleName.push(name);
responsibleEmail.push(email);
responsibleAddress.push(address);
}
return { responsibleName, responsibleEmail, responsibleAddress };
}, [filteredResponsible]);

How to filter two arrays of splitting?

I'm a bit confused
I am sending emails with nodemailer, and every time I send one I perform certain validations in order to manage the upload limit of the attachments. If the upload limit exceeds what is established, the service divides that email and sends it in different emails with the same subject and body as well as its attachment.
Every time this happens, it does a _.chunk that takes care of splitting the pdfs array into smaller elements. But, it should be noted that before that, he made a method to prepare the attachments and this is in charge of obtaining certain information from the api to paint the pdf buffer and thus put it in the content of the emails.
But now what I want to do is search within the matrix that performs the step before dividing the files those that are equal to the array that obtains the information and if they are equal, carry out the instruction that it sends
I will explain with a graph:
If getAmount.pdfBuffer === attachmentMap
// doAction console.log('Equals)
But even though I tried to do it, I couldn't, I don't know if it's because for each attachment that the array has divided, it generates a getAmount array. What do you think I'm doing wrong?
async sendEmail(
{
para: to,
asunto: subject,
plantilla: template,
contexto: context,
}: CorreoInfoDto,
attachments: EmailAttachment[],
driveConfig: OAuthGoogleConfig
) {
const totalSize: number = this.getSizeFromAttachments(attachments);
const chunkSplit = Math.floor(isNaN(totalSize) ? 1 : totalSize / this.LIMIT_ATTACHMENTS) + 1;
const attachmentsChunk: any[][] = _.chunk(attachments, chunkSplit);
if ((totalSize > this.LIMIT_ATTACHMENTS) && attachmentsChunk?.length >= 1) {
await Promise.all(
attachmentsChunk?.map(async (attachment: EmailAttachment[], index) => {
console.log('attachment', attachment)
if (this.getSizeFromAttachments(attachment) > this.LIMIT_ATTACHMENTS) {
const result: GenerateDriveLinkResponse[] = await Promise.all(
attachment?.map(item => {
const file = new GoogleDriveUploadFile({
name: item?.filename,
mimeType: MimeTypesEnum.PDF,
body: item?.content
});
return this.uploadFilesService.uploadToDrive(driveConfig, file) as any;
})
)
const texto = result?.map((item, index) => {
console.log('item', item?.webViewLink);
console.log('index', index);
return new SolicitudXLinkDrive({
texto: attachment[index].filename,
link: item?.webViewLink
})
});
context.links = texto;
const link = `(${index + 1}/${attachmentsChunk?.length - 1})`;
const newContext = {
getCurrent: link,
...context
}
const prepareEmail = this.prepareEmail({
para: to,
asunto: ` ${subject} (${index + 1}/${attachmentsChunk?.length})`,
plantilla: template,
contexto: newContext,
}, []);
return prepareEmail
} else {
// this.getCantidad = `(${index + 1}/${attachmentsChunk?.length - 1})`;
console.log('getCantidad', this.getAmount );
const attachmentMap = attachment.map(element => element.content);
this.getAmount .forEach(element => {
if (element.pdfBuffer === attachmentMap) {
console.log('do action');
}
})
const link = ` (${index + 1}/${attachmentsChunk?.length - 1})`;
const newContext = {
getCurrent: link,
...context
}
return this.prepareEmail({
para: to,
asunto: ` ${subject} (Correo ${index + 1}/${attachmentsChunk?.length - 1})`,
plantilla: template,
contexto: newContext,
}, attachment);
}
})
);
} else {
await this.prepareEmail(
{
para: to,
asunto: ` ${subject}`,
plantilla: template,
contexto: context,
},
attachments,
);
}
}
async prepareEmail(
{
para: to,
asunto: subject,
plantilla: template,
contexto: context,
}: CorreoInfoDto,
attachments: EmailAttachment[],
) {
return await this.mailerService.sendMail({
to,
from: `${process.env.SENDER_NAME} <${process.env.EMAIL_USER}>`,
subject,
template,
attachments: attachments,
context: context,
});
}
async sendEmails(correos: EnvioMultiplesCorreosDto) {
let pdf = null;
let info: ConfiguracionDocument = null;
let GDriveConfig: ConfiguracionDocument = null;
let logo: ConfiguracionDocument = null;
let forContext = {};
const documents = Array.isArray(correos.documento_id) ? correos.documento_id : [correos.documento_id];
const solicitudes = await this.solicitudesService.findByIds(documents);
const nombresPacientes = solicitudes.reduce((acc, cv) => {
acc[cv.correlativo_solicitud] = cv['info_paciente']?.nombre_paciente;
return acc;
}, {});
await Promise.all([
await this.getPdf(correos.tipo_reporte, correos.documento_id, correos?.dividir_archivos).then(data => { pdf = data; }),
await this.configuracionesService.findByCodes([
ConfigKeys.TEXTO_CORREO_MUESTRA,
ConfigKeys[process.env.DRIVE_CONFIG_API],
ConfigKeys.LOGO_FIRMA_PATMED
]).then(data => {
info = data[0];
GDriveConfig = data[1];
logo = data[2];
})
]);
forContext = this.configuracionesService.castValorObjectToObject(info?.valor_object)
const attachmentPrepare = this.prepareAttachments(pdf as any, nombresPacientes);
await this.sendEmail(
{
para: correos.para,
asunto: correos.asunto,
plantilla: 'muestras',
contexto: {
cuerpo: correos.cuerpo,
titulo: forContext[EnvioCorreoMuestraEnum.titulo],
direccion: forContext[EnvioCorreoMuestraEnum.direccion],
movil: forContext[EnvioCorreoMuestraEnum.movil],
pbx: forContext[EnvioCorreoMuestraEnum.pbx],
email: forContext[EnvioCorreoMuestraEnum.email],
logo: logo?.valor,
},
},
attachmentPrepare,
this.configuracionesService.castValorObjectToObject(GDriveConfig?.valor_object) as any,
);
const usuario = new UsuarioBitacoraSolicitudTDTO();
usuario.createFromUserRequest(this.sharedService.getUserFromRequest());
solicitudes.forEach((solicitud) => {
const actual = new BitacoraSolicitudDTO();
actual.createFromSolicitudDocument(solicitud);
const newBitacora = new CrearBitacoraSolicitudDTO();
newBitacora.createNewItem(null, actual, actual, usuario, AccionesBitacora.EmailEnviado);
this.bitacoraSolicitudesService.create(newBitacora);
});
}
prepareAttachments(item: BufferCorrelativosDTO | BufferXSolicitudDTO[], nombresPacientes: { [key: string]: string }) {
if (this.sharedService.isAnArray(item)) {
const castItem: BufferXSolicitudDTO[] = item as any;
this.getCantidad = castItem;
return castItem?.map((s) => {
const namePatient = nombresPacientes[s.correlativo_solicitud];
return new EmailAttachment().setFromBufferXSolicitudDTO(s, namePatient, 'pdf');
});
} else {
return [new EmailAttachment().setFromBufferCorrelativosDTO(item as any, 'pdf')];
}
}
Thank you very much for your attention, I appreciate it. Cheers
You could try using lodash as this has _.intersectionBy and _.intersectionWith functions that should allow you to compare 2 arrays and filter the common values.
There are some good examples here:
How to get intersection with lodash?

Set parameters from UI to SQL editor, React/JS

the idea of this stuff is that user can add parameters to the SQL editor from two inputs, one for the parameter itself and the other one for its value
and if user writes in SQL editor, automatically adds inputs that are the parameter and the value.
From SQL editor to inputs it works fine, cause I'm sending a regex. The trouble is located where I try to send the inputs to SQL Editor. I think is more like a logic problem, but I still don't find the solution.
The point is that by adding one parameter from the input, it adds more than required, even though I always clean it before adding, but apparently that doesn't affect.
This is the code
import React, { useEffect, useState} from 'react';
import SQLContainerInput from '../Components/SQLContainerInput';
........
function arrayParamsExec(stringSql) {
const paramsQueryText = [...stringSql.matchAll(/{{(\w+)}}/ig)];
const newArray = paramsQueryText.map(item => item[1]);
return newArray;
}
const initalStateCurrentChartInfo = {
SQLQuery: '',
dataType: 'TABLE',
columns: [],
};
const CustomSQLEditor = ({
fromQuery, // del Redux
}) = {
const [currentChartInfo, setCurrentChartInfo] = useState(
initalStateCurrentChartInfo,
);
const [params, setParams] = useState([]);
const [textSql, setTextSql] = useState('');
useEffect(() => {
....
let sqlDefaultString = '';
sqlDefaultString = fromQuery.internal_name
? `SELECT * FROM \`${fromQuery.internal_name}__${fromQuery.items[0]}\` LIMIT 20`
: '';
setCurrentChartInfo({
...currentChartInfo,
SQLQuery: `${sqlQuery}`,
});
},[fromQuery]);
// ------------------params---------------------
const addProperty = () => {
setParams([
...params,
{ name: '', value: '' },
]);
};
const updateProperty = (event, index, key) => {
const newProperties = [...params];
newProperties[index][key] = event?.target?.value;
// agregar parĂ¡metros al editor SQL
let sqlParams = textSql;
if (key === 'name') {
params.forEach(p => {
if (p.name && /^\w+$/i.test(p.name)) {
sqlParams += `{{${p.name}}}`;
}
});
setTextSql('');
setTextSql(`${sqlParams}`);
}
setParams(newProperties);
};
const deleteProperty = index => {
const newProperties = [...params];
newProperties.splice(index, 1);
const newTextSQL = replaceAll(textSql, `{{${params[index]?.name}}}`, '');
setTextSql(newTextSQL);
setParams(newProperties);
};
// ------------------end params---------------------
const changeTextEditor = (valueEditor) => {
const namesParams = arrayParamsExec(valueEditor);
const newProperties = namesParams.map((pName) => {
const valueNew = params.find(p => p.name === pName);
return {name: pName, value: valueNew?.value || ''};
});
setParams(newProperties);
setTextSql(valueEditor);
}
return (
<>
<SQLContainerInput
button={{
onClick: handleSubmit,
}}
input={{
value: `${textSql}\n`,
onChange: changeTextEditor,
}}
/>
<DymanicKeyValueInputInput
properties={params}
updateProperty={updateProperty}
deleteProperty={deleteProperty}
addProperty={addProperty}
/>
</>
);
}
Then, I tried as a solution set another value which is textSql, that takes care of placing the concatenated string, and the string coming from redux is fromQuery. The redux string is set in the sqlParams variable, when is added concatenates with the params and then, I clean textSql
......
const updateProperty = (event, index, key) => {
const newProperties = [...params];
newProperties[index][key] = event?.target?.value;
// agregar parĂ¡metros al editor SQL
let sqlParams = currentChartInfo.SQLQuery;
if (key === 'name') {
params.forEach(p => {
if (p.name && /^\w+$/i.test(p.name)) {
sqlParams += `{{${p.name}}}`;
}
});
setTextSql('');
setTextSql(`${sqlParams}`);
}
setParams(newProperties);
};
......
The trouble in there is that if I directly write from SQL editor, it resets the whole string, I mean, everything that has been written but there it works when I put the params and it's not repeated. I don't find a way to do that, so I'm sorry for the ignorance if I'm doing something wrong.
For example, when I write a large SQL text.
When a parameter is added from the input, it resets.
Video with the error demo: https://www.youtube.com/watch?v=rQBPOPyeXlI
Repo's url: https://gitlab.com/albert925/parametrosui-a-editor-sql
try this:
import { useState, useEffect } from 'react';
import DymanicKeyValueInputInput from './components/DymanicKeyValueInputInput';
import SQLContainerInput from './components/SQLContainerInput';
import { fromQuery } from './bd/data';
import { replaceAll, arrayParamsExec } from './utils/strings';
import { Content, ContentAddButton } from './stylesApp';
const initalStateCurrentChartInfo = {
SQLQuery: '',
columns: [],
};
function App() {
const [currentChartInfo, setCurrentChartInfo] = useState(
initalStateCurrentChartInfo,
);
const [params, setParams] = useState([]);
const [textSql, setTextSql] = useState('');
const [endSql, setendSql] = useState('');
useEffect(() => {
let sqlQuery = '';
sqlQuery = fromQuery.internal_name
? `SELECT * FROM \`${fromQuery.internal_name}__${fromQuery.items[0]}\` LIMIT 20`
: '';
setCurrentChartInfo({
...currentChartInfo,
SQLQuery: `${sqlQuery}`,
});
setTextSql(sqlQuery);
},[fromQuery]);
useEffect(()=>{
const endSql = replaceAll(textSql, '\n', '');
setendSql('')
setendSql(endSql);
},[textSql]);
const cleanSQLString = (string) => {
//corto la cadena en {{
//reemplazo {{ por "" en cada item
//devuelvo el array con los reemplazos
return string.split("{{").map(item=>item.replace("}}",""));
}
// ------------------params---------------------
const addProperty = () => {
setParams([
...params,
{ name: '', value: '' },
]);
};
const updateProperty = (event, index, key) => {
const newProperties = [...params];
newProperties[index][key] = event?.target?.value;
let currentSQL = cleanSQLString(endSql);
// clean the string so that then add parameters to sql
if (key === 'name' && /^\w+$/i.test(event?.target?.value)) {
let sqlParams;
if(currentSQL.length > 1){
sqlParams = `${currentSQL[0]}`;
}else{
sqlParams = `${endSql}`;
}
params.forEach(p => {
if (p.name && /^\w+$/i.test(p.name)) {
sqlParams += `{{${p.name}}}`;
}
});
setTextSql('');
setTextSql(`${sqlParams}`);
/*if(currentSQL.length > 1){
sqlParams = `${currentSQL[0]}`;
}else{
sqlParams = `${endSql}`;
}
console.log(sqlParams)
// get parameter positions by regular expression
const searchParamRegedix = arrayParamsExec(endSql);
console.log(searchParamRegedix, 'searchParamRegedix')
if (searchParamRegedix.paramsQueryText.length > 0) {
console.log(111)
// get the position
const searchPosition = searchParamRegedix.paramsQueryText[index]?.index;
// remove the old word in braces
const deleteOldParam = replaceAll(sqlParams, `${searchParamRegedix.list[index]}`, '');
// the remaining string is removed from the obtained position
const deleteFirtsLetter = deleteOldParam.substr(searchPosition + 2);
// the string is removed from the beginning to the position obtained
const deleteRemaining = deleteOldParam.substr(0, searchPosition + 2)
// the string of the beginning and end is combined with its parameter
const contantString = deleteRemaining + event?.target?.value + deleteFirtsLetter;
// the entire string is overwritten in the state
setTextSql(contantString);
}
else{
params.forEach(p => {
if (p.name && /^\w+$/i.test(p.name)) {
sqlParams += `{{${p.name}}}`;
}
});
setTextSql('');
setTextSql(`${sqlParams}`);
}*/
}
setParams(newProperties);
};
const deleteProperty = index => {
const newProperties = [...params];
newProperties.splice(index, 1);
const newTextSQL = replaceAll(textSql, `{{${params[index]?.name}}}`, '');
setTextSql(newTextSQL);
setParams(newProperties);
};
// ------------------end params---------------------
const changeTextEditor = (valueEditor) => {
const namesParams = arrayParamsExec(valueEditor);
// keep the value with the parameter with respect to adding a new parameter in the sql editor,
// but if the parameter word is changed, the value is deleted
const newProperties = namesParams.list.map((pName) => {
const valueNew = params.find(p => p.name === pName);
return {name: pName, value: valueNew?.value || ''};
});
setParams(newProperties);
setTextSql(valueEditor);
}
return (
<Content>
<div>
<SQLContainerInput
input={{
value: `${endSql}\n`,
onChange: changeTextEditor,
}}
/>
</div>
<div>
<h2>PARAMS</h2>
<ContentAddButton>
<DymanicKeyValueInputInput
properties={params}
updateProperty={updateProperty}
deleteProperty={deleteProperty}
addProperty={addProperty}
id="sqlapiparams"
className="isMultipleInpustSelects"
tilesColumns={["", ""]}
inputsPlaceholder={["My_Parameter", "Type params value"]}
isIconTransfer
isIconError
/>
</ContentAddButton>
</div>
</Content>
);
}
export default App;

How do I get user details in Firebase Storage?

I'm a new programmer and very new to firebase and I'm trying to get the current user files info to display on the screen, it seems that my problem is that I can get the URL and the metadata separately, how do I combine them? how can I take everything at once?
I need to show the file name, date, time, link to download.
const getUserFiles = async () => {
if (!userUID) {
return null;
}
let listRef = storageRef.child(userUID);
listRef.listAll().then(res => {
// res.prefixes.forEach((item) => {
// });
res.items.forEach(item => {
item.getMetadata().then(item => {
var file = {
name: item.name.toString(),
timeCreated: item.timeCreated.toString(),
link: '',
};
myFiles.push(file);
});
});
res.items.forEach(item => {
let counter = 0;
item.getDownloadURL().then(url => {
myFiles[counter].link = url.toString();
});
});
});
console.log(myFiles);
};
the current method don't work! and notice that the userUID its only the uid without the user (local state)
Thanks!
The problem is with the asynchronous calls. You're making an async call in forEach and forEach expects a synchronous function.
You can change the logic to use for-of instead.
See below:
const getUserFiles = async () => {
if (!userUID) {
return null;
}
let listRef = storageRef.child(userUID);
const res = await listRef.listAll();
for (const itemRef of res.items) {
const itemMetadata = await itemRef.getMetadata();
const url = await itemRef.getDownloadUrl();
var file = {
name: itemMetadata.name.toString(),
timeCreated: itemMetadata.timeCreated.toString(),
link: url,
};
myFiles.push(file);
}
console.log(myFiles);
}

How to bypass jest setTimeout error of 5000ms by managing promises (Async and Await)

I wrote an Async/Await function to return promises for drivers report and analysis.
I have three different promise API files I extracted details from to do my analysis. However running test ith jest I get the error
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:
I have refactored my code more than three times in two days but the error returns.
I will like to know how to manage my promises, perhaps there is something am not doing well and I am keen on this for optimization.
Is there a way to manage the promises in the code below to bypass the jest error?
any other suggestion will be highly appreciated.
NB: sorry I have post all the code for better insight.
code
const { getTrips } = require('api');
const { getDriver } = require('api')
const { getVehicle } = require('api')
/**
* This function should return the data for drivers in the specified format
*
* Question 4
*
* #returns {any} Driver report data
*/
async function driverReport() {
// Your code goes here
let trip = await getTrips()
trip = trip.map(item => {
item.billedAmount = parseFloat(item.billedAmount.toString().replace(',', '')).toFixed(2);
return item;
})
let getId = trip.reduce((user, cur) => {
user[cur.driverID] ? user[cur.driverID] = user[cur.driverID] + 1 : user[cur.driverID] = 1
return user
}, {})
// console.log(getId)
let mapId = Object.keys(getId)
// console.log(mapId)
let eachTripSummary = mapId.reduce((acc, cur) => {
let singleTrip = trip.filter(item => item.driverID == cur)
acc.push(singleTrip)
return acc
}, [])
// eachTripSummary = eachTripSummary[0]
// console.log(eachTripSummary)
// console.log(trip)
let reducedReport = eachTripSummary.reduce(async(acc, cur) =>{
acc = await acc
// console.log(acc)
let user = {}
let cash = cur.filter(item => item.isCash == true)
// console.log(cash.length)
let nonCash = cur.filter(item => item.isCash == false)
let driverSummary = await getDriverSummary(cur[0]['driverID'])
let trips = []
let customer = {}
cur[0].user ? (customer['user'] = cur[0]['user']['name'], customer['created'] = cur[0]['created'], customer['pickup'] = cur[0]['pickup']['address'],
customer['destination'] = cur[0]['destination']['address'], customer['billed'] = cur[0]['billedAmount'], customer['isCash'] = cur[0]['isCash']) : false
trips.push(customer)
let vehicles = []
if(driverSummary == undefined){
// console.log(cur)
user = {
id: cur[0]['driverID'],
vehicles: vehicles,
noOfCashTrips: cash.length,
noOfNonCashTrips: nonCash.length,
noOfTrips: cur.length,
trips: trips
}
acc.push(user)
// console.log(user)
return acc
}
let driverInfo = driverSummary[0]
let vehicleInfo = driverSummary[1]
let { name, phone } = driverInfo
let { plate, manufacturer } = vehicleInfo[0]
// console.log(plate)
let vpm = {
plate,
manufacturer
}
vehicles.push(vpm)
// console.log(cash.length)
user ={
fulName: name,
phone,
id: cur[0]['driverID'],
vehicles: vehicles,
noOfCashTrips: cash.length,
noOfNonCashTrips: nonCash.length,
noOfTrips: cur.length,
trips: trips
}
acc.push(user)
// console.log(acc)
return acc
}, [])
// reducedReport.then(data =>{console.log(data)})
return reducedReport
}
async function getDriverSummary(param) {
let driverDetails = await getDriver(param)
.then(data => {return data}).catch(err => {return err})
// console.log(driverDetails)
let vehicleDetails;
let { vehicleID } = driverDetails
if(driverDetails != "Error" & vehicleID != undefined){
// console.log(vehicleID)
vehicleDetails = vehicleID.map(async item => {
let vehicleSummary = getVehicle(item)
return vehicleSummary
})
// console.log(await vehicleDetails)
return await Promise.all([driverDetails, vehicleDetails])
}
}
driverReport().then(data => {
console.log(data)
})
module.exports = driverReport;
Use jest.setTimeout(30000); to increase the timeout. It will increase the timeout globally.
// jest.config.js
module.exports = {
setupTestFrameworkScriptFile: './jest.setup.js'
}
// jest.setup.js
jest.setTimeout(30000)
Or you can use user test example like this
describe("...", () => {
test(`...`, async () => {
...
}, 30000);
});

Categories

Resources