简体   繁体   中英

Multi actions API best Practice / Design Pattern

I have an API with a multi actions POST function.

It is structured like that:

exports.myFunction = functions.https.onRequest((request: any, response: any) => {
    const action: 'a' | 'b' | 'c' = request.body.action;
    switch(action) {
      case 'a':
        doProcessA();
        break;
      case 'b': 
        doProcessB();
        break;
      case 'c': 
        doProcessC();        
        break;
    }
    response.send('done');
});

I cannot split this function into 3 exposed functions. Regarding this contraint, is my code clean, or is there any better practice / Design pattern to handle such situation?

The main principle of microservices and FaaS design is the separation of concern.

If your processes are similar, or reuse some parts of processing, your pattern make sense.


However, if your process are complex, if they can evolve independently, if he required resources are the same in each process, the pattern is not the correct one. It's better to have 1 router, and 3 "process functions".

You need to keep only one entry point, no problem, this fonction will only route the request to the corresponding process function.

The process function is responsible on one, and only one process. It can evolve independently, it can scale independently, you can tune it (memory/cpu) as required

Some advanced API gateways are also able to replace your router function.

The type of controller/logic, as you are using, is not uncommon. For example ASP.net Web API Routing takes much the same approach.

You just want to make sure your code and API are composed in a sensible way:

  • Different API's have their own routing branches - like what you posted.
  • The routing is as efficient and clean as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM