Détail du package

@eggjs/tegg-controller-plugin

eggjs1.7k3.57.9

controller decorator for egg

egg, plugin, typescript, module

readme

@eggjs/tegg-controller-plugin

使用注解的方式来开发 egg 中的 Controller

Install

# tegg 注解
npm i --save @eggjs/tegg
# tegg 插件
npm i --save @eggjs/tegg-plugin
# tegg controller 插件
npm i --save @eggjs/tegg-controller-plugin

Prepare

// tsconfig.json
{
  "extends": "@eggjs/tsconfig"
}

Config

// config/plugin.js
exports.tegg = {
  package: '@eggjs/tegg-plugin',
  enable: true,
};

exports.teggController = {
  package: '@eggjs/tegg-controller-plugin',
  enable: true,
};

Usage

Middleware

Middleware 支持多个入参,依次传入要生效的中间件 中间件注解,可以添加在类/方法上。添加在类上时,对类上所有方法生效,添加在方法上时,只对当前方法生效。

// app/middleware/global_log.ts
import { Context } from 'egg';
import type { Next } from '@eggjs/controller-decorator';

export default async function globalLog(ctx: Context, next: Next) {
  ctx.logger.info('have a request');
  return next();
}

export default async function globalLog2(ctx: Context, next: Next) {
  ctx.logger.info('have a request2');
  return next();
}

// app/controller/FooController.ts
import { Middleware } from '@eggjs/tegg';
@Middleware(globalLog,globalLog2)
export class FooController {
  @Middleware(methodCount)

  async hello() {
  }
}

Context

当需要 egg context 时,可以使用 @Context 注解来声明。

// app/controller/FooController.ts
import { Context, EggContext } from '@eggjs/tegg';

export class FooController {
  @Middleware(methodCount)
  async hello(@Context() ctx: EggContext) {
  }
}

HTTP 注解

HTTPController/HTTPMethod

@HTTPController 注解用来声明当前类是一个 HTTP controller,可以配置路径前缀。 @HTTPMethod 注解用来声明当前方法是一个 HTTP method,只有带了这个注解,HTTP 方法才会被暴露出去,可以配置方法路径,

// app/controller/FooController.ts
import { Context, EggContext, HTTPController, HTTPMethod, HTTPMethodEnum } from '@eggjs/tegg';

@HTTPController({
  path: '/foo',
})
export class FooController {
  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/hello',
  })
  async hello() {
  }
}

Param

HTTP 协议中有各种各样的传参方式,比如 query,path,body 等等。

HTTPBody

接收 body 参数

// app/controller/FooController.ts
import { Context, EggContext, HTTPController, HTTPMethod, HTTPMethodEnum, HTTPBody } from '@eggjs/tegg';

@HTTPController({
  path: '/foo',
})
export class FooController {
  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/hello',
  })
  async hello(@HTTPBody() name: string) {
    return `hello, ${name}`;
  }
}
HTTPQuery/HTTPQueries

两者的区别在于参数是否为数组, HTTPQuery 只会取第一个参数,HTTPQueries 只提供数组形式。 HTTPQuery 的参数类型只能是 string, HTTPQueries 的参数类型只能是 string[]。

// app/controller/FooController.ts
import { Context, EggContext, HTTPController, HTTPMethod, HTTPMethodEnum, HTTPQuery, HTTPQueries } from '@eggjs/tegg';

@HTTPController({
  path: '/foo',
})
export class FooController {
  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/hello',
  })
  async hello(
    // /foo/hello?name=bar
    // HTTPQuery: name=bar
    // HTTPQueries: name=[bar]
    @HTTPQuery() name: string,
    @HTTPQueries() names: string[],
  ) {
    return `hello, ${name}`;
  }
}

如果需要使用别名,比如说 query 中的 name 不能在 js 中声明时,如 foo[bar] 这类的。可以通过以下形式

@HTTPQuery({ name: 'foo[bar]' }) fooBar: string,
HTTPParam

接收 path 中的参数,类型只能为 string

// app/controller/FooController.ts
import { Context, EggContext, HTTPController, HTTPMethod, HTTPMethodEnum, HTTPBody } from '@eggjs/tegg';

@HTTPController({
  path: '/foo',
})
export class FooController {
  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/:id',
  })
  async hello(@HTTPParam() id: string) {
    return `hello, ${name}`;
  }
}

如果需要使用别名,比如说 path 中使用正则声明 /foo/(.*), 可以通过以下形式

// 具体 name 值可以查看 path-to-regexp
@HTTPParam({ name: '0' }) id: string

Host

Host 注解,用于指定 HTTP 方法仅在 host 匹配时执行。 可以添加在类/方法上。添加在类上时,对类上所有方法生效,添加在方法上时,只对当前方法生效。方法上的注解可以覆盖类上的注解

// app/controller/FooController.ts
import { Host } from '@eggjs/tegg';
@Host('foo.eggjs.com')
export class FooController {
  // 仅能通过 foo.eggjs.com 访问
  async hello() {
  }

  // 仅能通过 bar.eggjs.com 访问
  @Host('bar.eggjs.com')
  async bar() {
  }
}

MCP 注解

MCPController/MCPPrompt/MCPTool/MCPResource

@MCPController 注解用来声明当前类是一个 MCP controller。 通过使用装饰器 @MCPPrompt @MCPTool @MCPResource 来声明对应的 MCP 类型。 使用 @ToolArgsSchema @PromptArgsSchema @Extra 来 schema 和 extra。

import {
  MCPController,
  PromptArgs,
  ToolArgs,
  MCPPromptResponse,
  MCPToolResponse,
  MCPResourceResponse,
  MCPPrompt,
  MCPTool,
  MCPResource,
  PromptArgsSchema,
  Logger,
  Inject,
  ToolArgsSchema,
} from '@eggjs/tegg';
import z from 'zod';

export const PromptType = {
  name: z.string(),
};

export const ToolType = {
  name: z.string({
    description: 'npm package name',
  }),
};


@MCPController()
export class McpController {

  @Inject()
  logger: Logger;

  @MCPPrompt()
  async foo(@PromptArgsSchema(PromptType) args: PromptArgs<typeof PromptType>): Promise<MCPPromptResponse> {
    this.logger.info('hello world');
    return {
      messages: [
        {
          role: 'user',
          content: {
            type: 'text',
            text: `Generate a concise but descriptive commit message for these changes:\n\n${args.name}`,
          },
        },
      ],
    };
  }

  @MCPTool()
  async bar(@ToolArgsSchema(ToolType) args: ToolArgs<typeof ToolType>): Promise<MCPToolResponse> {
    return {
      content: [
        {
          type: 'text',
          text: `npm package: ${args.name} not found`,
        },
      ],
    };
  }


  @MCPResource({
    template: [
      'mcp://npm/{name}{?version}',
      {
        list: () => {
          return {
            resources: [
              { name: 'egg', uri: 'mcp://npm/egg?version=4.10.0' },
              { name: 'mcp', uri: 'mcp://npm/mcp?version=0.10.0' },
            ],
          };
        },
      },
    ],
  })
  async car(uri: URL): Promise<MCPResourceResponse> {
    return {
      contents: [{
        uri: uri.toString(),
        text: 'MOCK TEXT',
      }],
    };
  }
}

MCP 地址

MCP controller 完整的实现了 SSE / streamable HTTP / streamable stateless HTTP 三种模式,默认情况下,他们的路径分别是 /mcp/init /mcp/stream /mcp/stateless/stream, 你可以根据你所需要的场景,灵活使用对应的接口。

// config.{env}.ts
import { randomUUID } from 'node:crypto';

export default () => {

  const config = {
    mcp: {
      sseInitPath: '/mcp/init', // SSE path
      sseMessagePath: '/mcp/message', // SSE message path
      streamPath: '/mcp/stream', // streamable path
      statelessStreamPath: '/mcp/stateless/stream', // stateless streamable path
      sessionIdGenerator: randomUUID, 
    },
  };

  return config;
};

changelog

Change Log

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

3.57.9 (2025-05-29)

Note: Version bump only for package tegg

3.57.8 (2025-05-29)

Note: Version bump only for package tegg

3.57.7 (2025-05-28)

Bug Fixes

  • the loading order issue in multi-module mode (#324) (c9610bd)

3.57.6 (2025-05-27)

Bug Fixes

3.57.5 (2025-05-15)

Bug Fixes

3.57.4 (2025-05-14)

Note: Version bump only for package tegg

3.57.3 (2025-05-13)

Bug Fixes

3.57.2 (2025-05-13)

Bug Fixes

3.57.1 (2025-05-13)

Bug Fixes

3.57.0 (2025-05-09)

Features

  • preserve SQL hint in minify function (#314) (145bcf3)

3.56.3 (2025-05-07)

Bug Fixes

3.56.2 (2025-05-01)

Bug Fixes

3.56.1 (2025-04-29)

Bug Fixes

3.56.0 (2025-04-29)

Features

3.55.0 (2025-04-29)

Features

3.54.0 (2025-04-29)

Features

3.53.0 (2025-04-21)

Bug Fixes

Features

  • add timeout metadata for http controller (#301) (68980c2)

3.52.1 (2025-03-14)

Bug Fixes

3.52.0 (2024-12-30)

Features

3.51.2 (2024-12-09)

Features

3.51.1 (2024-11-06)

Bug Fixes

3.51.0 (2024-10-30)

Features

3.50.1 (2024-10-23)

Bug Fixes

3.50.0 (2024-10-22)

Features

3.49.0 (2024-10-21)

Features

3.48.1 (2024-10-14)

Bug Fixes

3.48.0 (2024-10-10)

Features

3.47.2 (2024-10-10)

Note: Version bump only for package tegg

3.47.1 (2024-10-10)

Bug Fixes

3.47.0 (2024-10-10)

Features

3.46.4 (2024-10-09)

Note: Version bump only for package tegg

3.46.3 (2024-10-08)

Bug Fixes

3.46.2 (2024-10-07)

Note: Version bump only for package tegg

3.46.1 (2024-09-30)

Bug Fixes

  • fix miss MultiInstance proper qualifiers (#241) (15666d3)

3.46.0 (2024-09-29)

Features

  • impl MultiInstance inject MultiInstance (#240) (08e3b0c)

3.45.0 (2024-09-29)

Features

3.44.1 (2024-09-29)

Bug Fixes

3.44.0 (2024-09-29)

Features

3.43.2 (2024-09-14)

Bug Fixes

3.43.1 (2024-09-14)

Note: Version bump only for package tegg

3.43.0 (2024-09-13)

Features

3.42.0 (2024-09-10)

Features

3.41.0 (2024-08-26)

Features

  • export controller info util for get aop middleware (#233) (1d3cca8)

3.40.1 (2024-08-23)

Bug Fixes

3.40.0 (2024-08-22)

Features

3.39.5 (2024-08-09)

Bug Fixes

  • generate index name with column name (#230) (82ec72d)

3.39.4 (2024-07-09)

Bug Fixes

3.39.3 (2024-04-28)

Bug Fixes

  • mount clazzExtension/clazzExtension/tableSql to BaseDao (#220) (ac322cf)

3.39.2 (2024-04-28)

Bug Fixes

3.39.1 (2024-04-28)

Bug Fixes

3.39.0 (2024-04-19)

Bug Fixes

Features

  • use app.loader.getTypeFiles to generate module config file names (#213) (e0656a4)

3.38.0 (2024-04-18)

Features

3.37.3 (2024-04-17)

Bug Fixes

3.37.2 (2024-04-17)

Bug Fixes

  • always get extension from Module._extensions (#211) (62e9c06)

3.37.1 (2024-04-16)

Bug Fixes

3.37.0 (2024-04-16)

Bug Fixes

Features

3.36.3 (2024-04-10)

Bug Fixes

3.36.2 (2024-04-08)

Bug Fixes

3.36.1 (2024-04-07)

Bug Fixes

  • use @eggjs/ajv-keywords and @eggjs/ajv-formats (#204) (31b02a0)

3.36.0 (2024-04-02)

Features

3.35.1 (2024-03-26)

Bug Fixes

3.35.0 (2024-03-26)

Features

  • dal-runtime templates support pkg alias (#198) (cecef78)

3.34.0 (2024-03-22)

Features

3.33.1 (2024-03-22)

Bug Fixes

3.33.0 (2024-03-22)

Bug Fixes

Features

3.32.0 (2024-02-19)

Bug Fixes

Features

  • set plugin module optional false if be enabled as a plugin (#190) (57a1adc)

3.31.0 (2024-01-31)

Features

  • add getEggObjects API to fetch all instances (#189) (f8592c2)

3.30.1 (2024-01-25)

Bug Fixes

  • fix modify ctx.args in aop beforeCall not work (#187) (7656424)

3.30.0 (2024-01-17)

Bug Fixes

  • config for env is not merged when default config is empty (#178) (9c1de22)

Features

  • scan framework dependencies as optional module (#184) (a4908c6)

3.29.0 (2023-12-26)

Features

  • allow a handler to subscribe to multiple events (#179) (1d460a5)

3.28.2 (2023-12-12)

Bug Fixes

3.28.1 (2023-12-11)

Note: Version bump only for package tegg

3.28.0 (2023-12-10)

Features

  • inject moduleConfig read from tegg-config app.moduleConfigs config (#169) (2d984ef)

3.27.0 (2023-11-23)

Features

3.26.0 (2023-11-17)

Features

3.25.2 (2023-11-06)

Bug Fixes

  • verify isEggMultiInstancePrototype before proto exists (#164) (db9a621)

3.25.1 (2023-11-03)

Bug Fixes

3.25.0 (2023-11-03)

Features

3.24.0 (2023-10-26)

Features

  • support Request decorators for HTTPController (#159) (945e1eb)

3.23.0 (2023-09-20)

Bug Fixes

Features

  • add className property to EggPrototypeInfo (#158) (bddac97)

3.20.0 (2023-09-07)

Features

3.19.0 (2023-08-31)

Features

  • add LoadUnitMultiInstanceProtoHook for tegg plugin (#150) (b938580)

3.18.1 (2023-08-29)

Bug Fixes

  • fix use MultiInstanceProto from other modules (#147) (b71af60)

3.18.0 (2023-08-29)

Features

  • add aop runtime/dynamic inject runtime for standalone (#149) (6091fc6)
  • add helper to get EggObject from class (#148) (77eaf38)

3.17.0 (2023-08-24)

Features

3.16.0 (2023-08-24)

Features

3.14.3 (2023-08-14)

Bug Fixes

3.14.2 (2023-08-14)

Bug Fixes

  • init all context advice if root proto miss (#139) (0602ea8)

3.14.1 (2023-08-11)

Bug Fixes

  • ensure ContextInitiator be called after ctx ready (#138) (79e16da)

3.14.0 (2023-07-31)

Features

3.13.0 (2023-07-25)

Features

3.12.0 (2023-07-13)

Bug Fixes

  • after call mockModuleContext, hasMockModuleContext should be true (#134) (88b3caa)

3.11.1 (2023-06-29)

Bug Fixes

3.11.0 (2023-06-29)

Features

  • export transaction decorator from tegg (8be0521)
  • impl transaction decorator (#124) (4896615)

3.10.0 (2023-06-28)

Bug Fixes

Features

3.9.0 (2023-06-20)

Features

  • implement advice params (76ec8ad)

3.8.0 (2023-05-30)

Features

  • impl EggObjectLifecycle hook in decorator (#119) (cced8a2)

3.7.0 (2023-04-03)

Bug Fixes

Features

  • The exposed module reads the options. (#112) (a52b44b)

3.6.3 (2023-03-02)

Bug Fixes

  • fix contextEggObjectGetProperty conflict (#105) (c570315)

3.6.2 (2023-02-16)

Bug Fixes

3.6.1 (2023-02-14)

Bug Fixes

  • get app/ctx properties when load unit beforeCreate (#102) (76ef679)

3.6.0 (2023-02-13)

Bug Fixes

  • egg qualifier should register after all file loaded (#100) (5033b51)

Features

3.5.2 (2023-02-10)

Bug Fixes

3.5.1 (2023-02-10)

Bug Fixes

  • remove useless init singleton proto (#96) (097ac58)

3.5.0 (2023-02-10)

Bug Fixes

Features

  • append call stack for runInBackground (#91) (ec7bc2c)
  • remove context egg object factory (#93) (e14bdb2)
  • use SingletonProto for egg ctx object (#92) (3385d57)

3.4.1 (2023-02-02)

Bug Fixes

  • BackgroundTaskHelper should support recursively call (#90) (368ac03)

3.4.0 (2023-02-01)

Features

  • use singleton model insteadof context (#89) (cfdfc05)

3.3.4 (2023-01-29)

Bug Fixes

  • should not notify backgroundTaskHelper if teggContext not exists (#88) (4cab68b)

3.3.3 (2023-01-29)

Bug Fixes

  • wait egg background task done before destroy tegg ctx (#87) (deea4d8)

3.3.2 (2023-01-29)

Bug Fixes

  • beginModuleScope should be reentrant (#86) (648aeaf)

3.3.1 (2023-01-28)

Bug Fixes

  • inject property should be configurable (#85) (c13ab55)

3.3.0 (2023-01-28)

Bug Fixes

Features

3.2.3 (2023-01-16)

Bug Fixes

  • cork/uncork should can be called multi times in same ctx (#78) (269cda6)

3.2.2 (2023-01-06)

Note: Version bump only for package tegg

3.2.1 (2022-12-28)

Bug Fixes

  • fix nest inject ctx obj to singleton obj (#74) (e4b6252)

3.2.0 (2022-12-28)

Features

3.1.0 (2022-12-27)

Bug Fixes

  • add 'globby' as dependencies (#71) (76d85d9)
  • eventbus runtime should wait all handlers done (#51) (0651d30)
  • fix events type from any to keyof Events (#54) (a2551b2)
  • fix file path for advice decorator (#64) (d6aa091)
  • fix miss agent file (0fa496b)
  • fix miss agent file (#56) (cfb4dcc)
  • fix mock prototype in aop not work (#66) (16640eb)
  • fix rootProtoManager.registerRootProto (f416ed7)
  • fix schedule import (1fb5481)
  • inject context proto to singleton proto (#72) (fcc0b2b)
  • none exist node_modules path (#59) (77cb068)
  • optimize backgroud output (#47) (6d978c5)
  • skip file not exits (#62) (10e56d4)
  • use getMetaData for ModelMetadataUtil (#44) (87a306c)
  • use require.resolve instead path.join to resolve dependencies path (#63) (d7f3beb)

Features

3.0.0 (2022-12-26)

Features

  • delete controller root hook (bbb68f4)

3.0.0-alpha.0 (2022-12-22)

Bug Fixes

  • eventbus runtime should wait all handlers done (#51) (0651d30)
  • fix events type from any to keyof Events (#54) (a2551b2)
  • fix file path for advice decorator (#64) (d6aa091)
  • fix miss agent file (0fa496b)
  • fix miss agent file (#56) (cfb4dcc)
  • fix mock prototype in aop not work (#66) (16640eb)
  • fix rootProtoManager.registerRootProto (f416ed7)
  • fix schedule import (1fb5481)
  • none exist node_modules path (#59) (77cb068)
  • optimize backgroud output (#47) (6d978c5)
  • skip file not exits (#62) (10e56d4)
  • use getMetaData for ModelMetadataUtil (#44) (87a306c)
  • use require.resolve instead path.join to resolve dependencies path (#63) (d7f3beb)

Features

1.3.0 (2022-07-01)

Features

0.2.0 (2022-01-20)

Bug Fixes

Features