likes
comments
collection
share

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

作者站长头像
站长
· 阅读数 49

jsonapi-check

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

前言

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

实现原理

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

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

使用示例

axios[Node]

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-method.ts 文件。

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

fetch[brower]

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

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 拦截器,将请求进行转发。

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)

转载自:https://juejin.cn/post/7274518244084514873
评论
请登录