New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More

@mest-fe/porters-middleware

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mest-fe/porters-middleware

供 [Porters](https://github.com/mest-io/porters) 项目使用的 Lambda 中间件,适用于 [Nitric](https://nitric.io/docs/installation) 环境。

0.4.0
latest
Version published
Weekly downloads
22
100%
Maintainers
2
Weekly downloads
 
Created

Porters Middleware

Porters 项目使用的 Lambda 中间件,适用于 Nitric 环境。

介绍

Schedule Middleware

标准化外部调用参数,将定时任务平台或手动调用提供的参数序列化后提供给 Lambda。在调用时,单个 Lambda 可能同时被并行调用多次, 每个函数内部请按当前序列号来决定需要处理的任务批次。

函数参数来自于 request body,序列化后可参考:

  • version: 当前调用版本,hash 字符串
  • current: 当前 Lambda 工作的位置,相对于并发数的序列号,从 1 开始,应当小于 concurrency
  • concurrency: 当前调用版本的并发数
  • ignoreRetry: 是否忽略重试
Auth Middleware

使用后 Lambda 需要验证 header 中 token 字符串是否合法,如果合法则继续调用,否则返回 401。

使用

在 Lambda 函数中嵌套使用中间件:

mainApi.post('/api', async ctx => {
  const handler = () => {
    // do something
  }
  await scheduleMiddleware(ctx, handler)
})

多个中间件请按参数调用嵌套:

const authHandler = next => scheduleMiddleware(next, handler)
await authMiddleware(ctx, authHandler)

错误处理

业务异常

业务中出现需要中断进程的错误,可及时捕获并返回错误信息。

const request = () => {
  throw new Error('something wrong')
} 
await scheduleMiddleware(ctx, () => {
  try {
    request()
  } catch (err) {
    return HTTP.badGateway(ctx, `${err.message}`)
  }
})
运行时的警告

多数场景中,Lambda 并不需要因为单个错误中断流程,可以将错误信息记录到日志,并继续执行。

const request = async () => {
  const result = await Promise.all([...])
  const errors = result.filter(item => item.status === 'rejected')
  
  // 大于一定数量的错误,直接抛出业务异常
  if (errors.length > 5) {
    throw new Error(errors.map(item => item.reason)
      .join('\n'))
  }
  // 允许范围内,统计警告并继续运行
  if (errors.length > 0) {
    errors.forEach(item => globalWarning.add(item.reason))
  }
}

FAQs

Package last updated on 24 Aug 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts