如何更智能更优雅地检验后端接口

jsonapi-check

前言

接口联调是前后端分离后的必争之地。清楚记得当初工作第一个单子就是该原因,个人消息列表页中判定消息是否已读状态的字段,后端修改后未及时沟通,周六项目上线,周一上班时就来了个单子。字段擅自修改导致问题有时比较隐蔽难发现,所以做了个可以方便使用并迅速发现字段修改,减少 battle 的包。

实现原理

使用 axios 发送请求方式时,使用拦截器对请求的接口进行拦截,获取请求的路径,方式和返回的数据,自动生成对应的 Type 文件,下次请求时,将返回的数据进行检验,如有错误提示出来。

注意:一定在 DEV 模式下使用!

使用示例

axios[Node]

js 复制代码
const axios = require('axios')
const { jsonapiCheck } = require('jsonapi-check')

axios.interceptors.response.use((response) => {
  const { request, data } = response
  const { path, method } = request
  const options = {
    schemaDir: 'schema',
    hasSubdirs: false
  }

  // dev-mode check
  jsonapiCheck(path, method, data, options)
  return response
})

通过请求的路径,方式,和返回的数据自动在当前目录下生成 schema/path-mwthod.ts 文件。

详情请跳转完整示例 example/node

fetch[brower]

由于该包需要在 Node 环境下进行使用,所以浏览器的环境需加一个中间服务器来接收浏览器发送的请求。

js 复制代码
const { jsonapiCheck } = require('jsonapi-check')
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
app.use(cors())

app.use(bodyParser.json({ type: 'text/plain' }))

app.all('*', (req, res) => {
  const { path, headers, body } = req
  const { 'x-http-method-override': method } = headers
  const errors = jsonapiCheck(path, method, body)
  res.send(JSON.stringify(errors, null, 2))
})

app.listen(5050, () => {
  console.log('listening on port 5050')
})

浏览器端使用 fetch 拦截器,将请求进行转发。

js 复制代码
const { fetch: rawFetch } = window

window.fetch = async (...args) => {
  const response = await rawFetch(...args)
  response.json().then(data => {
    const headers = { 'X-HTTP-Method-Override': getMethod(args[1] || {}).toUpperCase() }
    rawFetch(changeURLPORT(args[0]), { method: "POST", headers, body: JSON.stringify(data)})
    .then(res => res.json())
    .then(res => printErrorLog(res))
  })
  return response
}

// 替换路径
function changeURLPORT(url){
  return url.replace(3000, 5050)
}

// 转发接口时,数据传递需要使用 post,所以将原有请求方式使用 headers 进行传递
function getMethod(options){
  const { method, headers = {} } = options
  const { 'x-http-method-override': httpMethodOverride } = headers

  return method || httpMethodOverride || 'GET'
}

// 在浏览器控制台输出报错信息
function printErrorLog({ filePath, errors }) {
  if(errors.length === 0) return
  
  let errorLog = ''
  errorLog += `FAIL ${filePath}\n`
  errors.forEach((error) => {
    const { lines, property, message } = error
    errorLog += property ? `  ${property}: ${message}\n` : `  ${message}\n`
    lines.forEach((line) => {
      errorLog += `    ${line}\n`
    })
  })
  console.error(errorLog)
}

详情请跳转完整示例 example/brower

Options 第四个参数对象

schemaDir

  • Type: string

  • Default: schema

控制生成的文件夹名字。

hasSubdirs

  • Type: boolean

  • Default: false

控制生成的文件夹是否有子文件夹。

  • GET /authors --> schema/authors/authors-GET.ts --> interface Author

  • GET /web/.../authors --> schema/web/author-GET.ts --> interface Author

✨ Happy hacking!

欢迎使用,点赞和评论 Efrice/jsonapi-check: Easy to check type for json api response. (github.com)

相关推荐
万少1 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站3 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名6 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫6 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊6 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter6 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折6 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_6 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial6 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu7 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端