How to use a rest API in promise chaining, unifying FE / BE (react, express)?

Viewed 111

This is a very general question and it may sound sketchy at first. As a full stack javascript developer, I come acros the same problem again and again concerning the matching between the calls the frontend makes to the backend, and the route handler the backend uses for each request. So the code looks like this:

// frontend

onTrigger(event).then(some logic).then(api GET '/api/endpoint').then(do something with the response)

// backend

route.get('/api/endpoint').businessLogic().respond(data)

I want a way to unify all this thing and as a result to have something like this:

onTrigger(event).then(some logic).unify(api GET '/api/endpoint').businessLogic().then(do something with the response)

I know at first it may sound terrible, but this way a developer has full control over the whole process of what's going on with the application. And just before building the project, a transpiler could check for all the "unify" methods and build all the requests / api calls for the frontend, and all the route handlers for the backend. I mean there is no reason to have such an overhead code over the libraries that make the requests on FE and the routers that handle these requests. I think it would be really helpful if you could only have access to what matters which is just the business logic of the application. Also, it would be really convenient because the application's Data Transfer Object and the Errors could be shared among frontend and backend.

For example,

// Current situation

// frontent
onTrigger(event).then(fetch data).catch(http error).then(do something with data)

// backend
route.apiMethod().authorize().then(respond).catch(return new UnauthorizedError())
// proposed unification

onTrigger(event).unify(fetch data).then(do something with data).catch(UnauthorizedError).catch(a general error)

With the proposed solution, both data model and UnauthorizedError can be shared seamlessly between FE/BE. This way less mistakes will be done from a developer concerning the DTO's and the error messages between FE and BE.

So my question is if there is any actual value to what I am proposing and how hard would it be to create a "transpiler" which will go through the code to find all the "unify" methods and then build the boilerplate code needed for FE and BE ?

0 Answers
Related