iCloudFunc
🚀 一个基于 Koa 的轻量级云函数框架,支持自动路由生成和函数式开发。
✨ 特性
- 📁 自动路由生成:自动扫描
functions 目录,根据文件结构生成路由
- 🔄 多种导出方式:支持函数导出、对象导出、HTTP 方法导出等多种方式
- 🎯 动态路由:支持动态路由参数(如
[id].js 自动转换为 :id)
- ⚙️ 环境变量配置:通过环境变量灵活配置 functions 目录、端口等
- 🛠️ 中间件支持:内置 body parser、CORS、日志等常用中间件
- 📦 开箱即用:零配置启动,快速构建 API 服务
📦 安装
npm install icloudfunc
或使用 yarn:
yarn add icloudfunc
🚀 快速开始
方式一:使用 CLI 快速创建项目(推荐)
npx icloudfunc create my-app
cd my-app
npm install
npm start
方式二:手动创建
1. 创建项目结构
my-project/
├── app.js
└── functions/
├── hello.js
└── users.js
2. 创建入口文件
app.js
const iCloudFunc = require('icloudfunc');
const app = new iCloudFunc({
port: 3000,
prefix: '/api'
});
app.listen();
3. 创建云函数
functions/hello.js
module.exports = async (ctx) => {
ctx.body = {
success: true,
message: 'Hello, World!'
};
};
functions/users.js
exports.get = async (ctx) => {
ctx.body = {
success: true,
data: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
};
};
exports.post = async (ctx) => {
const { name } = ctx.request.body;
ctx.body = {
success: true,
message: `User ${name} created`
};
};
4. 启动服务
node app.js
访问:
GET http://localhost:3000/api/hello
GET http://localhost:3000/api/users
POST http://localhost:3000/api/users
📖 详细用法
环境变量配置
创建 .env 文件:
FUNCTIONS_DIR=./functions
ROUTE_PREFIX=/api
PORT=3000
NODE_ENV=development
然后在代码中使用:
require('dotenv').config();
const iCloudFunc = require('icloudfunc');
const app = new iCloudFunc();
app.listen();
配置选项
const app = new iCloudFunc({
functionsDir: './functions',
prefix: '/api',
port: 3000,
enableLogger: true,
cors: {
origin: '*',
methods: 'GET,POST,PUT,DELETE,OPTIONS',
headers: 'Content-Type,Authorization'
},
middlewares: [
]
});
函数导出方式
1. 默认函数导出
module.exports = async (ctx) => {
ctx.body = { message: 'Hello' };
};
路由:ALL /api/hello(支持所有 HTTP 方法)
2. HTTP 方法导出
exports.get = async (ctx) => {
};
exports.post = async (ctx) => {
};
exports.put = async (ctx) => {
};
exports.delete = async (ctx) => {
};
路由:
GET /api/users
POST /api/users
PUT /api/users
DELETE /api/users
3. Handler 导出
exports.handler = async (ctx) => {
ctx.body = { message: 'Custom handler' };
};
路由:ALL /api/custom
动态路由
使用 [参数名].js 格式创建动态路由:
exports.get = async (ctx) => {
const { id } = ctx.params;
ctx.body = {
success: true,
userId: id
};
};
路由:GET /api/users/:id
访问:GET /api/users/123 → { success: true, userId: '123' }
index.js 文件
index.js 文件会映射到其所在目录的根路径:
exports.get = async (ctx) => {
ctx.body = { message: 'Products list' };
};
路由:GET /api/products(而不是 /api/products/index)
嵌套路由
支持任意深度的目录嵌套:
functions/
├── api/
│ ├── v1/
│ │ └── users.js → /api/api/v1/users
│ └── v2/
│ └── users.js → /api/api/v2/users
自定义中间件
const app = new iCloudFunc({
middlewares: [
async (ctx, next) => {
const token = ctx.headers.authorization;
if (!token) {
ctx.status = 401;
ctx.body = { error: 'Unauthorized' };
return;
}
await next();
}
]
});
app.use(async (ctx, next) => {
console.log('Custom middleware');
await next();
});
访问 Koa 实例
const app = new iCloudFunc();
const koaApp = app.getApp();
koaApp.use(async (ctx, next) => {
await next();
});
app.listen();
🗂️ 项目结构示例
my-app/
├── app.js # 入口文件
├── .env # 环境变量配置
├── package.json
└── functions/ # 云函数目录
├── hello.js → GET/POST /api/hello
├── users.js → GET/POST /api/users
├── users/
│ └── [id].js → GET/PUT/DELETE /api/users/:id
├── products/
│ ├── index.js → GET/POST /api/products
│ └── [id].js → GET/PUT/DELETE /api/products/:id
└── admin/
└── dashboard.js → ALL /api/admin/dashboard
🔥 高级用法
错误处理
框架内置了错误处理中间件,你可以直接抛出错误:
exports.get = async (ctx) => {
if (!ctx.query.id) {
ctx.throw(400, 'ID is required');
}
throw new Error('Something went wrong');
};
请求体解析
框架自动解析 JSON 请求体:
exports.post = async (ctx) => {
const { name, email } = ctx.request.body;
};
响应格式
推荐使用统一的响应格式:
ctx.body = {
success: true,
data: { },
message: 'Success'
};
ctx.status = 400;
ctx.body = {
success: false,
error: 'Error message'
};
📝 发布到 npm
1. 登录 npm
npm login
2. 发布包
npm publish
3. 更新版本
npm version patch
npm version minor
npm version major
npm publish
🤝 贡献
欢迎提交 Issue 和 Pull Request!
📄 License
MIT
🙏 致谢
基于 Koa 构建。