You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

asop

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

asop

middleware framework for node.js

0.0.4
latest
Source
npmnpm
Version published
Maintainers
1
Created
Source

asop

npm npm

Asop 是为了适应 非 web 开发而 fork 自 Koa 项目而实现的。

Asop 是一个十分具有表现力的中间件框架,力求让应用开发和 API 使用更加地愉快。Asop 的中间件之间按照编码顺序在栈内依次执行,允许您执行操作并向下传递请求(downstream),之后过滤并逆序返回响应(upstream)。

Asop 没有捆绑任何中间件,也不依赖第三方包,实现代码不超过120行,可以运行在 Node.js环境 和 浏览器端。

下面例子均以 Node.js 环境为准。

安装

  • 在 Node.js 环境下,Asop 依赖 node v7.6.0 或 ES2015及更高版本和 async 方法支持;
  • 在浏览器端则需要通过其它工具转码 async 函数,或者使用 Promise
$ npm install asop

CDN

<script src="https://cdn.jsdelivr.net/npm/asop@0.0.2/dist/asop.umd.js"></script>

Hello Asop

const Asop = require('asop');
const app = new Asop();

// 使用一个普通函数作为中间件
app.use((ctx, next) => {
  ctx.hello = 'hello';
  return next();
});

// 使用 async 函数作中间件
app.use(async (ctx, next) => {
  ctx.hello += ' world!';
  await next();
});

const handle = app.callback();
const done = (ctx) => {
  console.log(ctx.hello);
};

handle(done);
// => 'hello world!'

中间件

Asop 是一个中间件框架,可以采用两种不同的方法来实现中间件:

  • asymc function
  • common function

以下是使用两种不同方法实现一个日志中间件的示例:

async function (node v7.6+)

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`Take ${ms}ms`);
});

Common function

// 中间件通常带有两个参数 (ctx, next), ctx 是一个请求的上下文(context),
// next 是调用执行下游中间件的函数. 在代码执行完成后通过 then 方法返回一个 Promise.

app.use((ctx, next) => {
  const start = Date.now();
  return next().then(() => {
    const ms = Date.now() - start;
    console.log(`Take ${ms}ms`);
  });
});

上下文

每个中间件都接收一个纯对象 Object,该对象初始化状态仅仅包含了 Asop 实例的下面两个简单配置为属性。 ctx 通常用作上下文对象的参数名称。

  • env - 运行环境,默认值为 process.env.NODE_ENV || 'development';
  • silent - 静默模式。
app.use(async (ctx, next) => {
  await next();
});

Asop 应用程序

在执行 new Asop() 时创建的对象被称为 Asop 应用对象。

应用对象是不带有任何服务的 Asop 接口,它可以处理中间件的注册,通过 callback 将执行中间件,进行默认错误处理,以及对上下文对象进行配置。

了解有关应用程序对象的更多信息请到 应用 API 参考.

运行测试

$ npm test

Keywords

middleware

FAQs

Package last updated on 11 Apr 2018

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