@tumbaland/backend-core

中文文档
1.57.0发布于 2026/11/03MITTypeScriptCommonJS

Core shared functionality for Tumbaland backend services

原始使用文档
文档目录15 节
  1. Installation
  2. Usage
  3. Basic Service Setup
  4. Using Authentication
  5. Health Checks (unified standard)
  6. Graceful Shutdown
  7. Structured Logging
  8. API Responses
  9. Environment Variables
  10. Docker Logging
  11. Development vs Production
  12. Development
  13. Production
  14. 📦 Releases & Versioning
  15. Contributing

@tumbaland/backend-core

Core shared functionality for Tumbaland backend services.

Installation

npm install @tumbaland/backend-core

Usage

Basic Service Setup

import express from 'express';
import {
  logger,
  healthCheck,
  connectDB,
  requestLogger,
  errorHandler,
  correlationMiddleware
} from '@tumbaland/backend-core';

const app = express();

// Environment variables
process.env.SERVICE_NAME = 'my-service';
process.env.SERVICE_DESCRIPTION = 'My awesome service';

// Middleware
app.use(correlationMiddleware);
app.use(requestLogger);

// Routes
app.get('/health', healthCheck);

// Error handling (must be last)
app.use(errorHandler);

// Start server
connectDB()
  .then(() => {
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
      logger.info(`🚀 Service running on port ${PORT}`);
    });
  })
  .catch((error) => {
    logger.error('Failed to start service:', error);
    process.exit(1);
  });

Using Authentication

import { authenticateToken } from '@tumbaland/backend-core';

app.get('/protected', authenticateToken, (req, res) => {
  const user = (req as any).user;
  res.json({ message: `Hello ${user.name}!` });
});

Health Checks (unified standard)

Every service mounts the same /health readiness endpoint via the createHealthCheck factory — one response contract across all services, so monitoring and dashboards see identical shapes:

import { createHealthCheck } from '@tumbaland/backend-core';

// DB-backed service (default): reports `dependencies.mongodb` and returns 503
// while the connection is down.
export const healthCheck = createHealthCheck({
  service: 'my-service',
  description: 'My awesome service'
});

// Service with no database: readiness is a static ok, no `dependencies`.
export const healthCheck = createHealthCheck({
  service: 'public-service',
  description: 'Public API endpoints service',
  checkDatabase: false
});

app.get('/health', healthCheck);

Response body: { status, service, type: 'backend', timestamp, version, description }, plus dependencies.mongodb when checkDatabase is on. /health/live (liveness, no dependency checks — used by the Docker HEALTHCHECK) is mounted separately by createBaseApp.

Graceful Shutdown

registerShutdown wires SIGINT and SIGTERM (the signal Docker/Kubernetes send on stop and rollout) to drain the HTTP server and close the MongoDB connection before the process exits:

import { registerShutdown } from '@tumbaland/backend-core';

const server = app.listen(PORT, () => logger.info('Service started', { port: PORT }));

// DB-backed service
registerShutdown({ serviceName: 'my-service', server });

// No-DB service: skip the Mongo disconnect
registerShutdown({ serviceName: 'public-service', server, disconnectDatabase: false });

The handler is idempotent and self-arms a force-exit timer so a hung close still terminates.

Structured Logging

import { logger } from '@tumbaland/backend-core';

// Different log levels
logger.error('Database connection failed', { error: err.message });
logger.warn('High memory usage detected', { usage: '85%' });
logger.info('User logged in', { userId: '123', ip: '192.168.1.1' });
logger.debug('Processing request', { correlationId: req.correlationId });

API Responses

import { sendSuccess, sendError } from '@tumbaland/backend-core';

app.get('/api/users', (req, res) => {
  // Success response
  sendSuccess(res, users, 'Users retrieved successfully');

  // Error response
  sendError(res, 'Failed to retrieve users', 500, 'Database error');
});

Environment Variables

  • NODE_ENV: development or production
  • SERVICE_NAME: Name of your service
  • SERVICE_DESCRIPTION: Description of your service
  • LOG_TO_FILE: Set to true to also log to files (development only)

Docker Logging

This library is optimized for Docker deployments:

  • Logs to stdout/stderr by default
  • Use structured JSON in production
  • Integrates with Docker logging drivers
  • Compatible with log aggregation tools (ELK, Loki, etc.)

Development vs Production

Development

  • Colored console output
  • Debug level logging
  • Human-readable format

Production

  • JSON structured logging
  • Info level and above
  • Optimized for log aggregation

📦 Releases & Versioning

This library is a real published npm package (@tumbaland/backend-core), versioned independently of the monorepo with standard-version and Conventional Commits. See the root README's "Commits & Releases" section for the full process and the reasoning behind it — summary: commit with conventional messages, then from this directory run npm run release (never hand-edit version and npm publish directly, or the package, changelog, and tags drift out of sync with each other). Tags for this package are scoped as backend-core-vX.Y.Z so they can't collide with frontend-core's, components', or the monorepo's own app-vX.Y.Z tags.


Contributing

  1. Make changes to source files in src/
  2. Run npm run build to compile TypeScript
  3. Test your changes
  4. Submit a pull request

版本与发布记录

@tumbaland/backend-core 共发布 44 个版本,首次发布于 2026/07/12;过去 12 个月发布了 44 个版本。

版本发布日期距今
1.57.0latest2026/11/03今天
1.56.02026/11/021 天前
1.55.02026/11/012 天前
1.54.02026/10/312 天前
1.53.02026/10/312 天前
1.52.02026/10/304 天前

关于 @tumbaland/backend-core 的常见问题

@tumbaland/backend-core 是什么?

Tumbaland后端服务的核心共享功能

如何安装 @tumbaland/backend-core?

在项目目录运行 npm install @tumbaland/backend-core,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:express(^5.2.1)、mongoose(^9.7.3)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@tumbaland/backend-core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@tumbaland/backend-core 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@tumbaland/backend-core 可以商用吗?

@tumbaland/backend-core 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@tumbaland/backend-core 还在维护吗?

最新版本 1.57.0 发布于 2026/11/03(今天);至今共发布 44 个版本,其中过去 12 个月发布了 44 个;首次发布于 2026/07/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。