rest.ts
rest.ts copied to clipboard
[Improvement] Multiple returns and status codes
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})
}
})
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.