[node] Call backend functions from the frontend
There are several ways to communicate between the backend and the frontend. I would like to share a few of them and go in more detail about a new one I recently discovered.
I started working with nodejs when it was in beta and it got my attention because it was really easy to setup websockets. Since we use SPAs it's not needed anymore to return html from the backend. I'm used to transfer data via rest (json) and before my time soap (xml) was really populair and is still used in a lot of systems. Currently GraphQL is gaining attraction and one of the advantages is that you can automatically generate types of the query, which you can use on the backend and the frontend. This blogpost is about RPC.
RPC stands for Remote Procedure Call and is actually really old. Maybe you can call it FaaS (Functions as a Service) as well, although the idea is that you run your own (private) service. It's so simply that I don't know if the terminology is correct. As the title is saying, the idea is that you can call backend functions from the frontend. They have the same name, same arguments and same return value. The only difference is that the function is asynchronously, because it does a post request under the hood to the backend, which actually calls the real function and returns the value.
Ok, enough talk. The wildcard-api package is doing the heavy lifting and next is some code that will make it more clear. Let's start with creating an express app and use the Wildcard middleware.
backend/app.ts
As you can see, we also imported endpoints.ts. Here we define our functions we want to share with the frontend.
backend/endpoints.ts
You might wonder why we we adding async in front of the function getFoo, since the functions is synchronously. The first reason is because it's going to be called from the frontend and there it will be used asynchronously due to the request to the backend and the second reason you'll get later. Now in the frontend we can do the following.
frontend/print-foo.ts
Et voilà, it will print the number 5! And you know, the function is even typed! For example, if you add an argument to the getFoo function, the typescript compiler will complain on the frontend about a missing argument where the function is being called. The second reason we prepended async to the function is to make sure the type of the function is a Promise<number>.
Using this package will increase productivity, although I think it can't replace all other communication methods. Especially if you want to make a public api or if you want to make use of the graphql frontend libraries. JSON might get less popular in the future. If you know the types on both sides, there is no need for (human) readable data and it is more efficient to only send the contents without the structure.