@sumor/api-middleware

api-middleware

一个 Sumor Cloud 工具。
更多文档 API Middleware 是一个用于 Node.JS 的中间件。 它可以轻松将函数暴露给 API,并验证参数。

CI Test Coverage Audit

安装

npm i @sumor/api-middleware --save

先决条件

Node.JS 版本

需要 Node.JS 版本 16.x 或更高

需要 Node.JS ES 模块

由于这个包是用 ES 模块编写的, 请在您的 package.json 文件中更改以下代码:

{
  "type": "module"
}

用法

基本用法

1. 在您的项目文件夹 api 中添加一个名为 plus.js 的文件
export default async (context, req, res) => {
  const { data } = context
  const { a, b } = data
  return a + b
}
[可选] 2. 在您的项目文件夹 api 中添加一个名为 plus.json 的文件
{
  "name": "plus",
  "parameters": {
    "a": {
      "name": "参数 a",
      "type": "number",
      "length": 3
    },
    "b": {
      "name": "参数 b",
      "type": "number"
    }
  }
}
3. 在您的 index.js 文件中添加以下代码
import express from 'express'
import apiMiddleware from '@sumor/api-middleware'

const app = express()
apiMiddleware(app, process.cwd() + '/api')

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000')
})
4. 运行 index.js
node index.js

上下文

data

它包含请求中传递的所有参数

文件上传将被解析为以下对象:

exposeApis

它包含所有暴露的 API