Hkm Sadek
Hkm Sadek

Reputation: 3209

Typescript return and async await

I am facing a design problem in typescript. In my controller I do a validation and validation method returns 422 response which ends the thread or a validated data which I am trying to use. So here is my code. In my controller I have

async createFeed(ctx : HttpContextContract){
    await this.feedValidator.createFeedValidate(ctx)
    return this.feedService.createFeed(ctx)
  }

Here await this.feedValidator.createFeedValidate(ctx) does the validation logic and this method return 422 or a validated object

try {
        const payload = await ctx.request.validate({ schema: createFeedSchema, messages : msg })
        return payload
      } catch (error) {
         return ctx.response.status(422).send(error.messages)
  }


Right now, with this approach, I am not being able to access the payload returned by the validation method.

If I try

let validatedData = await this.feedValidator.createFeedValidate(ctx)
return this.feedService.createFeed(ctx,validatedData)

Then the thread doesn't stop if validation returns return ctx.response.status(422).send(error.messages)

Is there anyways, I can do method chaining or have nice advanced solution?

Thank you in advanced.

Upvotes: 0

Views: 456

Answers (1)

Julien
Julien

Reputation: 852

You seem to be using AdonisJS. If you look at the documentation, the send method ( ctx.response.status(422).send(error.messages)) returns 'void', i.e. nothing. That's why you can't get the return from your try catch.

Alternatively, you could do something like this:

Your createFeedValidateMethod should only contains this :

return ctx.request.validate({ schema: createFeedSchema, messages : msg })

and in your controller :

async createFeed(ctx : HttpContextContract){
   try {
    let validatedData = await this.feedValidator.createFeedValidate(ctx)
    return this.feedService.createFeed(ctx, validatedData)
   } catch (err) {
     return ctx.response.status(422).send(error.messages)
   }
}

Upvotes: 3

Related Questions