h1ml Blog - Web Development & Engineering

website·Indexed 30 days ago

https://blog.h1ml.cn

A technical blog focusing on frontend engineering, JavaScript, and Vue.js. Content covers deep dives into Vue 3 and Vue 2 lifecycles, pnpm Monorepo architecture, Vite, Element Plus, and JavaScript core concepts like Promises, this binding, and async/await. It also provides practical guides on HTTP streaming interfaces, browser caching strategies, and npm dependency management.

Tokens
91.4K
Snippets
421
Records
565
Agent score
47%

What's inside h1ml Blog

  1. Implement a three-layer AI tool calling architecture

    To build a scalable AI tool system, use a three-layer architecture that separates API communication from business logic:

    1. AI Service Layer (e.g., OpenAIService): Handles communication with the AI provider (OpenAI API) and processes the initial response.
    2. Tool Management Layer (e.g., ToolService): Manages the registry of available tool handlers and dispatches tool calls to the correct handler.
    3. Tool Processing Layer (e.g., ToolHandlers): Contains the actual business logic for each specific tool.
  2. Understand OCI Network Topology for Public Instance Access

    In Oracle Cloud Infrastructure (OCI), a cloud instance resides within a Virtual Cloud Network (VCN) and a specific Subnet. Even a 'Public Subnet' uses a private CIDR range (e.g., 10.0.0.0/24). The instance connects to the subnet via a Virtual Network Interface Card (VNIC), which is assigned a Private IP. A Public IP is not part of the subnet's address range but is mapped/bound to the VNIC's Private IP to provide an external entry point.

    Traffic Flow for Inbound Requests:

    1. Public User $\rightarrow$ Internet Gateway (IGW): The entry point for public traffic.
    2. Security List / Network Security Group (NSG): Traffic is checked against subnet-level (Security List) and VNIC-level (NSG) rules.
    3. VNIC: Traffic is delivered to the instance's virtual network card.
    4. OCI Instance $\rightarrow$ OS Firewall: Traffic must pass through the instance's internal firewall (e.g., iptables, firewalld) and reach the application listening on the port.

    Traffic Flow for Outbound/Response (Return Path): Response traffic follows the path: Application $\rightarrow$ VNIC $\rightarrow$ Route Table $\rightarrow$ Internet Gateway $\rightarrow$ Public User. The Route Table must have a rule (typically 0.0.0.0/0 $\rightarrow$ Internet Gateway) for the response to reach the public internet; otherwise, the connection will time out despite the request successfully entering the VCN.

  3. Understand OCI Networking Components

    OCI networking is structured hierarchically to manage traffic flow and security:

    • VCN (Virtual Cloud Network): Your private network environment in OCI; it defines the overall boundary and structure.
    • Subnet: A subdivision of a VCN.
    • VNIC (Virtual Network Interface Card): The actual network interface of an instance. It is the entry and exit point for all traffic to the instance.
    • Private IP: The internal address assigned to a VNIC within the VCN.
    • Public IP: An external address bound to a VNIC's Private IP to allow internet access.
    • Internet Gateway (IGW): The gateway that allows traffic to flow between the VCN and the internet.
    • Route Table: Defines the rules for where traffic should be directed (e.g., directing all internet-bound traffic to the IGW).
    • Security List / NSG (Network Security Group): Virtual firewalls that determine whether specific traffic is allowed to enter or leave the subnet/VNIC.
  4. Distinguish between npm package distribution and application bundling

    There is a critical difference between how an npm package is published and how a final application is built:

    1. npm Package Publisher: Does NOT bundle dependencies into the dist/ folder. Dependencies are kept as import statements and declared in package.json so the end-user's package manager can install them.
    2. Application Project: DOES bundle all declared dependencies (including those from npm packages) into the final production assets (e.g., dist/assets/index.js) using Tree-shaking to remove unused code. The final deployment does not require the node_modules folder.
  5. Compare Vite and Webpack configuration and ecosystem

    Choosing between Vite and Webpack often depends on the required level of control and project scale:

    • Vite: Offers a simpler configuration experience where defaults satisfy most use cases. Its plugin ecosystem is rich and largely based on Rollup plugins.
    • Webpack: Has a more complex configuration requiring manual detail tuning. However, it possesses a massive, mature plugin ecosystem capable of implementing almost any build requirement.
  6. Follow the Security Development Lifecycle (SDL)

    Integrate security across four stages:

    1. Design: Perform threat modeling, security architecture reviews, and risk assessments.
    2. Development: Apply secure coding standards, perform dependency security checks, and conduct code security audits.
    3. Testing: Execute penetration testing, security scanning, and vulnerability verification.
    4. Operations: Manage security configurations, fix vulnerabilities, and establish emergency response protocols.
  7. Implement email verification flow in Node.js with Koa

    To implement email verification, use a layered architecture consisting of a Controller (HTTP handling), Service (business logic), Utility (code generation/storage), and Infrastructure (email delivery). The flow involves validating the email format, generating a secure code, storing it with an expiration timestamp, and sending it via SMTP.
    // Controller: Handles HTTP requests
    export class EmailVerificationController {
      public async sendEmailVerificationCode(ctx: Context): Promise<void> {
        const { email } = ctx.request.body as EmailRequest;
        if (!email || !this.validateEmail(email)) {
          ctx.status = 400;
          ctx.body = error("邮箱地址格式不正确", 400);
          return;
        }
        const result = await emailVerificationService.sendVerificationCode(email);
        if (result) {
          ctx.body = success(null, "验证码已发送,请检查邮箱");
        } else {
          ctx.status = 500;
          ctx.body = error("验证码发送失败,请稍后重试", 500);
        }
      }
    
      private validateEmail(email: string): boolean {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
      }
    }
    
    // Service: Orchestrates business logic
    export class EmailVerificationService {
      public async sendVerificationCode(email: string): Promise<boolean> {
        const code = EmailCodeUtil.generateEmailCode();
        EmailCodeUtil.saveCode(email, code);
        const result = await emailService.sendVerificationCode(email, code);
        if (!result) EmailCodeUtil.removeCode(email);
        return result;
      }
    }
  8. Implement error handling in a Node.js three-tier architecture

    In a three-tier architecture, error handling should act as a filter that transforms technical errors into business-domain errors and finally into HTTP responses. Each layer has a specific responsibility:

    1. Repository Layer: Captures raw database errors, logs technical details, and converts them into data-access errors.
    2. Service Layer: Captures repository errors, performs business logic validation, and converts data-access errors into business-domain errors with added context.
    3. Controller Layer: Captures all downstream exceptions and converts them into a unified HTTP response format with appropriate status codes.
  9. Monorepo Architecture Principles for Cross-Platform Projects

    To avoid environment compatibility issues (e.g., DOM API errors in mini-programs), follow these dependency rules:

    • packages/* (Shared Logic): Use only pure JS libraries (e.g., dayjs, lodash, axios). Avoid platform-specific UI libraries.
    • apps/web (Web App): Use Web-specific libraries like element-plus or echarts.
    • apps/uni (uni-app): Use cross-platform libraries like @dcloudio/uni-ui.
  10. Compare OS architecture support for common server distributions

    Different Linux distributions provide varying levels of support for AMD64 (x86_64) and ARM64 architectures:

    • CentOS Stream 9: Supports both amd64 and arm64 (Rolling release).
    • Debian 12.0: Supports both amd64 and arm64 (High stability).
    • Ubuntu Server 22.04 LTS: Supports both amd64 and arm64 (Long Term Support).
    • CentOS 7.6: Primarily amd64; arm64 support is limited.
    • OpenCloudOS 8: Primarily amd64; check official documentation for arm64 support.
  11. Understand the three types of uni-app project structures

    uni-app projects generally fall into three categories, each with different compilation flows and target audiences:

    1. Traditional uni-app Template (HBuilderX Built-in): A 'black box' approach where the compiler is built into the HBuilderX IDE. It lacks package.json, node_modules, and vite.config.ts. It is ideal for beginners or those who do not need CI/CD and prefer a GUI-driven workflow.
    2. uni-app (Vue3 + TS + Vite) Template: The modern recommended approach. It uses standard web tooling (package.json, vite.config.ts, npm/pnpm) and can be run via CLI or HBuilderX. It is suitable for professional developers, large-scale projects, and those requiring automation/CI.
    3. Standard Vue3 + Vite Project: A regular web project. While it uses Vue3, it is NOT a uni-app project because it lacks the necessary pages.json, manifest.json, and the uni-app runtime required for cross-platform deployment.