天天看點

如何優雅地校驗後端接口資料,不做前端背鍋俠

作者:小小怪下士的架構攻略

背景

最近新接手了一批項目,還沒來得及接新需求,一大堆bug就接踵而至,仔細一看,應該傳回數組的字段傳回了 null,或者沒有傳回,甚至傳回了字元串 "null"???

這我能忍?我立刻截圖發到群裡,用紅框加大加粗重點标出。後端同學也積極響應,答應改正。

如何優雅地校驗後端接口資料,不做前端背鍋俠

第二天,同樣的事情又在其他的項目上演,我隻是一個小前端,為什麼什麼錯都找我啊!!

日子不能再這樣下去,于是我決定寫一個工具來解決遇到 bug 永遠在找前端的困境。

TypeScript 運作時校驗

如何對接口資料進行校驗呢,因為我們的項目是 React+TypeScript 寫的,是以第一時間就想到了使用 TypeScript 進行資料校驗。但是衆所周知,TypeScript 用于編譯時校驗,有沒有辦法作用到運作時呢?

我還真找到了一些運作時類型校驗的庫:typescript-needs-types,大部分需要使用指定格式編寫代碼,相當于對項目進行重構,拿其中 star 最多的 zod 舉例,代碼如下。

import { z } from "zod";

const User = z.object({
  username: z.string(),
});

User.parse({ username: "Ludwig" });

// extract the inferred type
type User = z.infer<typeof User>;
// { username: string }
           

我甯可查 bug 也不可能重構手裡一大堆項目啊。此種方案 ❎。

此時看到了 typescript-json-schema 可以把 TypeScript 定義轉為 JSON Schema ,然後再使用 JSON Schema 對資料進行校驗就可以啦。這種方案比較靈活,且對代碼入侵性較小。

搭建一個項目測試一下!

使用 npx create-react-app my-app --template typescript 快速建立一個 React+TS 項目。

首先安裝依賴 npm install typescript-json-schema

建立類型檔案 src/types/user.ts

export interface IUserInfo {
  staffId: number
  name: string
  email: string
}
           

然後建立 src/types/index.ts 檔案并引入剛才的類型。

import { IUserInfo } from './user';

interface ILabel {
  id: number;
  name: string;
  color: string;
  remark?: string;
}

type ILabelArray = ILabel[];

type IUserInfoAlias = IUserInfo;
           

接下來在 package.json 添加腳本

"scripts": {
    // ...
    "json": "typescript-json-schema src/types/index.ts '*' -o src/types/index.json --id=api --required --strictNullChecks"
}
           

然後運作 npm run json 可以看到建立了一個 src/types/index.json 檔案(此步在已有項目中可能會報錯報錯,可以嘗試在 json 指令中添加 --ignoreErrors 參數),打開檔案可以看到已經成功轉成了 JSON Schema 格式。

{
    "$id": "api",
    "$schema": "http://json-schema.org/draft-07/schema#",
    "definitions": {
        "ILabel": {
            "properties": {
                "color": {
                    "type": "string"
                },
                "id": {
                    "type": "number"
                },
                "name": {
                    "type": "string"
                },
                "remark": {
                    "type": "string"
                }
            },
            "required": [
                "color",
                "id",
                "name"
            ],
            "type": "object"
        },
        "ILabelArray": {
            "items": {
                "$ref": "api#/definitions/ILabel"
            },
            "type": "array"
        },
        "IUserInfoAlias": {
            "properties": {
                "email": {
                    "type": "string"
                },
                "name": {
                    "type": "string"
                },
                "staffId": {
                    "type": "number"
                }
            },
            "required": [
                "email",
                "name",
                "staffId"
            ],
            "type": "object"
        }
    }
}
           

使用 JSON Schema 校驗資料

至于如何使用JSON Schema 校驗資料,我找到了現成的庫 ajv,至于為什麼選擇 ajv,主要是因為它說它很快,詳見:https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance

如何優雅地校驗後端接口資料,不做前端背鍋俠

接下來嘗試一下。我找到了中文版文檔,有興趣的可以去看下 http://www.febeacon.com/ajv-docs-zh-cn/。

先安裝依賴 npm install ajv,然後建立檔案 src/validate.ts

import Ajv from 'ajv';
import schema from './types/index.json';

const ajv = new Ajv({ schemas: [schema] });

export function validateDataByType(type: string, data: unknown) {
  console.log(`開始校驗,類型:${type}, 資料:`, data);

  var validate = ajv.getSchema(`api#/definitions/${type}`);
  if (validate) {
    const valid = validate(data);
    if (!valid) {
      console.log('校驗失敗', validate.errors);
    }
    else {
      console.log('校驗成功');
    }
  }
}
           

接下來在 src/index.tsx 添加下面代碼來測試一下。

validateDataByType('IUserInfoAlias', {
  email: '[email protected]',
  name: 'idonteatcookie',
  staffId: 12306
})

validateDataByType('IUserInfoAlias', {
  email: '[email protected]',
  staffId: 12306
})

validateDataByType('IUserInfoAlias', {
  email: '[email protected]',
  name: 'idonteatcookie',
  staffId: '12306'
})
           

可以在控制台看到成功列印如下資訊:

如何優雅地校驗後端接口資料,不做前端背鍋俠

攔截請求

因為項目中發送請求都是調用統一封裝的函數,是以我首先想到的是在函數中增加一層校驗邏輯。但是這樣的話就與項目代碼耦合嚴重,換一個項目又要再寫一份。我真的有好多項目QAQ。

那幹脆攔截所有請求統一處理好了。

很容易的找到了攔截所有 XMLHttpRequest 請求的庫 ajax-hook,可以非常簡單地對請求做處理。

首先安裝依賴 npm install ajax-hook,然後建立 src/interceptTool.ts:

import { proxy } from 'ajax-hook';
export function intercept() {
  // 擷取 XMLHttpRequest 發送的請求
  proxy({
    onResponse: (response: any, handler: any) => {
      console.log('xhr', response.response)
      handler.next(response);
    },
  });
}
           

這樣就攔截了所有的 XMLHttpRequest 發送的請求,但是我突然想到我們的項目,好像使用 fetch 發送的請求來着???

好叭,那就再攔截一遍 fetch 發送的請求。

export function intercept() {
  // ...
  const { fetch: originalFetch } = window;
  // 擷取 fetch 發送的請求
  window.fetch = async (...args) => {
    const response = await originalFetch(...args);
    response.clone().json().then((data: { result: any }) => {
      console.log('window.fetch', args, data);
      return data;
    });
    return response;
  };
}
           

為了證明攔截成功,使用 json-server 搭建一個本地 mock 伺服器。首先安裝 npm install json-server,然後在根目錄建立檔案 db.json:

{
  "user": { "staffId": 1, "name": "cookie1", "email": "[email protected]" },
  "labels": [
    {
      "id": 1,
      "name": "ck",
      "color": "red",
      "remark": "blabla"
    },
    {
      "id": 2,
      "color": "green"
    }
  ]
}
           

再在 package.json 添加腳本

"scripts": {
  "serve": "json-server --watch db.json -p 8000"
},
           

現在執行 npm run serve 就可以啟動伺服器了。在 src/index.tsx 增加調用接口的代碼,并引入 src/interceptTool.ts。

import { intercept } from './interceptTool';
// ... other code
intercept();

fetch('http://localhost:8000/user');

const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8000/labels');
xhr.send();
           
如何優雅地校驗後端接口資料,不做前端背鍋俠

可以看到兩種請求都攔截成功了。

校驗接口傳回資料

勝利在望,隻差最後一步,校驗傳回資料。我們校驗資料需要提供兩個關鍵資訊,資料本身和對應的類型名,為了将兩者對應起來,需要再建立一個映射檔案,把 url 和類型名對應起來。

建立檔案 src/urlMapType.ts 然後添加内容

export const urlMapType = {
  'http://localhost:8000/user': 'IUserInfoAlias',
  'http://localhost:8000/labels': 'ILabelArray',
}
           

我們在 src/validate.ts 新增函數 validateDataByUrl

import { urlMapType } from './urlMapType';
// ...
export function validateDataByUrl(url: string, data: unknown) {
  const type = urlMapType[url as keyof typeof urlMapType];
  if (!type) {
    // 沒有定義對應格式不進行校驗
    return;
  }
  console.log(`==== 開始校驗 === url ${url}`);
  validateDataByType(type, data);
}
           

然後在 src/interceptTool.ts 檔案中引用

import { proxy } from 'ajax-hook';
import { validateDataByUrl } from './validate';

export function intercept() {
  // 擷取 XMLHttpRequest 發送的請求
  proxy({
    onResponse: (response, handler: any) => {
      validateDataByUrl(response.config.url, JSON.parse(response.response));
      handler.next(response);
    },
  });

  const { fetch: originalFetch } = window;
  // 擷取 fetch 發送的請求
  window.fetch = async (...args) => {
    const response = await originalFetch(...args);
    response.json().then((data: any) => {
      validateDataByUrl(args[0] as string, data);
      return data;
    });
    return response;
  };
}
           

現在可以在控制台看到接口資料校驗的接口辣~ ✿✿ヽ(°▽°)ノ✿

如何優雅地校驗後端接口資料,不做前端背鍋俠

總結下流程圖

如何優雅地校驗後端接口資料,不做前端背鍋俠

後續規劃

目前所做的事情,準确的說不是攔截,隻是擷取傳回資料,然後對比列印校驗結果,因為初步目标不涉及資料的處理。

後續會考慮對不合法的資料進行處理,比如應該傳回數組但是傳回了 null 的情況,如果能自動指派 [],就可以防止前端頁面崩潰的情況了。

原文連結:https://www.cnblogs.com/wenruo/p/17040398.html

繼續閱讀