🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

icloudfunc

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

icloudfunc

一个基于 Koa 的轻量级云函数框架,支持自动路由生成

latest
npmnpm
Version
1.0.0
Version published
Weekly downloads
3
200%
Maintainers
1
Weekly downloads
 
Created
Source

iCloudFunc

🚀 一个基于 Koa 的轻量级云函数框架,支持自动路由生成和函数式开发。

✨ 特性

  • 📁 自动路由生成:自动扫描 functions 目录,根据文件结构生成路由
  • 🔄 多种导出方式:支持函数导出、对象导出、HTTP 方法导出等多种方式
  • 🎯 动态路由:支持动态路由参数(如 [id].js 自动转换为 :id
  • ⚙️ 环境变量配置:通过环境变量灵活配置 functions 目录、端口等
  • 🛠️ 中间件支持:内置 body parser、CORS、日志等常用中间件
  • 📦 开箱即用:零配置启动,快速构建 API 服务

📦 安装

npm install icloudfunc

或使用 yarn:

yarn add icloudfunc

🚀 快速开始

方式一:使用 CLI 快速创建项目(推荐)

# 使用 npx 创建新项目
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

// 支持多个 HTTP 方法
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 目录路径
FUNCTIONS_DIR=./functions

# 路由前缀
ROUTE_PREFIX=/api

# 服务器端口
PORT=3000

# Node 环境
NODE_ENV=development

然后在代码中使用:

// 使用 dotenv 加载环境变量
require('dotenv').config();

const iCloudFunc = require('icloudfunc');

// 框架会自动从环境变量读取配置
const app = new iCloudFunc();

app.listen();

配置选项

const app = new iCloudFunc({
  // Functions 目录路径(默认:process.cwd()/functions)
  functionsDir: './functions',
  
  // 路由前缀(默认:/api)
  prefix: '/api',
  
  // 端口号(默认:3000)
  port: 3000,
  
  // 启用日志(默认:true)
  enableLogger: true,
  
  // CORS 配置(默认:false)
  cors: {
    origin: '*',
    methods: 'GET,POST,PUT,DELETE,OPTIONS',
    headers: 'Content-Type,Authorization'
  },
  
  // 自定义中间件
  middlewares: [
    // 你的自定义中间件
  ]
});

函数导出方式

1. 默认函数导出

// functions/hello.js
module.exports = async (ctx) => {
  ctx.body = { message: 'Hello' };
};

路由:ALL /api/hello(支持所有 HTTP 方法)

2. HTTP 方法导出

// functions/users.js
exports.get = async (ctx) => {
  // GET 请求处理
};

exports.post = async (ctx) => {
  // POST 请求处理
};

exports.put = async (ctx) => {
  // PUT 请求处理
};

exports.delete = async (ctx) => {
  // DELETE 请求处理
};

路由:

  • GET /api/users
  • POST /api/users
  • PUT /api/users
  • DELETE /api/users

3. Handler 导出

// functions/custom.js
exports.handler = async (ctx) => {
  ctx.body = { message: 'Custom handler' };
};

路由:ALL /api/custom

动态路由

使用 [参数名].js 格式创建动态路由:

// functions/users/[id].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 文件会映射到其所在目录的根路径:

// functions/products/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();
    }
  ]
});

// 或者使用 use 方法
app.use(async (ctx, next) => {
  console.log('Custom middleware');
  await next();
});

访问 Koa 实例

const app = new iCloudFunc();

// 获取底层 Koa 实例
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. 更新版本

# 补丁版本(bug 修复)
npm version patch

# 次版本(新功能)
npm version minor

# 主版本(破坏性更改)
npm version major

# 发布新版本
npm publish

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📄 License

MIT

🙏 致谢

基于 Koa 构建。

Keywords

koa

FAQs

Package last updated on 16 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts