一个用于通用应用的云服务库。
pnpm add m-cloud
import { Router } from 'm-cloud';
// 创建路由实例
const router = new Router();
// 定义GET路由
router.get('/api/users', async (ctx) => {
// 获取查询参数
const { page = 1, limit = 10 } = ctx.query;
// 模拟获取用户列表
const users = [
{ id: 1, name: '张三', email: 'zhangsan@example.com' },
{ id: 2, name: '李四', email: 'lisi@example.com' }
];
return {
success: true,
data: users,
pagination: { page, limit, total: users.length }
};
});
// 定义POST路由
router.post('/api/users', async (ctx) => {
// 获取请求体数据
const userData = ctx.body;
// 模拟创建用户
const newUser = {
id: 3,
...userData
};
return {
success: true,
data: newUser,
message: '用户创建成功'
};
});
// 处理请求
const event = {
httpMethod: 'GET',
path: '/api/users',
queryStringParameters: { page: '1', limit: '10' }
};
const context = {};
const result = await router.serve(event, context);
console.log(result);
import { Router } from 'm-cloud';
const router = new Router();
// 日志中间件
const loggerMiddleware = async (ctx, next) => {
console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.path}`);
await next();
console.log(`[${new Date().toISOString()}] Response status: ${ctx.status || 200}`);
};
// 认证中间件
const authMiddleware = async (ctx, next) => {
const token = ctx.headers.authorization?.split(' ')[1];
if (!token) {
return {
success: false,
error: '缺少认证令牌',
code: 401
};
}
// 验证令牌...
ctx.user = { id: 1, name: '认证用户' };
await next();
};
// 应用中间件
router.use(loggerMiddleware);
router.use('/api/protected', authMiddleware);
// 公开路由
router.get('/api/public', async (ctx) => {
return { success: true, message: '公开接口' };
});
// 受保护路由
router.get('/api/protected/profile', async (ctx) => {
return {
success: true,
data: ctx.user,
message: '受保护接口'
};
});
import { Router, PluginManager } from 'm-cloud';
const router = new Router();
// 创建缓存插件
const cachePlugin = {
name: 'cache',
install: (ctx) => {
const cache = new Map();
return {
get: (key) => cache.get(key),
set: (key, value, ttl = 3600000) => {
cache.set(key, value);
// 简单的TTL实现
setTimeout(() => cache.delete(key), ttl);
},
clear: () => cache.clear()
};
}
};
// 注册插件
router.usePlugin(cachePlugin);
// 使用插件
router.get('/api/users/:id', async (ctx) => {
const { id } = ctx.params;
const cacheKey = `user_${id}`;
// 尝试从缓存获取
const cachedUser = ctx.cache.get(cacheKey);
if (cachedUser) {
return {
success: true,
data: cachedUser,
fromCache: true
};
}
// 模拟从数据库获取
const user = { id: parseInt(id), name: `用户${id}`, email: `user${id}@example.com` };
// 存入缓存
ctx.cache.set(cacheKey, user);
return {
success: true,
data: user,
fromCache: false
};
});
import { Router, getPluginManager } from 'm-cloud';
import { loggerPlugin, cachePlugin } from 'm-cloud/plugin/plugins';
const router = new Router();
// 初始化插件系统
async function initPlugins() {
const pluginManager = getPluginManager();
// 安装带配置的插件
await pluginManager.installWithOptions(loggerPlugin, {
level: 'info',
format: 'json'
});
await pluginManager.installWithOptions(cachePlugin, {
ttl: 600000, // 10分钟
maxSize: 500,
prefix: 'app:'
});
return pluginManager;
}
// 使用插件
router.get('/api/users/:id', async (ctx) => {
const { id } = ctx.params;
const cacheKey = `user_${id}`;
// 获取缓存工具
const createCache = ctx.pluginManager?.getUtility('createCache');
if (createCache) {
const cache = createCache({ ttl: 300000 });
// 尝试从缓存获取
const cachedUser = cache.get(cacheKey);
if (cachedUser) {
return {
success: true,
data: cachedUser,
fromCache: true
};
}
// 模拟从数据库获取
const user = { id: parseInt(id), name: `用户${id}`, email: `user${id}@example.com` };
// 存入缓存
cache.set(cacheKey, user);
return {
success: true,
data: user,
fromCache: false
};
}
return {
success: false,
error: '缓存插件未安装'
};
});
import { DatabaseOperations } from 'm-cloud';
// 初始化数据库操作
const dbOps = new DatabaseOperations();
// 查询数据
async function getUserList() {
const users = await dbOps.find('users', {
query: { status: 'active' },
options: {
sort: { createdAt: -1 },
limit: 10,
skip: 0
}
});
return users;
}
// 插入数据
async function createUser(userData) {
const result = await dbOps.insert('users', userData);
return result;
}
// 更新数据
async function updateUser(userId, updates) {
const result = await dbOps.update('users',
{ _id: userId },
{ $set: updates }
);
return result;
}
// 删除数据
async function deleteUser(userId) {
const result = await dbOps.delete('users', { _id: userId });
return result;
}
// 分页查询
async function getUserPage(page = 1, limit = 10) {
const result = await dbOps.paginate('users', {
query: { status: 'active' },
options: {
sort: { createdAt: -1 }
},
pagination: {
page,
limit
}
});
return result;
}
import { Router } from 'm-cloud';
const router = new Router({
// 路由前缀
prefix: '/api/v1',
// 全局错误处理
errorHandler: (error, ctx) => {
console.error('Error:', error);
return {
success: false,
error: error.message || '服务器内部错误',
code: error.code || 500
};
},
// 404 处理
notFoundHandler: (ctx) => {
return {
success: false,
error: '接口不存在',
code: 404
};
}
});
import { DatabaseOperations } from 'm-cloud';
const dbOps = new DatabaseOperations({
// 缓存配置
cache: {
enabled: true,
ttl: 3600000, // 缓存过期时间(毫秒)
size: 1000 // 缓存最大条目数
},
// 数据库连接配置
database: {
// 数据库连接选项
}
});
src/
├── config/ # 配置相关
├── context/ # 上下文管理
├── db/ # 数据库操作
├── lib/ # 核心库
├── middleware/ # 中间件
├── plugin/ # 插件系统
├── utils/ # 工具函数
├── BaseContext.ts # 基础上下文
├── Router.ts # 路由系统
├── errors.ts # 错误定义
├── index.ts # 入口文件
└── types.ts # 类型定义
# 运行所有测试
pnpm run test
# 运行测试并查看覆盖率
pnpm run test:coverage
# 监听模式运行测试
pnpm run test:watch
# 使用 UI 运行测试
pnpm run test:ui
# 生成 API 文档
pnpm run docs
# 本地预览文档
pnpm run docs:serve
pnpm run build
# 检查代码
pnpm run lint
# 自动修复代码问题
pnpm run lint:fix
项目包含多个示例,位于 examples/ 目录:
basic-features/ - 基础功能示例advanced-features/ - 高级功能示例common-patterns/ - 常见使用模式global-plugin-system/ - 全局插件系统m-cloud-demo/ - 完整演示项目Apache-2.0