npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@youngjs/core

v2.0.1

Published

基于koa封装的typescript的nodejs后端高效框架,更多请访问youngjs.top

Readme

@youngjs/core

基于 koa、使用 typescript 的约定式 MVC 后端框架,专注高效开发 nodejs 接口

Image text

  • 完整文档与示例:Youngjs
  • 快速开始脚手架:npm create youngjs-app@latest my-app

特性

  • 约定式目录结构:module/(服务)、entity/(typeorm 实体)、comm/(通用类)、queue/(队列)、socket/、middleware/、esindex/ 按目录自动加载,零配置起步
  • 类型原生推断,无代码生成:实体/服务访问一律使用类引用(getRepository(EntityClass)、new Service(ctx)、import 单例),类型由 TS 自动推断,不再依赖动态声明文件生成器
  • 内置安全中间件(零依赖):CORS、安全响应头(对标 helmet 核心项)、IP/自定义维度限流(store: "auto" 时自动使用 Redis 分布式滑动窗口,多实例共享;未配置 redis 回退内存),config.security 开关控制
  • 内置认证授权(JWT):config.jwt 声明式启用,Bearer/裸 token 兼容,ctx.user / ctx.makeUserToken / 可插拔 permission 授权钩子(403)
  • 内置统一异常与响应:类型化 BizError(业务码 + 可选 HTTP 状态 + 附加数据)、统一信封 { code, message, data }、ctx.ok / ctx.fail 助手;系统级异常自动 500 且不泄漏内部信息
  • 内置可观测能力(零依赖):X-Request-Id 请求链路 ID + W3C Traceparent 透传、JSON 结构化日志(生产环境)与请求级 ctx.log、访问日志中间件、/__health 健康检查(对 orm/redis 真实探活,依赖不健康返回 503)、SIGTERM/SIGINT 优雅停机
  • 配置 schema 校验(zod):内置键启动时校验、类型错误快速失败;业务配置原样透传
  • 数据访问加固:migration/ 目录约定自动注册迁移(typeorm.migrationsRun: true 启动自动执行);生产环境禁止 synchronize(显式 allowSynchronizeInProd 逃生);数据库初始化失败默认 fail-fast
  • 上传守卫:config.upload 扩展名/MIME 白名单校验,拒绝的文件自动清理并返回 400
  • 内置任务队列:基于 bullmq@6 的 bull 兼容适配层(TaskClient),app.task / app.queue.* 保持 bull 风格 API
  • 数据访问:[email protected](DataSource),MySQL(mysql2 驱动),也可配置 Redis(ioredis 5)、Elasticsearch
  • 工程化开箱即用:Node 内置 test runner、ESLint 9 flat config + Prettier、GitHub Actions CI(Node 20/22/24 + lint + typecheck + build + test + audit)

环境要求

  • Node.js >= 20
  • TypeScript(推荐 5.x,框架内置类型依赖 zod 4 类型声明)

快速开始

# 方式一:脚手架
npm create youngjs-app@latest my-app
cd my-app
npm install
npm run dev

# 方式二:手动创建
npm i @youngjs/core

app.ts(入口):

import { young } from "@youngjs/core";
young();

config/config.default.ts:

module.exports = {
  port: 3001,
  // 反向代理信任配置:开启后 ctx.ip 取 X-Forwarded-For(限流/审计依赖真实 IP)
  // proxy: true,
  // 可选:内置安全中间件(默认仅开启安全响应头)
  security: {
    // cors: true, // 或 { origin: "https://example.com", maxAge: 86400 }
    // rateLimit: { windowMs: 60000, max: 100 }, // store: "auto" 有 redis 自动用分布式限流
  },
  // 可选:健康检查路径(默认 /__health;依赖不健康返回 503,strict:false 关闭)
  // health: { path: "/__health", strict: true, timeout: 2000 },
  // 可选:JWT 认证(config.jwt 存在即启用,secret 必填)
  // jwt: {
  //   secret: process.env.JWT_SECRET, // 必填,生产必须环境变量注入
  //   expires: 3600 * 24 * 7,         // token 有效期(秒)
  //   prefixes: ["admin"],            // 需要认证的 URL 前缀
  //   ignore: ["admin/system/user/login"], // 跳过认证的完整相对路径
  // },
  // 可选:上传守卫(扩展名/MIME 白名单,拒绝的文件自动清理并返回 400)
  // upload: { enabled: true, extensions: ["jpg", "png", "pdf"] },
  // 可选:配置数据库后自动初始化 typeorm,未配置则跳过。
  // 生产环境禁止 synchronize,请使用 migration/ 目录 + migrationsRun: true
  // typeorm: { type: "mysql", host: "127.0.0.1", port: 3306, username: "root", password: "", database: "app", migrationsRun: true },
  // 可选:配置后自动初始化 redis
  // redis: { host: "127.0.0.1", port: 6379 },
};

注意:数据库/Redis 等敏感信息一律通过环境变量(.env)注入,禁止把真实密码提交到仓库。

目录约定

| 目录 | 作用 | | --- | --- | | module/ | 服务类(Controller + Service 一体),框架自动加载路由 | | entity/ | typeorm 实体类,自动注册进 DataSource | | comm/ | 通用工具类,导出一份单例实例供 import | | queue/ | 队列类,配合 app.queue.xxx 使用 | | socket/ | socket.io 事件处理类 | | middleware/ | koa 中间件(config.middleware 数组启用) | | esindex/ | elasticsearch 索引定义 | | config/ | 配置:config.default.ts + config.local.ts(dev)/ config.prod.ts(prod) |

服务与类型(类引用)

import { get, post, router, youngService } from "@youngjs/core";
import UserEntity from "../entity/user";

@router("/user", ["info", "page", "add", "delete", "update", "list"])
export default class User extends youngService {
  constructor(ctx) {
    super(ctx);
    this.entity = UserEntity;
    this.searchOption.fieldEq = ["id"];
  }

  // 类引用获取 Repository,返回类型自动推断为 Repository<UserEntity>
  async info() {
    const repo = this.getRepository(UserEntity);
    return this.success(await repo.findOne({ where: { id: this.body.id } }));
  }

  // 自定义路由以 "/" 开头会拼接类前缀:@post("/login") => POST /user/login
  // 不以 "/" 开头则注册为根路径:@get("hello") => GET /hello
  @post("/login")
  async login() {
    return this.success(/* ... */);
  }
}

关键点:

  • 实体类文件本身就是类型来源,this.getRepository(UserEntity) 返回 Repository<UserEntity>,无需任何代码生成
  • @router / @get / @post 装饰器由框架自动收集注册,重复注册自动跳过并告警
  • 公共代码放 comm/,导出一份单例实例:
// comm/helper.ts
export default new class {
  sleep(ms: number) {
    return new Promise((r) => setTimeout(r, ms));
  }
}();
// 使用:import helper from "../../comm/helper";

应用实例与启动编排(Application)

import { young, Application } from "@youngjs/core";

// 1) 便捷入口:创建实例 → boot(配置/插件/中间件/路由/资源)→ start(监听端口)
young();                       // 等价旧用法
young({ baseDir: "/srv/app", env: "prod" }); // 显式项目根目录与环境

// 2) 显式控制(企业级 / 测试):boot 不监听端口,可直接 app.callback() 供 supertest 使用
const app = new Application();
await app.boot({ baseDir: "/srv/app" }); // 完成全部初始化
await app.start();                       // 再监听端口
await app.teardown();                    // 释放资源(插件 stop → worker → redis → orm)
  • 每次 young() / new Application() 都是独立实例(旧版为模块级单例,多实例会互相污染)
  • 路由在 boot 期注册:启动即打印路由清单(POST /user/info -> User.info 等),首个请求不再惰性初始化
  • 目录语义:baseDir=项目根(显式传入优先,缺省按 require.main 探测,ESM/程序化入口回退 cwd 并告警);rootDir=加载目录(dev=baseDir,prod=dist/,非标准布局回退并告警)

阶段化生命周期

启动按阶段推进,每阶段触发同名事件(app.on("configDidLoad", fn) 可监听,beforeStart/ready 支持异步):

configDidLoad → pluginDidLoad → middlewareDidLoad → beforeStart → serverDidReady

config/lifecycle.ts 的类钩子与事件一一对应:

export default class {
  before(app) {}                        // 兼容旧钩子 ≈ configDidLoad
  configDidLoad(app) {}                 // 配置加载完成
  pluginDidLoad(app) {}                 // 插件加载完成
  middlewareDidLoad(app) {}             // 中间件与路由注册完成
  async beforeStart(app) {}             // 资源(orm/redis/task/queue/es)就绪后、监听前(可 await)
  ready(app) {}                         // 服务已监听(≈ serverDidReady)
}

插件(config/plugin.ts)

  • 文件可缺省(缺失时告警跳过);每个插件收集到 app.plugins 注册表
  • 导出两种格式:
// 兼容:函数
module.exports = function start(app, config) {};

// 企业级:完整生命周期(stop 会在 teardown / 启动失败清理时被调用)
module.exports = {
  start(app, config) {},     // 必选
  beforeStart(app) {},       // 资源就绪后(boot 会 await)
  ready(app) {},             // 服务就绪后
  stop(app) {},              // 停止/失败清理
};
  • boot 失败自动清理:任一步抛错 → 按序 teardown(插件 stop → 任务/队列 worker → redis → orm)→ 重新抛出;young() 入口对启动失败输出错误日志并 process.exit(1)(fail-fast)
  • 配置深合并:config.local/config.prod 覆盖 config.default 时按对象递归合并(内层键各自覆盖),数组整体替换

多应用限制:装饰器(@router/@get 等)在模块加载时写入进程级注册表,因此同进程内多个 Application 共享同一份装饰器注册(各自持有独立的 app.router 实例与配置)。如需完全隔离的多应用,请拆分为独立进程,或使用 app.router 编程式注册。

内置能力

配置校验(zod)

config/*.ts 加载后,框架对内置键(port / static / security / health / proxy / typeorm / redis / body / upload / jwt)做 schema 校验,类型错误在启动时立即报错;业务自定义键原样透传。

统一异常与响应(lib/errors + lib/errorHandler)

  • 框架自动挂载统一异常中间件(无需配置):
    • BizError(throw new BizError(1001, "描述", { status, data }) 或快捷工厂 bizError)→ 统一信封 { code, message, data };未指定 status 时业务码 400~599 跟随为 HTTP 状态码
    • 普通 Error 视为业务异常(code=1001,HTTP 200,兼容旧行为);系统级异常(TypeError 等)返回 500 且不泄漏内部信息
    • 异常均记录结构化日志(含 requestId / traceId / 堆栈)
  • ctx.ok(data, message?) / ctx.fail(code?, message?, status?) 响应助手
  • 404 统一返回 { code: 404, message: "not found", data: null }

JWT 认证(config.jwt)

  • config.jwt 存在即启用:prefixes 命中的 URL 前缀要求携带有效 token(Bearer 或裸 token 均兼容),通过后挂载 ctx.user(payload)与 ctx.auth = { url, method, action }
  • ctx.makeUserToken(user) 签发 token;可选 permission(ctx, { url, method, action }) 授权钩子,返回 false 时 403
  • 旧配置键兼容:checkUrlPrefix / ignoreUrl

安全(config.security)

  • cors:布尔或 { origin, methods, allowedHeaders, maxAge },默认关闭
  • headers:安全响应头(X-Content-Type-Options / X-Frame-Options / Referrer-Policy 等),默认开启
  • rateLimit:布尔或 { windowMs, max, message, store, keyBy },默认关闭
    • store: "auto"(默认):配置了 redis 时使用 Redis 滑动窗口(多实例共享),否则回退进程内内存滑动窗口;"memory" / "redis" 可强制指定
    • keyBy:默认按 IP(建议配合 proxy: true 取真实 IP),可传函数 (ctx) => string

上传守卫(config.upload)

  • upload: { enabled: true, extensions: [...], mimeTypes: [...] } 启用后,koa-body 解析完的文件先过白名单校验,非法文件自动清理并返回 400
  • 默认上传大小上限 50MB(config.body.maxFileSize 调整),JSON 请求体默认 1mb(config.body.jsonLimit)

数据访问(typeorm)

  • entity/ 目录约定自动注册实体;新增 migration/ 目录约定自动注册迁移类(需实现 up/down)
  • typeorm.migrationsRun: true 启动自动执行待执行迁移
  • 生产环境禁止 synchronize:启动直接报错,除非显式 typeorm.allowSynchronizeInProd: true
  • 初始化失败默认 fail-fast(typeorm.failFast: false 可关闭),避免带病启动

可观测(lib/ops)

  • 每个请求生成/透传 X-Request-Id 与 W3C Traceparent(ctx.state.requestId / ctx.state.traceId),并挂载绑定 requestId 的请求级日志器 ctx.log
  • 访问日志中间件:方法/路径/状态/耗时/IP/requestId/traceId,JSON 行输出(生产环境)
  • 结构化日志:NODE_ENV=production 时 app.log.* 输出 JSON 行(time/level/msg/requestId),开发环境保持彩色文本
  • GET /__health 对配置的依赖(orm SELECT 1 / redis PING)真实探活,任一不健康返回 503(health.strict: false 关闭;health.timeout 调整超时,默认 2000ms)
  • 收到 SIGTERM/SIGINT 后按序关闭:http server(含空闲 keep-alive 连接)→ 任务/队列 worker → redis → typeorm,超时强制退出

任务与队列

// queue/test.ts
import { youngQueue } from "@youngjs/core";
export default class TestQueue extends youngQueue {
  async job(data) {
    // 消费逻辑(返回 Promise 即可)
  }
}

// 任意 service 中
this.app.queue.test.add({ time: Date.now() });

底层为 bullmq@6,对外 API 保持 bull 风格(add(data, {repeat})、getRepeatableJobs、removeRepeatableByKey)。

开发与发布

npm test         # 运行测试(Node 内置 test runner)
npm run lint     # ESLint
npm run typecheck # tsc --noEmit
npm run build    # 编译 lib 产物(tsc)
npm run format   # Prettier 格式化

破坏性变更(自 1.0.30)

  • 实体/服务访问改为类引用:移除动态声明文件生成机制(lib/typings.js、lib/comm.js),app.orm.AdminUserEntity 等字符串访问不再有类型声明,请改用 getRepository(EntityClass)
  • typeorm 0.2 → 1.x:Connection → DataSource;find/findOne 需使用 { where: {...} };MySQL 驱动 mysql → mysql2
  • bull@3 → bullmq@6:任务处理器由 done 回调改为返回 Promise
  • Node >= 20

升级注意(企业级加固)

  • 统一异常处理已内置:应用自带的 exception 中间件可移除(保留会重复记录日志)
  • 生产环境 synchronize 被拒绝:请改用 migration/ 目录 + typeorm.migrationsRun: true,或显式 allowSynchronizeInProd: true 临时放行
  • 数据库初始化失败默认 fail-fast:typeorm.failFast: false 可恢复旧行为(带病启动)
  • 上传默认上限收紧为 50MB(原 200MB),通过 config.body.maxFileSize 调整
  • dev 模式不再每请求重建路由(由 nodemon 重启进程实现热更新)
  • 修复 config/lifecycle 生产环境不生效(此前只检测 .ts 后缀)
  • 认证能力上收内核:应用侧 requestCheck 类中间件可替换为 config.jwt + 应用级授权中间件;密码存储请使用单向哈希(示例见 youngjs-last comm/password.ts,Node 内置 scrypt)
  • 应用实例化:young() 每次调用创建独立实例(原模块级单例);测试请用 new Application() + app.boot() + app.callback()
  • 路由在 boot 期注册:启动日志打印路由清单;不再依赖首请求初始化
  • 配置深合并:config.local/prod 现在按对象递归覆盖 default(此前为浅合并),数组整体替换——如依赖浅合并覆盖整个对象的行为,请注意调整
  • config/plugin 可缺省:不再因缺少该文件启动失败;插件支持 stop 钩子,teardown 时会调用

相关项目

  • create-youngjs-app:项目脚手架
  • youngjs-last:完整后台示例(RBAC、上传、swagger 文档等)

License

ISC