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

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 小时前
Day02-JavaScript-Vue
前端·javascript·vue.js
前端李易安4 小时前
Web常见的攻击方式及防御方法
前端
萧鼎4 小时前
Python常见问题解答:从基础到进阶
开发语言·python·ajax
PythonFun4 小时前
Python技巧:如何避免数据输入类型错误
前端·python
知否技术4 小时前
为什么nodejs成为后端开发者的新宠?
前端·后端·node.js
hakesashou4 小时前
python交互式命令时如何清除
java·前端·python
天涯学馆4 小时前
Next.js与NextAuth:身份验证实践
前端·javascript·next.js
HEX9CF5 小时前
【CTF Web】Pikachu xss之href输出 Writeup(GET请求+反射型XSS+javascript:伪协议绕过)
开发语言·前端·javascript·安全·网络安全·ecmascript·xss
ConardLi5 小时前
Chrome:新的滚动捕捉事件助你实现更丝滑的动画效果!
前端·javascript·浏览器