mominger / blog

Tech blog
45 stars 3 forks source link

Based on Koa2+Typescript BFF (Backend for Frontend) architecture design #44

Open mominger opened 10 months ago

mominger commented 10 months ago

Overview

  1. This article first briefly explains a standard BFF (Backend for Frontend) architecture.
  2. Second,since our business mostly involves making direct calls to external services and returning responses, so I have enhanced the design for external service access in common MVC (Model-View-Controller) architecture.
  3. Last explains the process of how the BFF (Backend for Frontend) backend authenticates WeChat Mini Program users For more details, you can refer to the source code

Standard BFF Architecture

Suitable for various client types, the Standard BFF Architecture involves each client having a dedicated BFF backend. This backend interacts with and processes data from internal microservices. While it may not fully align with the company's overarching architecture, it does not impact the design of the mini-program's backend.

Mini Program Backend's BFF Design

Made primarily in the MVC Design, with specific enhancements focusing on external services.

Key Design

Unified Response Structure

Errors are identified through specific HTTP codes and unique error codes for easier client-side handling.

Response Data When Correct

{
    "data": {},
    "msg": "Success!",
    "code": 10000
}

Response Data for General Errors

{
    "msg": "bg-key is auth failed",
    "code": 20004
}

Response Data for Errors in External Services

{
    "data": {
        "data": {
            "error": {
                "message": "BadRequest 400 Bad Request: Error get booking data from payments deep-link"
            }
        },
        "status": 400
    },
    "msg": "Third-party service error!",
    "code": 30000
}

Mini Program's API Authentication Design

Key Design

Ensuring Real User Authentication

The mini-program uses the wx.login function to obtain a temporary code, which is then sent to the WeChat server for verification by the BFF backend.

Keeping the API Token Secure