Home > Net >  What is the best practice for creating payload for a request?
What is the best practice for creating payload for a request?

Time:10-24

This might be a very noob query, but I would like to have a opinion. And I'm not sure how should I proceed. Basically, I want to create a payload for my POST request:

const payload = {
      empCode: userId,
      name: firstName,
      doj: moment(employee?.doj?.date).format('DD MMM, YYYY'),
      designation: designation ?? '',
      location: resForms.countryOfBirth ?? '',
      region: resForms.region ?? '',
      email: email ?? '',
      contact: employee?.profile?.contact,
      rmMail: employee?.profile?.rmMail,
      hr: hr ?? '',
      Aadhar_Card: resForms.aadharNumber ?? '',
      Latest_Electricity_Bill: documents['uploadLatestElectricityBill']?.[0]['signedUrl'] ?? '',
      Highest_Degree_Certificates: documents['uploadDegreeCertificate']?.[0]['signedUrl'] ?? '',
      '10th_Marksheet':
        documents['educationDetails']?.[0]?.['uploadDegreeMarksheet'][0]['signedUrl'] ?? '',
      '12th_Marksheet':
        documents['educationDetails']?.[1]?.['uploadDegreeMarksheet'][0]['signedUrl'] ?? '',
      Bachelors_Marksheet:
        documents['educationDetails']?.[2]?.['uploadDegreeMarksheet'][0]['signedUrl'] ?? '',
      Relieving_Letter: documents['uploadRelievingLetter']?.[0]['signedUrl'] ?? '',
      Last_Three_Month_Salary_Slip: documents['uploadLastMonthsPayslips']?.[0]['signedUrl'] ?? '',
      PED_Form: documents['uploadPedForm']?.[0]['signedUrl'] ?? ''
    };

At the moment my payload looks like this and boy is it ugly, should I create a type for this payload separately? ( I know I should right? ). Also, more importantly there is a variable called documents which is and array of objects. What could be a better way to extract data instead of doing this?

Any suggestions are welcome... Thanks in advance.

CodePudding user response:

In overall, the object will end up the same, The only matter is to make it more readably, You can do so by separate some parts of it into smaller chunks of functions, for example:

const getPersonalInfo = () => ({
      empCode: userId,
      name: firstName,
      doj: moment(employee?.doj?.date).format('DD MMM, YYYY'),
      designation: designation ?? '',
      location: resForms.countryOfBirth ?? '',
      region: resForms.region ?? '',
      email: email ?? '',
      contact: employee?.profile?.contact,
      rmMail: employee?.profile?.rmMail,
      hr: hr ?? '',
})

const payload = {
 ...getPersonalInfo(),
 ...getLatestElectricityBill(),
 ...getEducationDetails()
}

I will also advise you to use some Utils to make the code a bit more clean, for example lodash get - https://lodash.com/docs/4.17.15#get Where you can use it in something like that:

_.get(documents, 'educationDetails.0.uploadDegreeMarksheet.0.signedUrl'. '')
  • Related