### uni-app Frontend Upload Example
Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-ext-storage-basic.md
Example of how to implement file uploads from a uni-app frontend using cloud objects and `uni.uploadFile`.
```APIDOC
## uni-app Frontend Upload Example
### Description
Demonstrates how to select an image using `uni.chooseImage` and upload it via a uniCloud cloud object.
### Code Snippet
```javascript
// Select image and initiate upload
uni.chooseImage({
count: 1, // Number of images to choose
success: async (res) => {
const filePath = res.tempFilePaths[0];
uni.showLoading({ title: "Uploading...", mask: true });
// Import the cloud object that handles upload parameters
const extStorageCo = uniCloud.importObject("ext-storage-co");
// Get upload options from the cloud object
const uploadFileOptionsRes = await extStorageCo.getUploadFileOptions({
cloudPath: `images/${Date.now()}.jpg` // Define the cloud path
});
// Execute the upload using uni.uploadFile
const uploadTask = uni.uploadFile({
...uploadFileOptionsRes.uploadFileOptions, // Spread the upload parameters
filePath: filePath, // Local file path
success: (uploadFileRes) => {
if (uploadFileRes.statusCode === 200) {
const result = {
cloudPath: uploadFileOptionsRes.cloudPath,
fileID: uploadFileOptionsRes.fileID,
fileURL: uploadFileOptionsRes.fileURL
};
console.log("Upload successful", result);
}
},
fail: (err) => {
console.log("Upload failed", err);
}
});
// Monitor upload progress
uploadTask.onProgressUpdate((res) => {
console.log("Upload progress", res.progress + "%");
});
uni.hideLoading();
}
});
```
```
--------------------------------
### Cloud Object Basic Template
Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-permission-system.md
A foundational template for creating VK Cloud Objects, including initialization, request pre-processing (_before), request post-processing (_after), and example functions.
```APIDOC
## Cloud Object Basic Template
### Description
This template provides the basic structure for a VK Cloud Object, which is a collection of cloud functions within a single JavaScript file. It includes hooks for pre- and post-request processing.
### Method
N/A (This is a structural template)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
```javascript
'use strict';
var vk; // Global vk instance
// Table names involved
const dbName = {
//test: "vk-test", // Test table
};
var db = uniCloud.database(); // Global database reference
var _ = db.command; // Database operators
var $ = _.aggregate; // Aggregate query operators
var cloudObject = {
isCloudObject: true, // Mark as rapid development mode
/**
* Pre-request processing, mainly for pre-processing before calling methods, usually for interceptors, unified identity authentication, parameter validation, global object definition, etc.
*/
_before: async function() {
vk = this.vk; // Define vk as a global object
// let { customUtil, uniID, config, pubFun } = this.getUtil(); // Get utility package
},
/**
* Post-request processing, mainly for processing the return result or thrown errors of the current call method
*/
_after: async function(options) {
let { err, res } = options;
if (err) {
return; // If the method throws an error, directly return; do not process
}
return res;
},
/**
* Template function
* @url client/user.getInfo Frontend call URL parameter address
*/
getInfo: async function(data) {
let { uid } = this.getClientInfo(); // Get client information
let userInfo = await this.getUserInfo(); // Get the currently logged-in user's info
let res = { code: 0, msg: '' };
// Business logic start-----------------------------------------------------------
console.log("Request parameters", data);
res.userInfo = userInfo; // Return the current logged-in user information to the frontend
// Business logic end-------------------------------------------------------------
return res;
},
/**
* Template function
* @url client/user.getList Frontend call URL parameter address
*/
getList: async function(data) {
let { uid, filterResponse, originalParam } = this.getClientInfo(); // Get client information
let res = { code: 0, msg: '' };
// Business logic start-----------------------------------------------------------
console.log("Request parameters", data);
// Business logic end-------------------------------------------------------------
return res;
}
};
module.exports = cloudObject;
```
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Vue Component Structure and Best Practices
Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-component-development.md
Demonstrates the basic structure of a Vue component, including template, script setup, and scoped styles. It highlights the use of defineProps for attributes, defineEmits for events, ref and computed for reactive data, and scoped CSS for style isolation.
```vue
{{ title }}
```
--------------------------------
### Check User Roles and Permissions using VK Unicloud
Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-permission-system.md
Provides examples of checking user roles and permissions using the vk.userCenter utility. It demonstrates how to check for a specific role, any of multiple permissions, or all specified permissions.
```javascript
// 检查用户是否有特定角色
let hasRole = await vk.userCenter.hasRole({
uid,
role: 'admin'
});
// 检查用户是否有多个权限中的任意一个
let hasAnyPermission = await vk.userCenter.hasAnyPermission({
uid,
permissions: ['user-view', 'user-manage']
});
// 检查用户是否有所有指定权限
let hasAllPermissions = await vk.userCenter.hasAllPermissions({
uid,
permissions: ['user-view', 'user-edit']
});
```
--------------------------------
### Setup Payment Database Indexes in JavaScript
Source: https://github.com/382444017/vk-unicloud/blob/master/vk-pay-error-handling.md
Optimizes database performance by creating necessary indexes on the 'payment_orders' table. It sets up unique indexes for order numbers and non-unique indexes for user IDs, status, and creation dates. This function assumes a 'vk.baseDao' object for database operations.
```javascript
// 支付表索引优化
async function setupPaymentIndexes() {
// 创建订单号索引
await vk.baseDao.createIndex({
dbName: "payment_orders",
field: "out_trade_no",
unique: true
});
// 创建用户ID索引
await vk.baseDao.createIndex({
dbName: "payment_orders",
field: "user_id"
});
// 创建状态索引
await vk.baseDao.createIndex({
dbName: "payment_orders",
field: "status"
});
// 创建时间索引
await vk.baseDao.createIndex({
dbName: "payment_orders",
field: "create_date"
});
}
```
--------------------------------
### Perform Cloud-Side HTTP Requests with VK Unicloud
Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-best-practices.md
Illustrates how to make HTTP requests from within VK Unicloud functions. Covers various methods (POST, GET), data types (JSON, text, binary), setting headers, timeouts, using proxies (Aliyun specific), and encrypted communication.
```javascript
// 云端HTTP请求(必须使用await)
const response = await vk.request({
url: 'https://api.example.com/data',
method: 'POST',
header: {
'content-type': 'application/json',
'authorization': 'Bearer token'
},
data: {
key: 'value'
},
timeout: 10000
});
console.log('请求结果:', response);
// 请求文本格式数据
const textResponse = await vk.request({
url: 'https://api.example.com/text',
method: 'GET',
dataType: 'text'
});
// 请求二进制数据
const binaryData = await vk.request({
url: 'https://example.com/image.jpg',
method: 'GET',
dataType: 'default'
});
// 转换为base64
const base64 = "data:image/png;base64," + binaryData.toString('base64')
// 使用代理请求(仅阿里云)
const proxyResponse = await vk.request({
url: 'https://api.example.com/data',
useProxy: true,
data: { key: 'value' }
});
// 加密通信
const encryptResponse = await vk.request({
url: 'https://your-domain.com/http/router/api/test',
encrypt: true,
header: {
'uni-id-token': userToken,
'vk-appid': '__UNI__12345',
'vk-platform': 'h5'
},
data: { a: 1, b: 2 }
});
```
--------------------------------
### Responsive Design with Media Queries
Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-style-guide.md
This code demonstrates responsive design principles using CSS media queries. It applies different styles based on screen width, starting with mobile-first design and progressively enhancing for tablet and desktop views. This ensures optimal layout and user experience across various devices.
```css
/* 移动端优先 */
.container {
padding: 20rpx;
width: 100%;
}
/* 平板端 */
@media (min-width: 768px) {
.container {
padding: 40rpx;
max-width: 750px;
margin: 0 auto;
}
}
/* 桌面端 */
@media (min-width: 1024px) {
.极狐tainer {
padding: 60rpx;
max-width: 1200px;
}
}
```
--------------------------------
### 使用 Context7 检索文档 (Bash)
Source: https://github.com/382444017/vk-unicloud/blob/master/README.md
通过 Context7 工具在 VK Unicloud 项目中检索文档。该命令接受一个搜索关键词作为参数,用于查找相关的文档内容。
```bash
# 使用 Context7 检索文档
context7 search "你的搜索关键词"
```
--------------------------------
### Successful Responses
Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-response-format.md
Examples of successful responses, with and without data, and for list data retrieval.
```APIDOC
## Successful Responses
### Description
These examples demonstrate successful operations. A `code` of 0 signifies success, triggering the `success` callback in `vk.callFunction`.
### Method
N/A
### Endpoint
N/A
### Response
#### Basic Success Response (code: 0)
- **code** (number) - 0 for success.
- **msg** (string) - Success message.
#### Response Example (Basic)
```json
{
"code": 0,
"msg": "Operation successful"
}
```
#### Success Response with Data
- **code** (number) - 0 for success.
- **msg** (string) - Success message.
- **data** (object) - Contains specific data, like user information.
#### Response Example (with data)
```json
{
"code": 0,
"msg": "Successfully retrieved",
"data": {
"userInfo": {
"_id": "user001",
"nickname": "Zhang San",
"avatar": "https://example.com/avatar.jpg"
}
}
}
```
#### List Data Response
- **code** (number) - 0 for success.
- **msg** (string) - Success message.
- **data** (object) - Contains list data with pagination information.
- **rows** (array) - The list of items.
- **total** (number) - Total number of items.
- **pageIndex** (number) - Current page index.
- **pageSize** (number) - Items per page.
- **hasMore** (boolean) - Indicates if there are more items.
#### Response Example (List Data)
```json
{
"code": 0,
"msg": "Successfully retrieved",
"data": {
"rows": [
{ "_id": "1", "title": "Title 1" },
{ "_id": "2", "title": "Title 2" }
],
"total": 100,
"pageIndex": 1,
"pageSize": 10,
"hasMore": true
}
}
```
```
--------------------------------
### 云对象权限控制配置
Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-object-development.md
此代码段展示了如何为云对象的方法配置权限。通过 `_permission` 对象,可以指定哪些方法需要登录('login')或特定的管理员权限('admin'),哪些方法是公开的([])。`_before` 函数可用于实现具体的权限验证逻辑。
```javascript
var cloudObject = {
// 权限配置
_permission: {
// 需要登录的方法
'getUserInfo': ['login'],
// 需要特定权限的方法
'deleteUser': ['admin'],
// 公开方法(无需权限)
'getPublicData': []
},
_before: async function() {
// 权限验证逻辑
let methodName = this.getMethodName();
let permissions = this._permission[methodName];
if (permissions && permissions.includes('login')) {
let { uid } = this.getClientInfo();
if (!uid) {
throw new Error('请先登录');
}
}
}
};
```
--------------------------------
### Get Temporary File URL
Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-ext-storage-basic.md
Generates a temporary, time-limited URL for accessing files, especially private ones.
```APIDOC
## POST /getTempFileURL
### Description
Generates temporary URLs for accessing files in the cloud storage.
### Method
POST
### Endpoint
/getTempFileURL
### Parameters
#### Request Body
- **fileList** (Array) - Required - A list of file identifiers (e.g., fileID, cloudPath).
- **expiresIn** (number) - Optional - The validity period for the temporary URL in seconds.
### Request Example
```json
{
"fileList": ["qiniu://test.jpg"],
"expiresIn": 3600
}
```
### Response
#### Success Response (200)
- **fileList** (Array