aipexbase-js
v1.1.13
Published
一个功能丰富的 BaaS (Backend as a Service) JavaScript SDK,提供完整的后端服务能力。
Readme
AipexBase JS SDK
一个功能丰富的 BaaS (Backend as a Service) JavaScript SDK,提供完整的后端服务能力。
📋 目录
特性
- 🔐 用户认证 - 登录、注册、登出和用户信息管理
- 📊 数据库操作 - 支持链式调用的 CRUD 操作
- 🤖 AI 能力 - 文本对话、文生图、文生音频/视频等
- 📄 文档处理 - PDF 转图片等功能
- 💰 商品比价 - 商品搜索和最低价查询
- 📦 物流查询 - 快递跟踪查询
- 📍 地理服务 - 地址解析、路线规划、附近搜索
- 🚄 出行服务 - 火车票和航班查询
- 📢 消息通知 - 飞书机器人、企业微信、邮件发送
- 🔌 插件系统 - 支持自定义插件扩展
- 🎯 链式调用 - 优雅的 API 设计
- 🔑 自动 Token 管理 - 自动存储和管理用户认证 Token
- 📦 多格式支持 - 同时支持 CommonJS 和 ES Module
安装
npm install aipexbase-js快速开始
初始化客户端
import { createClient } from 'aipexbase-js';
const client = createClient({
baseUrl: 'https://your-api-endpoint.com',
apiKey: 'your-api-key'
});自定义存储和请求
如果你需要在 Node.js 环境或其他环境中使用,可以自定义存储和请求实现:
import { createClient } from 'aipexbase-js';
import { NodeStorage } from 'your-storage-lib';
import axios from 'axios';
const client = createClient({
baseUrl: 'https://your-api-endpoint.com',
apiKey: 'your-api-key',
storage: new NodeStorage(), // 自定义存储实现
request: async (url, options) => {
const res = await axios({ url, ...options });
return res.data;
}
});完整 API 文档
认证模块 (Auth)
登录
支持用户名、手机号或邮箱登录:
// 使用手机号登录
const result = await client.auth.login({
phone: '13800138000',
password: 'your-password'
});
// 使用邮箱登录
const result = await client.auth.login({
email: '[email protected]',
password: 'your-password'
});
// 使用用户名登录
const result = await client.auth.login({
user_name: 'username',
password: 'your-password'
});注册
const result = await client.auth.register({
user_name: 'newuser',
phone: '13800138000',
email: '[email protected]',
password: 'your-password'
});获取用户信息
const user = await client.auth.getUser();登出
await client.auth.logout();手动设置 Token
client.setToken('your-auth-token');数据库模块 (DB)
查询操作
列表查询
// 简单查询
const result = await client.db
.from('users')
.list();
// 带多个过滤条件
const result = await client.db
.from('users')
.list()
.eq('status', 'active')
.gt('age', 18)
.order('created_at', 'desc');
// 分页查询
const result = await client.db
.from('users')
.page()
.page(1, 20) // 页码,每页数量
.eq('status', 'active');
// 获取单条数据
const result = await client.db
.from('users')
.get()
.eq('id', 123);过滤操作符
// 等于
.eq('field', value)
// 不等于
.neq('field', value)
// 大于
.gt('field', value)
// 大于等于
.gte('field', value)
// 小于
.lt('field', value)
// 小于等于
.lte('field', value)
// 在范围内
.in('field', [value1, value2, value3])
// 在区间内
.between('field', [min, max])OR 条件查询
const result = await client.db
.from('users')
.list()
.eq('status', 'active')
.or((q) => {
q.eq('role', 'admin')
.eq('role', 'moderator');
});排序
// 升序
.order('created_at', 'asc')
// 降序
.order('created_at', 'desc')
// 对象形式
.order('created_at', { ascending: true })
.order('created_at', { direction: 'desc' })插入数据
const result = await client.db
.from('users')
.insert()
.values({
name: 'John Doe',
email: '[email protected]',
age: 25
});更新数据
const result = await client.db
.from('users')
.update()
.set({
status: 'inactive'
})
.eq('id', 123);删除数据
const result = await client.db
.from('users')
.delete()
.eq('id', 123);API 模块
用于调用自定义 API 接口。
// 基本调用
const result = await client.api
.call('yourApiName')
.param('key1', 'value1')
.param('key2', 'value2');
// 批量设置参数
const result = await client.api
.call('yourApiName')
.params({
key1: 'value1',
key2: 'value2'
});
// 自定义请求头
const result = await client.api
.call('yourApiName')
.headers({
'X-Custom-Header': 'value'
})
.params({ data: 'value' });AI 模块
文本对话
// 基本对话
const result = await client.ai.chat()
.text('你好,介绍一下你自己');
// 带提示词和会话ID的对话
const result = await client.ai.chat()
.text('今天天气怎么样?')
.prompt('你是一个天气预报助手')
.conversationId('session-123');图片对话(图生文)
const result = await client.ai.imageToText()
.url('https://example.com/image.jpg')
.text('这张图片里有什么?')
.prompt('请详细描述图片内容');文生图
const result = await client.ai.textToImage()
.text('一只可爱的熊猫在竹林里');文本转语音
const result = await client.ai.textToSpeech()
.text('你好,欢迎使用语音合成服务');文本转视频
// 方式1:自动执行(创建任务并轮询直到完成)
const result = await client.ai.textToVideo()
.text('一只小猫在草地上玩耍');
// 方式2:手动控制
const videoTask = client.ai.textToVideo().text('一只小猫在草地上玩耍');
// 创建任务
const createResult = await videoTask.createTask();
console.log('任务ID:', createResult.data);
// 查询任务状态
const queryResult = await videoTask.queryTask(createResult.data);
console.log('任务状态:', queryResult.data);文本转音频
// 方式1:自动执行
const result = await client.ai.textToAudio()
.text('一段优美的旋律');
// 方式2:手动控制
const audioTask = client.ai.textToAudio().text('一段优美的旋律');
const createResult = await audioTask.createTask();
const queryResult = await audioTask.queryTask(createResult.data);文档处理模块
PDF 转图片
// 基本用法
const result = await client.document.convertPdf()
.url('https://example.com/document.pdf')
.convert();
// 自定义配置
const result = await client.document.convertPdf()
.url('https://example.com/document.pdf')
.format('pdf-to-image')
.pollingInterval(3000) // 轮询间隔(毫秒)
.maxRetries(50) // 最大重试次数
.convert();
// 手动控制
const pdfTask = client.document.convertPdf()
.url('https://example.com/document.pdf');
// 创建任务
const createResult = await pdfTask.createTask();
// 查询任务
const queryResult = await pdfTask.queryTask(createResult.data);
// 快捷方式
const result = await client.document.quickConvert({
url: 'https://example.com/document.pdf',
format: 'pdf-to-image',
pollingInterval: 3000,
maxRetries: 50
});比价模块
商品搜索
const result = await client.comparison.searchProduct()
.keyword('苹果手机');
// 自定义参数
const result = await client.comparison.searchProduct()
.keyword('苹果手机')
.setParams({ sort: 'price' });最低价查询
const result = await client.comparison.findLowestPrice()
.keyword('华为 Mate 60');物流模块
快递查询
// 普通快递查询
const result = await client.logistics.trackPackage()
.company('yuantong') // 快递公司代码
.trackingNumber('123456789')
.track();
// 顺丰快递(必须提供手机号)
const result = await client.logistics.trackPackage()
.company('shunfeng')
.trackingNumber('SF123456789')
.phone('13800138000')
.track();常见快递公司代码:
yuantong- 圆通速递shentong- 申通快递zhongtong- 中通快递yunda- 韵达速递shunfeng- 顺丰速运shunfengkuaiyun- 顺丰快运
地理位置模块
经纬度转地址(逆地理编码)
const result = await client.location.locationToAddress()
.latitude(39.9042)
.longitude(116.4074);地址转经纬度(地理编码)
const result = await client.location.addressToLocation()
.address('北京市天安门广场');获取当前IP位置
const result = await client.location.currentLocation();路线规划
const result = await client.location.driving()
.from(39.9042, 116.4074) // 起点经纬度
.to(40.0076, 116.4929); // 终点经纬度附近搜索
const result = await client.location.nearby()
.lat(39.9042)
.lng(116.4074)
.radius(1000) // 搜索半径(米)
.keyword('餐厅'); // 搜索关键词出行模块
火车票查询
const result = await client.travel.train()
.from('北京')
.to('上海')
.date('2024-01-01');航班查询
const result = await client.travel.flight()
.from('北京')
.to('上海')
.date('2024-01-01');通知模块
飞书机器人
await client.notification.feishuRobot()
.content('这是一条来自飞书机器人的消息');企业微信机器人
await client.notification.wechatRobot()
.content('这是一条来自企业微信的消息');邮件发送
// 简单邮件
await client.notification.mail()
.to('[email protected]')
.title('测试邮件')
.content('这是一封测试邮件');
// 模板邮件
await client.notification.mail()
.to('[email protected]')
.title('欢迎注册')
.content('欢迎加入我们!')
.params({
username: 'John Doe',
activationCode: 'ABC123'
});插件系统
AipexBase 支持插件扩展功能。
注册插件
检查插件状态
// 检查插件是否已注册
pluginLoader.isRegistered('myPlugin');
// 获取所有已注册的插件
pluginLoader.getRegisteredPlugins();
// 移除插件
pluginLoader.unregister('myPlugin');完整示例
用户认证和数据处理流程
import { createClient } from 'aipexbase-js';
// 初始化客户端
const client = createClient({
baseUrl: 'https://your-api-endpoint.com',
apiKey: 'your-api-key'
});
async function main() {
try {
// 1. 用户注册
const registerResult = await client.auth.register({
user_name: 'john_doe',
email: '[email protected]',
password: 'securePassword123'
});
console.log('注册成功:', registerResult);
// 2. 用户登录
const loginResult = await client.auth.login({
email: '[email protected]',
password: 'securePassword123'
});
console.log('登录成功');
// 3. 获取用户信息
const user = await client.auth.getUser();
console.log('用户信息:', user);
// 4. 创建数据
const createResult = await client.db
.from('posts')
.insert()
.values({
title: '我的第一篇文章',
content: '这是文章内容...',
author_id: user.data.id
});
console.log('创建成功:', createResult);
// 5. 查询数据
const posts = await client.db
.from('posts')
.list()
.eq('author_id', user.data.id)
.order('created_at', 'desc');
console.log('文章列表:', posts);
// 6. 更新数据
const updateResult = await client.db
.from('posts')
.update()
.set({ title: '更新的标题' })
.eq('id', createResult.data.id);
console.log('更新成功:', updateResult);
// 7. 登出
await client.auth.logout();
console.log('已登出');
} catch (error) {
console.error('操作失败:', error);
}
}
main();AI 功能集成示例
async function aiExample() {
try {
// 1. AI 对话
const chatResult = await client.ai.chat()
.text('你好,介绍一下你自己')
.prompt('你是一个友好的AI助手');
console.log('AI回复:', chatResult);
// 2. 图生文
const imageResult = await client.ai.imageToText()
.url('https://example.com/image.jpg')
.text('这张图片里有什么?');
console.log('图片分析:', imageResult);
// 3. 文生图
const imageGen = await client.ai.textToImage()
.text('一只可爱的熊猫在竹林里');
console.log('生成图片:', imageGen);
// 4. 文本转视频
const video = await client.ai.textToVideo()
.text('一只小猫在草地上玩耍');
console.log('生成视频:', video);
} catch (error) {
console.error('AI 功能失败:', error);
}
}物流和位置服务示例
async function logisticsAndLocation() {
try {
// 1. 查询快递
const tracking = await client.logistics.trackPackage()
.company('yuantong')
.trackingNumber('123456789');
console.log('快递信息:', tracking);
// 2. 地址转经纬度
const location = await client.location.addressToLocation()
.address('北京市天安门广场');
console.log('经纬度:', location);
// 3. 路线规划
const route = await client.location.driving()
.from(39.9042, 116.4074)
.to(40.0076, 116.4929);
console.log('路线信息:', route);
// 4. 附近搜索
const nearby = await client.location.nearby()
.lat(39.9042)
.lng(116.4074)
.radius(1000)
.keyword('餐厅');
console.log('附近餐厅:', nearby);
} catch (error) {
console.error('服务调用失败:', error);
}
}进阶用法
自定义请求拦截器
const customRequest = async (url, options) => {
// 添加自定义请求头
options.headers = {
...options.headers,
'X-Custom-Header': 'value'
};
// 记录请求日志
console.log('Request:', url, options);
const res = await fetch(url, options);
const data = await res.json();
// 处理错误
if (!res.ok) {
throw new Error(data.message || 'Request failed');
}
return data;
};
const client = createClient({
baseUrl: 'https://api.example.com',
apiKey: 'your-key',
request: customRequest
});自定义存储实现
// Node.js 环境
class NodeStorage {
constructor() {
this.data = {};
}
getItem(key) {
return this.data[key] || null;
}
setItem(key, value) {
this.data[key] = value;
}
removeItem(key) {
delete this.data[key];
}
}
const client = createClient({
baseUrl: 'https://api.example.com',
apiKey: 'your-key',
storage: new NodeStorage()
});错误处理最佳实践
async function safeOperation() {
try {
const result = await client.db
.from('users')
.list();
return { success: true, data: result };
} catch (error) {
console.error('操作失败:', error);
// 根据错误类型处理
if (error.message.includes('unauthorized')) {
// 重新登录
await client.auth.login({ ... });
}
return { success: false, error: error.message };
}
}开发指南
项目结构
aipexbase-js/
├── src/
│ ├── client.js # 核心客户端
│ ├── index.js # 入口文件
│ ├── modules/ # 功能模块
│ │ ├── auth.js # 认证模块
│ │ ├── db.js # 数据库模块
│ │ ├── api.js # API 模块
│ │ ├── ai.js # AI 模块
│ │ ├── document.js # 文档处理模块
│ │ ├── comparison.js # 比价模块
│ │ ├── logistics.js # 物流模块
│ │ ├── location.js # 地理位置模块
│ │ ├── travel.js # 出行模块
│ │ └── notification.js # 通知模块
│ └── plugins/ # 插件系统
│ ├── plugin-loader.js
│ └── README.md
├── dist/ # 构建输出
│ ├── index.cjs.js # CommonJS 格式
│ └── index.esm.js # ES Module 格式
├── tests/ # 测试文件
├── package.json
├── rollup.config.mjs
└── README.md本地开发
# 安装依赖
npm install
# 构建项目
npm run build
# 运行测试
npm test
# 运行真实 API 测试
npm run test:real
# 监听模式运行测试
npm run test:watch构建和发布
# 构建
npm run build
# 发布的文件在 dist 目录贡献
欢迎提交 Issue 和 Pull Request!
开发流程
- Fork 项目
- 创建特性分支
- 提交更改
- 推送到分支
- 创建 Pull Request
License
ISC
支持
如果您在使用过程中遇到问题,请:
- 查看文档和示例
- 搜索已有的 Issue
- 创建新的 Issue 并提供详细的错误信息
AipexBase JS SDK - 让后端开发更简单 🚀
