Bỏ qua, đến nội dung

Tham chiếu API — REST API Data Source

Tổng quan kiến trúc

Plugin REST API hoạt động theo mô hình proxy: khi Digiforce nhận request CRUD từ user, HttpApiRepository chuyển tiếp thành HTTP request đến API bên ngoài, rồi chuyển đổi response thành dữ liệu collection.

Các thao tác CRUD

list — Lấy danh sách

typescript
// HttpApiRepository.find()
const templateContext = {
  request: { params: { filter, sort, page, pageSize } },
  $env: app.environment.getVariables(),
};
const { transformedResponse } = await collection.runAction('list', templateContext);
return transformedResponse.data; // IModel[]

get — Lấy một bản ghi

typescript
// HttpApiRepository.findOne()
const { transformedResponse } = await collection.runAction('get', templateContext);
return transformedResponse.data; // IModel

create — Tạo bản ghi

typescript
// HttpApiRepository.create()
// values được lọc qua whiteList/blackList trước khi gửi
const { transformedResponse } = await collection.runAction('create', templateContext);
return transformedResponse.data;

update — Cập nhật bản ghi

typescript
// HttpApiRepository.update()
const { transformedResponse } = await collection.runAction('update', templateContext);
return transformedResponse.data;

destroy — Xóa bản ghi

typescript
// HttpApiRepository.destroy()
const { transformedResponse } = await collection.runAction('destroy', templateContext);
return transformedResponse.data;

count — Đếm bản ghi

typescript
// HttpApiRepository.count()
const { transformedResponse } = await collection.runAction('list', templateContext);
return transformedResponse.meta?.count ?? transformedResponse.data.length;

Debug API (runAction)

Plugin đăng ký resource dataSources.httpCollections với action runAction để hỗ trợ gửi request thử nghiệm từ giao diện quản trị:

typescript
await agent.resource('dataSources.httpCollections').runAction({
  sourceId: 'my-rest-api',
  values: {
    actionOptions: {
      type: 'list',
      method: 'GET',
      path: '/users',
      headers: [],
      params: [{ name: 'page', value: '1' }],
      contentType: 'application/json',
      responseTransformer: {
        data: '{{rawResponse.body.results}}',
        meta: { count: '{{rawResponse.body.total}}' },
      },
    },
    inferFields: true,
    debug: true,
    debugVars: {},
  },
});

Kết quả trả về của Debug Mode

TrườngMô tả
rawResponse.statusHTTP status code
rawResponse.statusTextHTTP status text
rawResponse.headersResponse headers
rawResponse.dataResponse body gốc
rawResponse.requestThông tin request đã gửi (url, method, headers)
transformedResponseDữ liệu sau khi qua response transformer
fieldsDanh sách fields được nhận diện (nếu inferFields: true)
filterTargetKeyPrimary key được đoán (id, nodeId, node_id)
debugBodyBody dùng cho hiển thị debug

ActionOptions — Cấu hình chi tiết cho mỗi action

typescript
interface ActionOptions {
  type: 'list' | 'get' | 'create' | 'update' | 'destroy';
  method: string;                    // HTTP method
  path: string;                      // URL path (hỗ trợ template)
  headers: Array<{ name, value }>;   // Headers bổ sung
  params: Array<{ name, value }>;    // Query parameters
  contentType: 'application/json' | 'application/x-www-form-urlencoded';
  body?: { value: any };             // Request body
  responseTransformer?: any;         // Template chuyển đổi response
  errorMessageTransformer?: any;     // Template trích xuất lỗi
  dataJsonPath?: string;             // JSON path đến mảng data
  totalCountJsonPath?: string;       // JSON path đến tổng số bản ghi
}

WhiteList và BlackList

HttpApiRepository hỗ trợ whiteListblackList cho các thao tác create/update:

Thuộc tínhMô tả
whiteListChỉ gửi các trường trong danh sách này
blackListLoại bỏ các trường trong danh sách này

Thứ tự áp dụng: whiteListblackList. Nếu cả hai đều có, whiteList được áp dụng trước, rồi blackList loại bỏ thêm.

Xử lý lỗi

Plugin đăng ký error handler vào plugin-error-handler để xử lý lỗi từ API bên ngoài:

  1. Nếu API trả về HTTP error (4xx/5xx), plugin ném Error với cause chứa thông tin lỗi
  2. Nếu có errorMessageTransformer, trích xuất thông báo lỗi từ response body
  3. Nếu không có transformer, sử dụng thông báo mặc định: Restful api request failed: {status} {statusText}
typescript
// Ví dụ errorMessageTransformer
{
  errorMessageTransformer: "{{rawResponse.body.error.message}}"
}

Biến môi trường và Template Context

Mỗi request đến API bên ngoài được xây dựng với template context bao gồm:

BiếnNguồnMô tả
request.headersRequest gốcHeaders của request từ user
request.tokenBearer tokenToken xác thực của user hiện tại
request.paramsAction paramsFilter, sort, page, pageSize
request.bodyRequest bodyDữ liệu cho create/update
dataSourceVariablesCấu hình data sourceBiến tùy chỉnh
$envEnvironment VariablesBiến môi trường hệ thống
valuesCreate/Update dataDữ liệu bản ghi

Content-Type

Plugin hỗ trợ hai loại Content-Type:

  • application/json (mặc định): Body được gửi dưới dạng JSON
  • application/x-www-form-urlencoded: Body được chuyển thành URL-encoded string qua URLSearchParams