Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Code Generation

Static Generation (compile-time file output)

#![allow(unused)]
fn main() {
use afast::{GenerateTarget, Lang, JsTsCallType, RsCallType};

let app = AFast::new()
    .service(api_svc)
    .generate(vec![
        GenerateTarget {
            lang: Lang::TS(vec![JsTsCallType::Fetch, JsTsCallType::Ws]),
            path: "./code".into(),
            debug: false,
        },
        GenerateTarget {
            lang: Lang::RS(vec![RsCallType::TcpAsync]),
            path: "./src/bin/client".into(),
            debug: true,
        },
    ]);
}

Dynamic Generation (HTTP endpoint)

GET /code/api/ts?call=fetch,ws
GET /code/api/js?call=fetch,ws
GET /code/pay/kt?call=http,ws,tcp
GET /code/api/rs?call=tcp-async

Supported Transport Types

TS/JS

ValueAPI
fetchBrowser fetch
wsBrowser WebSocket
nodetcpNode.js net
buntcpBun Bun.connect
unirequestUniApp uni.request
uniwsUniApp uni.connectSocket
wxrequestWeChat Mini Program wx.request
wxwsWeChat Mini Program wx.connectSocket

Kotlin

ValueAPI
http / fetchjava.net.HttpURLConnection
wsjava.net.http.WebSocket
tcpjava.net.Socket

Rust

ValueAPI
tcp-asynctokio::net::TcpStream (async)
tcp-syncstd::net::TcpStream (sync)

Client Usage

import { ApiClient } from './api';

// Dedicated WS port
const wsClient = new ApiClient('ws://localhost:3000');
const wsResult = await wsClient.apis.user.list_users({ page: 1, size: 20 });

// Merged mode (WS and HTTP on the same port)
const mergedClient = new ApiClient('ws://localhost:5000');
// Auto-connects to ws://localhost:5000/_ws

The client transport mode is fixed at construction time.

Client-Side Caching

The cache(seconds) attribute enables client-side caching:

#![allow(unused)]
fn main() {
#[handler(desc("List users"), cache(60))]
async fn list_users(...) -> Result<ListUsersResponse> { /* ... */ }
}

Generated client:

const users = await client.apis.admin.listUsers({ page: 1, size: 20 });
// Within 60 seconds, same params return cached data

const fresh = await client.apis.admin.listUsers({ page: 1, size: 20 }, true);
// force = true bypasses cache

About TextEncoder / TextDecoder

The generated client code uses TextEncoder and TextDecoder APIs. These are unavailable on React Native (older versions), WeChat Mini Programs, and older browsers.

Solutions:

  1. Polyfill: npm install text-encoding + import 'text-encoding'
  2. React Native 0.72+: Built-in support
  3. WeChat/UniApp: Use wxrequest/wxws/unirequest/uniws transport types