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

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)

相关推荐
加班是不可能的,除非双倍日工资2 小时前
css预编译器实现星空背景图
前端·css·vue3
wyiyiyi2 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
gnip3 小时前
vite和webpack打包结构控制
前端·javascript
excel3 小时前
在二维 Canvas 中模拟三角形绕 X、Y 轴旋转
前端
阿华的代码王国3 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
一条上岸小咸鱼3 小时前
Kotlin 基本数据类型(三):Booleans、Characters
android·前端·kotlin
Jimmy3 小时前
AI 代理是什么,其有助于我们实现更智能编程
前端·后端·ai编程
ZXT4 小时前
promise & async await总结
前端
Jerry说前后端4 小时前
RecyclerView 性能优化:从原理到实践的深度优化方案
android·前端·性能优化
画个太阳作晴天4 小时前
A12预装app
linux·服务器·前端