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

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)

相关推荐
IT_陈寒几秒前
Redis 性能翻倍的 7 个冷门技巧,第 5 个大多数人都不知道!
前端·人工智能·后端
mCell7 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip7 小时前
Node.js 子进程:child_process
前端·javascript
excel10 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel11 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼13 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping13 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙14 小时前
[译] Composition in CSS
前端·css
白水清风14 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
算家计算14 小时前
7B参数拿下30个世界第一!Hunyuan-MT-7B本地部署教程:腾讯混元开源业界首个翻译集成模型
人工智能·开源