Home > Software engineering >  Return my function returns in my reponse using express (NodeJS, TypeScript)
Return my function returns in my reponse using express (NodeJS, TypeScript)

Time:07-09

I would like to know how I could send in my reply the return of my functions.

In this example I want to return in my response the error of my validator if I have one

Here is my SqlCompanyRepository.ts:

async create(company: CompanyCommand): Promise<CompanyEntity> {
    const createCompany = await dataSource.getRepository(CompanyEntity).save(company)
    await validate(company).then(errors => {
        if (errors.length > 0) {
            return errors;
        }
    });
    return createCompany
}

And here is my index.ts:

app.post("/company", async (req, res) => {
const company = new CompanyCommand()
company.id = crypto.randomUUID()
company.name = req.body.name
company.email = req.body.email
company.password = req.body.password

const checkEmail = await companyRepository.findByEmail(company.email)

if (!!checkEmail) {
    res.status(409).send("Email already exists.")
} else {
    const companyResult = await companyRepository.create(company)
    res.send(companyResult)
}
})

CodePudding user response:

Replace return errors; with throw errors;, this causes the Promise<CompanyEntity> to be rejected with errors.

Then wrap the invocation in a try-catch-block to catch this rejection:

try {
  const companyResult = await companyRepository.create(company)
  res.send(companyResult)
} catch(errors) {
  res.send(errors)
}
  • Related