@8pattern/jmiddleware 中文文档教程

发布于 3年前 浏览 21 项目主页 更新于 3年前

jMiddleware

平台:节点/Web

像 Koa 或 Express 一样组织你的函数

如果你熟悉中间件框架对于 Koa 或 Express,Differences From Koa 可能更适合了解包。

Hello, jMiddleware

  import JMiddleware from '@8pattern/jmiddleware'
  const jMiddleware = new JMiddleware();
  jMiddleware.use(async (_, next) => {
    const start = Date.now();
    await next();
    console.log(Date.now() - start);
  });
  jMiddleware.startAsync();

Usage

  • Install
  npm i @8pattern/jmiddleware
  • Import
  import JMiddleware from '@8pattern/jmiddleware'
  • Instantiate
  const jMiddleware = new JMiddleware();
  • Register middlewares
  jMiddleware.use((_, next) => {
    const start = Date.now();
    next();
    console.log(Date.now() - start);
  });
  • Start
  jMiddleware.startSync();

APIs

Constructor

Context

类型:any

默认值:undefined

获取实例时可以定义任意类型的变量,不能在中间件中重新赋值。

  const Context = {};
  const jMiddleware = new JMiddleware(Context);
  jMiddleware.use((_, next, ctx) => {
    console.assert(ctx === Context);
    next();
  });
  jMiddleware.startSync();

没有必要。

  const jMiddleware = new JMiddleware();
  jMiddleware.use((_, next, ctx) => {
    console.assert(ctx === undefined);
    next();
  });
  jMiddleware.startSync();

Middleware

中间件将接收三个参数,也可以返回一个值。

Parameter: value

类型:未知

默认值:上次分配的值

如果中间件想要更改下一个的值,它可以将一个值传递给回调函数。

  jMiddleware.use((_, next) => {
    next(1);
  });
  jMiddleware.use<number>(v => {
    console.assert(v === 1);
  });
  jMiddleware.startSync();

如果没有收到来自前一个中间件的值,最后一个将生效。

  jMiddleware.use((_, next) => {
    next(1);
  });
  jMiddleware.use((v, next) => {
    console.assert(v === 1);
    next(); // not tranfer a value
  });
  jMiddleware.use<number>(v => {
    console.assert(v === 1);
  });
  jMiddleware.startSync();

Parameter: callback function

输入:(val?: any) => 未知

默认值:-

它将控制转移到下一个中​​间件。 它可以通过参数更改下一个中间件的值并接收下一个中间件的返回值。

  jMiddleware.use((_, next) => {
    const res = next(1);
    console.assert(res === 2)
  });
  jMiddleware.use<number>(v => {
    console.assert(v === 1);
    return 2;
  });
  jMiddleware.startSync();

Parameter: context

类型:any

默认值:undefined

在实例化时定义。

  const Context = {};
  const jMiddleware = new JMiddleware(Context);
  jMiddleware.use((_, next, ctx) => {
    console.assert(ctx === context);
    next();
  });
  jMiddleware.startSync();

Return

类型:any

默认值:undefined

任何中间件都可以返回一个值给前一个(对于第一个中间件,它的返回值将被视为最终结果)。

  jMiddleware.use((v, next) => {
    const val = `1-before ${v}`;
    const res = next(val);
    return `${res} 1-after`;
  });
  jMiddleware.use((v, next) => {
    const val = `2-before ${v}`;
    const res = next(val);
    return `${res} 2-after`;
  });
  const res = jMiddleware.startSync('0');
  console.log(res); // 2-before 1-before 0 2-after 1-after

Entry

在定义中间件时,包提供了两种方法来启动进程:startSyncstartAsync。 唯一的区别是 startAsync 将所有中间件视为异步方法,而 startSync 将中间件视为同步方法。

  jMiddleware.use((_, next) => next());
  console.assert(jMiddleware.startSync() === undefined);
  console.assert(jMiddleware.startAsync() instanceof Promise);

Differences From Koa

该包的灵感来自 Koa,但它不是为 Web 应用程序设计的,这造成了一些差异。

Parameters

在 Koa 中,中间件接收两个参数:上下文和回调函数。 而上下文参数是一个适合网络应用程序的复杂对象。 但是在这个包中,中间件有三个参数。

第一个参数是一个变量,可以赋给任何类型。

  // Koa
  app.use(ctx => {
    ctx.body = 'Hello Koa';
  });

  // jMiddleware
  jMiddleware.use(val => {
    console.log(val); // 'any value'
  });
  jMiddleware.startAsync('any value');

第二个参数是一个回调函数,可以将值传递给下一个中间件。

  // Koa
  app.use(async (ctx, next) => {
    await next();
  });

  // jMiddleware
  jMiddleware.use(async (val, next) => {
    await next('any value from prev middleware')
  });
  jMiddleware.use(val => {
    console.log(val); // 'any value from prev middleware'
  });
  jMiddleware.startAsync();

由于该包旨在以中间件的方式组织功能,因此我们使其参数更加灵活。 如果你熟悉 Koa 的方式,你可以指定一个对象作为初始值。

  // jMiddleware
  jMiddleware.use(val => {
    val.body = 'Hello';
  });
  jMiddleware.startAsync({});

第三个参数是一个变量,只能在实例化时赋值。

  // jMiddleware
  const jMiddleware = new JMiddleware('any value');
  jMiddleware.use((_, next, ctx) => {
    console.log(ctx); // any value;
  });
  jMiddleware.startAsync();

Async or Sync

在 Koa 中,中间件被设计为异步方法。 但是在包中,异步和同步方法都是允许的。 除了一些更适合使用同步方式的场景,使用同步方式也可以避免使用async/await关键字。 开关是您启动中间件的方式。

  // Async
  jMiddleware.use(async (_, next) => {
    await next();
  }); 
  jMiddleware.startAsync();

  // Sync
  jMiddleware.use((_, next) => {
    next();
  }); 
  jMiddleware.startSync();

Return

Koa 不需要返回值,在这个包中是允许的。 规则是任何中间件都会返回一个值给它的前一个中间件(对于第一个中间件,它的返回值将被视为最终结果)。

  jMiddleware.use((v, next) => {
    const val = `1-before ${v}`;
    const res = next(val);
    return `${res} 1-after`;
  });
  jMiddleware.use((v, next) => {
    const val = `2-before ${v}`;
    const res = next(val);
    return `${res} 2-after`;
  });
  const res = jMiddleware.startSync('0');
  console.log(res); // 2-before 1-before 0 2-after 1-after

jMiddleware

Platform: Node/Web

Organize your functions just like Koa or Express

If you are familar with the middleware framework of Koa or Express, Differences From Koa may be more suitable to acquaint the package.

Hello, jMiddleware

  import JMiddleware from '@8pattern/jmiddleware'
  const jMiddleware = new JMiddleware();
  jMiddleware.use(async (_, next) => {
    const start = Date.now();
    await next();
    console.log(Date.now() - start);
  });
  jMiddleware.startAsync();

Usage

  • Install
  npm i @8pattern/jmiddleware
  • Import
  import JMiddleware from '@8pattern/jmiddleware'
  • Instantiate
  const jMiddleware = new JMiddleware();
  • Register middlewares
  jMiddleware.use((_, next) => {
    const start = Date.now();
    next();
    console.log(Date.now() - start);
  });
  • Start
  jMiddleware.startSync();

APIs

Constructor

Context

Type: any

Default: undefined

A variable with any types can be defined when getting the instance, which can't be re-asigned in middlewares.

  const Context = {};
  const jMiddleware = new JMiddleware(Context);
  jMiddleware.use((_, next, ctx) => {
    console.assert(ctx === Context);
    next();
  });
  jMiddleware.startSync();

It is not necessary.

  const jMiddleware = new JMiddleware();
  jMiddleware.use((_, next, ctx) => {
    console.assert(ctx === undefined);
    next();
  });
  jMiddleware.startSync();

Middleware

Middlewares will receive three parameters and also can return a value.

Parameter: value

Type: unknown

Default: last asigned value

If a middleware want to change the value of the next one, it can tranfer a value to the callback function.

  jMiddleware.use((_, next) => {
    next(1);
  });
  jMiddleware.use<number>(v => {
    console.assert(v === 1);
  });
  jMiddleware.startSync();

If not receiving a value from the previous middleware, the last one will make effect.

  jMiddleware.use((_, next) => {
    next(1);
  });
  jMiddleware.use((v, next) => {
    console.assert(v === 1);
    next(); // not tranfer a value
  });
  jMiddleware.use<number>(v => {
    console.assert(v === 1);
  });
  jMiddleware.startSync();

Parameter: callback function

Type: (val?: any) => unknown

Default: -

It will transfer control to the next middleware. It can change the value of the next middleware by the argument and receiving the return from the next middleware.

  jMiddleware.use((_, next) => {
    const res = next(1);
    console.assert(res === 2)
  });
  jMiddleware.use<number>(v => {
    console.assert(v === 1);
    return 2;
  });
  jMiddleware.startSync();

Parameter: context

Type: any

Default: undefined

It is defined when instantiation.

  const Context = {};
  const jMiddleware = new JMiddleware(Context);
  jMiddleware.use((_, next, ctx) => {
    console.assert(ctx === context);
    next();
  });
  jMiddleware.startSync();

Return

Type: any

Default: undefined

Any middlewares are able to return a value to the previous one (for the first middleware, its return value will be regarded as the final result).

  jMiddleware.use((v, next) => {
    const val = `1-before ${v}`;
    const res = next(val);
    return `${res} 1-after`;
  });
  jMiddleware.use((v, next) => {
    const val = `2-before ${v}`;
    const res = next(val);
    return `${res} 2-after`;
  });
  const res = jMiddleware.startSync('0');
  console.log(res); // 2-before 1-before 0 2-after 1-after

Entry

When defining the middlewares, the package provides two methods to start the process: startSync and startAsync. The only difference is the startAsync regards all middlewares as asynchronous methods but startSync regards middlewares as synchronous methods.

  jMiddleware.use((_, next) => next());
  console.assert(jMiddleware.startSync() === undefined);
  console.assert(jMiddleware.startAsync() instanceof Promise);

Differences From Koa

The package is inspired by Koa, but it isn't designed for web applications, which accounts for some diferences.

Parameters

In Koa, middlewares receive two parameters: a context and a callback function. And the context parameter is a complex object to fit web applications. But in this package, middlewares have three parameters.

The first parameter is a variable can be asigned with any types.

  // Koa
  app.use(ctx => {
    ctx.body = 'Hello Koa';
  });

  // jMiddleware
  jMiddleware.use(val => {
    console.log(val); // 'any value'
  });
  jMiddleware.startAsync('any value');

The second parameter is a callback function which can transfer the value to the next middleware.

  // Koa
  app.use(async (ctx, next) => {
    await next();
  });

  // jMiddleware
  jMiddleware.use(async (val, next) => {
    await next('any value from prev middleware')
  });
  jMiddleware.use(val => {
    console.log(val); // 'any value from prev middleware'
  });
  jMiddleware.startAsync();

Since the package aims to organize functions in a way of middlewares, we make its parameters more flexiable. If you are familar with the way of Koa, you can asign a object as the initial value.

  // jMiddleware
  jMiddleware.use(val => {
    val.body = 'Hello';
  });
  jMiddleware.startAsync({});

The third parameter is a varaible which only can be assigned when instantiation.

  // jMiddleware
  const jMiddleware = new JMiddleware('any value');
  jMiddleware.use((_, next, ctx) => {
    console.log(ctx); // any value;
  });
  jMiddleware.startAsync();

Async or Sync

In Koa,middlewares are designed as asynchronous methods. But in the package, asynchronous and synchronous methods are both allowed. Besides some scenarios where synchronous methods are more suitable, async / await keywords can be avoided when using synchronous methods. The switch are how you start the middlewares.

  // Async
  jMiddleware.use(async (_, next) => {
    await next();
  }); 
  jMiddleware.startAsync();

  // Sync
  jMiddleware.use((_, next) => {
    next();
  }); 
  jMiddleware.startSync();

Return

Koa doesn't need return values, which are allowed in this package. The rule is any middleware will return a value to its previous middleware (for the first middleware, its return value will be regarded as the final result).

  jMiddleware.use((v, next) => {
    const val = `1-before ${v}`;
    const res = next(val);
    return `${res} 1-after`;
  });
  jMiddleware.use((v, next) => {
    const val = `2-before ${v}`;
    const res = next(val);
    return `${res} 2-after`;
  });
  const res = jMiddleware.startSync('0');
  console.log(res); // 2-before 1-before 0 2-after 1-after
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文