rest.ts icon indicating copy to clipboard operation
rest.ts copied to clipboard

[Improvement] Multiple returns and status codes

Open ricardo-devis-agullo opened this issue 5 years ago • 1 comments

Right now, every endpoint can only return one thing, but what if I want to type multiple things, linked to status codes?

Like, instead of just

    listPublications: GET `/publications/${'category'}`
        .response(PublicationsList),

It would be nice if we could do something like

import { StatusCodes } from 'rest-ts-core';

const ErrorModel = rt.Record({
  message: rt.String,
  code: rt.Number,
});
/// ....
    listPublications: GET `/publications/${'category'}`
        .response(StatusCodes.OK, PublicationsList)
        .response(StatusCodes.NOT_FOUND, rt.Void)
        .response(StatusCodes.INTERNAL_ERROR, ErrorModel),

So then, in my api implementation, I could have some helpers to type the returns to status codes like

.listPublications((req, res) => {
  try {
    const publicationsList = await getPublicationsList();
    if (publicationsList) {
      return StatusCodes.ok(publicationsList);
    } else {
      return StatusCodes.notFound();
    }
  } catch (err) {
    return StatusCodes.internalError({message: 'Something failed', code: 123})
  }
})

ricardo-devis-agullo avatar Apr 07 '20 16:04 ricardo-devis-agullo

This is a niche use case, although it makes complete sense.

There is some other work I'd like to prioritise before getting into this kind of refinement.

hmil avatar May 13 '20 21:05 hmil