===============
LIBRARY RULES
===============
From library maintainers:
- Logic is a JavaScript/Python-like scripting language for business logic in enterprise applications
- Every expression must end with a comma (,) except return statements
- Conditional expressions must have both true and false branches, use null for empty branches
- Use data.fieldName to access input parameters passed to Logic scripts
- Built-in objects: entity (database ORM), sql (SQL queries), log (logging), logic (calling other Logic scripts)
- Common plugins: commonTools, dateTools, jsonTools, restTools, securityUtils, convertTools
- Database operations: entity.getById(), entity.partialSave(), entity.deleteById()
- SQL operations: sql.querySQL(), sql.execute() with parameterized queries using {data.field}
- Exception handling: try-catch blocks, throw statements with string or object
- Parameter validation: validate blocks with required/default field specifications
- Loop operations: items.each() with row, rowIndex, rowKey variables
- Lambda expressions: (params) => { return result } syntax with .apply() method
### Business Tool Plugin Example
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Demonstrates the usage of a hypothetical number generator plugin to create order and ticket numbers, followed by logging the generated order number.
```logic
// 示例:假设项目中有编号生成插件
orderNumber = numberGenerator.generateOrderNumber(),
ticketNumber = numberGenerator.generateTicketNumber(),
log.info("生成订单号: {orderNumber}"),
```
--------------------------------
### Custom Java Plugin Development and Registration
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Guides on developing custom plugins by creating Java classes, defining static methods for processing and validation, and registering them in `plugins.xml` for use in Logic.
```java
public class CustomTools {
public static String processData(String input) {
// 处理逻辑
return "processed: " + input;
}
public static boolean validateData(Object data) {
// 验证逻辑
return data != null;
}
}
```
```xml
```
```javascript
// 调用自定义插件
result = customTools.processData(data.input),
isValid = customTools.validateData(data.payload)
```
--------------------------------
### Set SystemV4 Path Environment Variable
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Guides on setting the 'SYSTEMV4_HOME' environment variable for cross-project accessibility. Includes instructions for both Linux/Mac (bash/zshrc) and Windows (system-wide or session-specific).
```bash
# Linux/Mac: Add to ~/.bashrc or ~/.zshrc
export SYSTEMV4_HOME="../systemv4"
# Or set to an absolute path
# export SYSTEMV4_HOME="/path/to/your/systemv4"
```
```cmd
# Windows: Set system environment variable (persistent)
setx SYSTEMV4_HOME "..\systemv4"
# Or set in the current project session (temporary)
set SYSTEMV4_HOME=..\systemv4
```
--------------------------------
### Order Number Generation with OrderNumberGenerator
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Demonstrates the use of the OrderNumberGenerator plugin to create unique order numbers. The example shows generating a number and then using it to create an order record.
```javascript
// 生成唯一工单号
orderNumber = OrderNumberGenerator.generate(),
log.info("生成工单号: " + orderNumber),
// 创建工单记录
orderRecord = {
f_order_no: orderNumber,
f_title: data.title,
f_description: data.description,
f_creator: securityUtils.getCurrentUserId(),
f_create_time: dateTools.format(dateTools.now(), "yyyy-MM-dd HH:mm:ss")
}
```
--------------------------------
### Code Formatting Best Practices in Logic
Source: https://github.com/junior125306/logic-support/blob/master/docs/syntax-reference.md
Provides guidance on recommended code formatting, including consistent indentation, placement of braces, and using conditional expressions for cleaner logic flow, along with examples of good and bad practices.
```Logic
// ✅ 推荐的格式
validate {
name: {
required: true,
message: "姓名不能为空"
}
},
userName = data.name,
userAge = data.age,
userAge >= 18 : (
status = "成年人",
canVote = true
), (
status = "未成年人",
canVote = false
),
return {
success: true,
data: {
name: userName,
status: status,
canVote: canVote
}
}
```
--------------------------------
### Get Current User Info with securityUtils
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Shows how to retrieve information about the currently logged-in user using the securityUtils plugin. It covers getting the user object and user ID, and using them when saving data.
```javascript
// 获取当前登录用户
currentUser = securityUtils.getCurrentUser(),
currentUserId = securityUtils.getCurrentUserId(),
// 使用用户信息
log.info("当前用户: " + currentUser.username),
// 在数据保存时记录操作者
saveData = {
f_name: data.name,
f_creator: currentUserId,
f_create_time: dateTools.format(dateTools.now(), "yyyy-MM-dd HH:mm:ss")
}
```
--------------------------------
### Plugin Development Best Practices: Parameter Validation
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Highlights the importance of validating input parameters before processing them in plugin methods. It shows an example of throwing an `IllegalArgumentException` for invalid inputs.
```java
public static String validateAndProcess(String input) {
if (input == null || input.trim().isEmpty()) {
throw new IllegalArgumentException("输入参数不能为空");
}
return input.trim().toLowerCase();
}
```
--------------------------------
### Locate systemv4 Directory (Windows)
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
A command to find the 'systemv4' directory recursively in parent directories, aiding in locating the systemv4 installation.
```cmd
# 在上级目录中查找systemv4
dir /s /b /ad ..\systemv4
```
--------------------------------
### Plugin Usage Best Practices: Parameter Validation
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Emphasizes validating parameters before invoking plugins to prevent errors. The example shows a conditional check for a URL parameter before making an HTTP request.
```javascript
// 调用插件前验证参数
commonTools.isNotEmpty(data.url) : null, (
throw "URL不能为空"
),
response = restTools.get(data.url)
```
--------------------------------
### Logging Database Operations
Source: https://github.com/junior125306/logic-support/blob/master/docs/database-operations.md
Emphasizes the importance of logging key database operations for auditing, debugging, and monitoring. Examples show logging query execution, results, and significant data modifications.
```javascript
// 记录关键数据库操作
log.info("开始查询用户列表, 部门ID: " + data.deptId),
users = sql.querySQL("getUsersByDept", sqlQuery),
log.info("查询完成, 找到用户数: " + users.length),
// 记录重要的业务操作
user = entity.getById("t_user", data.userId),
user.f_status = 0,
result = entity.partialSave("t_user", user),
log.info("禁用用户: " + user.f_name + " (ID: " + user.id + ")"),
```
--------------------------------
### Implement Read/Write Splitting with JavaScript
Source: https://github.com/junior125306/logic-support/blob/master/docs/advanced-features.md
Provides examples for implementing read/write splitting patterns using JavaScript. It defines functions to write to the master database and read from a slave database, demonstrating how to manage data consistency and performance by directing operations to appropriate data sources.
```javascript
// 写操作使用主数据库
writeToMaster = (userData) => {
return entity.partialSave("t_user", userData)
},
// 读操作使用从数据库
readFromSlave = (userId) => {
return dynamicDataSource.withDataSource("slave-db", (params) => {
return entity.getById("t_user", params.userId)
}, {userId: userId})
},
// 实际应用
newUser = {
f_name: data.name,
f_email: data.email,
f_create_time: dateTools.format(dateTools.now(), "yyyy-MM-dd HH:mm:ss")
},
// 写入主库
savedUser = writeToMaster(newUser),
log.info("用户保存成功,ID: " + savedUser.id),
// 从从库读取(可能需要等待主从同步)
setTimeout(() => {
userFromSlave = readFromSlave(savedUser.id),
log.info("从从库读取用户: " + userFromSlave.f_name)
}, 1000),
```
--------------------------------
### Secure SQL Query with Parameterization
Source: https://github.com/junior125306/logic-support/blob/master/docs/database-operations.md
Highlights the importance of using parameterized queries to prevent SQL injection vulnerabilities. The example shows the correct way to pass parameters using placeholders and contrasts it with the insecure method of direct string concatenation.
```javascript
// ✅ 正确:使用参数化查询
users = sql.querySQL("safeQuery", "
SELECT * FROM t_user
WHERE f_name LIKE '%{data.keyword}%'
AND f_status = {data.status}
"),
// ❌ 错误:直接拼接SQL(存在注入风险)
// 不要这样写!
// unsafeQuery = "SELECT * FROM t_user WHERE f_name = '" + data.name + "'",
```
--------------------------------
### HTTP Requests with restTools
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
A plugin for making HTTP requests, supporting GET, POST, PUT, and DELETE methods. It allows for custom headers, sending JSON or form data, and includes basic error handling with try-catch blocks.
```logic
// GET请求
response = restTools.get("http://api.example.com/users", null),
users = jsonTools.convertToJson(response),
// GET请求(带请求头)
headers = {"Authorization":"Bearer token"}
headersStr = "{headers}",
response = restTools.get("http://api.example.com/users", headersStr),
// POST请求(JSON数据)
requestData = {
name: data.name,
email: data.email
},
postResponse = restTools.post("http://api.example.com/users", requestData),
// POST请求(字符串数据,带请求头)
jsonStr = '{"name":"张三","age":30}',
headers = '{"Content-Type":"application/json"}',
postResponse = restTools.post("http://api.example.com/users", jsonStr, headers),
// POST表单数据
formData = "name=张三&age=30",
formResponse = restTools.postByFormData("http://api.example.com/form", formData, headers),
// PUT和DELETE请求
putResponse = restTools.put("http://api.example.com/users/1", requestData),
deleteResponse = restTools.delete("http://api.example.com/users/1", headers),
// 错误处理
try {
apiResult = restTools.get("http://external-api.com/data", null),
data = jsonTools.convertToJson(apiResult)
} catch (Exception e) {
log.error("API调用失败: {e}"),
throw "外部服务暂时不可用"
}
```
--------------------------------
### Logic语言标准结构最佳实践
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
提供了一个标准的Logic脚本结构的最佳实践示例,包括参数验证、参数获取、业务逻辑处理和返回结果的顺序。
```logic
// 1. 参数验证
validate {
userId: {
required: true,
message: "用户ID不能为空"
}
},
// 2. 获取参数
userId = data.userId,
// 3. 业务逻辑处理
user = entity.getById("t_user", userId),
user != null : null, (
throw "用户不存在"
),
// 4. 返回结果
return {
success: true,
data: user
}
```
--------------------------------
### Recommended Logic Project Structure
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Illustrates a recommended directory structure for Logic projects, emphasizing the placement of the 'systemv4' framework, individual projects, and shared resources. This structure promotes modularity and maintainability.
```text
workspace/
├── systemv4/ # SystemV4 framework
│ └── af-common/
│ ├── af-common-plugins/
│ ├── af-common-jpa/
│ └── ...
├── project1/ # Logic project 1
│ ├── src/main/resources/
│ └── ...
├── project2/ # Logic project 2
│ ├── src/main/resources/
│ └── ...
└── shared-resources/ # Shared resources
└── plugins/
```
--------------------------------
### 第一个Logic脚本示例
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
展示了一个简单的Logic脚本,包括参数验证、条件判断、日志记录和返回结果。此脚本演示了Logic语言的基本结构和常用功能。
```logic
// hello-world.logic
// 这是你的第一个Logic脚本
// 参数验证
validate {
name: {
required: true,
message: "姓名不能为空"
}
},
// 获取入参
userName = data.name,
// 简单的条件判断
userName == "世界" : (
greeting = "Hello, World!"
), (
greeting = "你好, {userName}!"
),
// 记录日志
log.info("生成问候语: {greeting}"),
// 返回结果
return {
success: true,
message: greeting,
timestamp: dateTools.getNow2()
}
```
--------------------------------
### Logic语言错误处理最佳实践
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
展示了Logic语言中错误处理的最佳实践,包括参数校验和数据库操作的异常捕获。
```logic
// 参数验证
data.name != null && data.name != "" : null, (
throw "姓名不能为空"
),
// 数据库操作错误处理
try {
result = entity.partialSave("t_user", saveData)
} catch (Exception e) {
log.error("保存用户失败: {e}"),
throw "系统错误,请稍后重试"
}
```
--------------------------------
### Logic语言表达式结束符
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
演示了Logic语言中表达式结束符(逗号)的使用规则。除了return语句,所有表达式都必须以逗号结束。
```logic
name = "张三", // ✅ 正确
age = 30, // ✅ 正确
isAdmin = true, // ✅ 正确
return result // ✅ return语句不需要逗号
```
--------------------------------
### 项目结构和跨平台路径示例
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
说明了Logic项目插件配置文件的标准位置,并提供了在Linux/Mac和Windows操作系统下访问系统级插件配置文件的路径表示方法。
```umi
your-workspace/
├── your-logic-project/ # 当前Logic项目
│ ├── src/main/resources/
│ │ ├── plugins.xml # 项目级插件
│ │ └── {module}/plugins.xml # 模块级插件
│ └── ...
└── systemv4/ # SystemV4框架 (同级目录)
└── af-common/
├── af-common-plugins/
│ └── src/main/resources/plugins/plugins.xml
├── af-common-jpa/
│ └── src/main/resources/jpaSupportForLogic/plugins.xml
└── ...
# 不同操作系统的路径表示:
# Linux/Mac: ../systemv4/af-common/**/plugins.xml
# Windows: ..\systemv4\af-common\**\plugins.xml
```
--------------------------------
### Logic语言循环操作示例
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
展示了Logic语言中如何进行循环操作,包括遍历数组和范围循环。
```logic
// 遍历数组
items = [1, 2, 3, 4, 5],
items.each(
log.info("当前元素: {row}"),
log.info("索引: {rowIndex}")
),
// 范围循环
(1, 10).each(
log.info("数字: {row}")
),
```
--------------------------------
### Logic语言数据库操作示例
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
提供了Logic语言中进行数据库操作的示例,包括查询、保存/更新数据以及执行SQL查询。
```logic
// 查询用户信息
user = entity.getById("t_user", data.userId),
// 保存或更新数据
saveData = {
f_name: data.name,
f_age: data.age,
f_status: 1
},
result = entity.partialSave("t_user", saveData),
// 执行SQL查询
users = sql.querySQL("getUserList", "
SELECT * FROM t_user
WHERE f_status = 1
AND f_age > {data.minAge}
"),
```
--------------------------------
### Logic语言日志记录最佳实践
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
演示了在Logic脚本中进行日志记录的最佳实践,包括记录关键步骤、业务逻辑和操作结果。
```logic
// 记录关键步骤
log.info("开始处理用户注册, userId: {data.userId}"),
// 记录业务逻辑
log.info("用户验证通过, 开始保存数据"),
// 记录结果
log.info("用户注册成功, 生成ID: {result.id}"),
```
--------------------------------
### Asynchronous HTTP Requests with restAsyncTools
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Enables asynchronous HTTP requests, allowing operations to continue without blocking the main thread. It uses callback functions to handle responses from asynchronous GET and POST requests.
```logic
// 异步GET请求
callback = (response) => {
log.info("异步请求完成: {response}"),
// 处理响应数据
result = jsonTools.convertToJson(response)
},
restAsyncTools.getAsync("http://api.example.com/async-data", callback),
// 异步POST请求
asyncData = {
message: "异步数据",
timestamp: dateTools.getNow2()
},
restAsyncTools.postAsync("http://api.example.com/async", asyncData, callback)
```
--------------------------------
### Logic语言数据类型示例
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
展示了Logic语言中支持的各种数据类型,包括数字、字符串、布尔值、数组和对象。
```logic
// 数字
count = 10,
price = 15.99,
// 字符串
name = "张三",
message = "欢迎使用Logic",
// 布尔值
isActive = true,
isDeleted = false,
// 数组
numbers = [1, 2, 3, 4, 5],
names = ["张三", "李四", "王五"],
// 对象
user = {
name: "张三",
age: 30,
email: "zhangsan@example.com"
},
```
--------------------------------
### Find systemv4 plugins.xml in Windows
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Searches for 'plugins.xml' files specifically within the 'systemv4' directory structure on Windows. It uses 'dir' for recursive searching.
```cmd
# View systemv4 system plugins
dir /s /b ..\systemv4\*plugins.xml
# Or use environment variable
set SYSTEMV4_HOME=..\systemv4
dir /s /b %SYSTEMV4_HOME%\*plugins.xml
```
--------------------------------
### SQL注入防护 - 避免字符串拼接
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
警告不要在Logic中使用字符串拼接来构建SQL查询,并指出了在Logic中处理字符串拼接的正确方式。
```logic
// ❌ 避免字符串拼接
// logic中字符串拼接只能使用 参数处理 "SELECT * FROM t_user WHERE name = '{}{data.name}'"
// badQuery = "SELECT * FROM t_user WHERE name = '" + data.name + "'",
```
--------------------------------
### Find Plugins Configuration (Linux/Mac)
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Commands to locate all plugin configuration files named 'plugins.xml' within the project, specifically targeting those under 'resources' directories, and to view systemv4 system plugins.
```bash
# 查找项目中的所有插件配置
find . -name "plugins.xml" -path "*/resources/*"
# 查看systemv4系统插件
find ../systemv4 -name "plugins.xml" -type f 2>/dev/null
```
--------------------------------
### Find Plugins Configuration (Windows)
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Commands to find all 'plugins.xml' files recursively in the current directory and its subdirectories, with specific instructions for locating systemv4 system plugins using both direct path and environment variables.
```cmd
# 查找项目中的所有插件配置
dir /s /b *plugins.xml | findstr resources
# 查看systemv4系统插件
dir /s /b ..\systemv4\*plugins.xml
# 或者使用环境变量
set SYSTEMV4_HOME=..\systemv4
dir /s /b %SYSTEMV4_HOME%\*plugins.xml
```
--------------------------------
### IDE Configuration for SystemV4
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Details how to configure IDEs like VS Code and IntelliJ IDEA to recognize the SystemV4 path. This involves adding settings to 'settings.json' or project-specific path variables.
```json
// VS Code: Add to .vscode/settings.json
{
"systemv4.home": "../systemv4",
"files.associations": {
"*.logic": "javascript"
}
}
```
```APIDOC
IntelliJ IDEA:
Add path variable in project settings:
Name: SYSTEMV4_HOME
Value: ../systemv4
```
--------------------------------
### Find systemv4 plugins.xml in Linux/Mac
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Searches for 'plugins.xml' files specifically within the 'systemv4' directory structure on Linux and macOS. It redirects errors to null to keep the output clean.
```bash
# View systemv4 system plugins
find ../systemv4 -name "plugins.xml" -type f 2>/dev/null
# Or use environment variable
export SYSTEMV4_HOME="../systemv4"
find $SYSTEMV4_HOME -name "plugins.xml" -type f
```
--------------------------------
### Plugin Development Best Practices: Exception Handling
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Details best practices for exception handling within plugins, emphasizing the use of try-catch blocks to wrap business logic, log errors, and return user-friendly exceptions.
```java
public static String safeOperation(String input) {
try {
// 业务逻辑
return processInput(input);
} catch (Exception e) {
// 记录日志并返回友好信息
logger.error("处理失败", e);
throw new RuntimeException("操作失败:" + e.getMessage());
}
}
```
--------------------------------
### Logic语言异常处理示例
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
演示了Logic语言中的异常处理机制,包括使用try-catch块捕获异常并进行处理,以及如何抛出自定义异常。
```logic
try {
// 可能出错的代码
result = entity.getById("t_user", data.userId),
assert result != null
} catch (Exception e) {
log.error("查询用户失败: {e}"),
throw {
msg: "用户不存在",
status: 404
}
}
```
--------------------------------
### SQL注入防护 - 参数化查询
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
强调了在Logic中使用参数化查询来防止SQL注入攻击的重要性。
```logic
// ✅ 使用参数化查询
users = sql.querySQL("safe", "SELECT * FROM t_user WHERE name = {data.name}"),
```
--------------------------------
### 数据库优化 - 避免循环中的数据库操作
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
展示了如何通过JOIN查询来避免在循环中执行多次数据库操作,从而优化性能。
```logic
// ✅ 避免循环中的数据库操作
usersWithProfiles = sql.querySQL("joinQuery", "
SELECT u.*, p.avatar FROM t_user u
LEFT JOIN t_profile p ON u.id = p.user_id
"),
```
--------------------------------
### 数据验证 - 输入验证
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
展示了Logic中如何进行输入数据的验证,包括必填项和长度限制。
```logic
// 输入验证
data.userId != null && data.userId != "" : null, (throw "用户ID不能为空"),
data.userId.length <= 32 : null, (throw "用户ID长度超限"),
```
--------------------------------
### Find plugins.xml in Linux/Mac
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Locates all 'plugins.xml' files within project resources on Linux and macOS systems using the 'find' command. It searches recursively from the current directory.
```bash
find . -name "plugins.xml" -path "*/resources/*"
```
--------------------------------
### 同步调用Logic
Source: https://github.com/junior125306/logic-support/blob/master/docs/advanced-features.md
展示了如何使用`logic.run()`方法同步调用另一个Logic。这对于顺序执行任务非常有用。
```logic
// 调用其他Logic
result = logic.run("targetLogicName", parameters),
// 示例
userInfo = logic.run("getUserById", {userId: data.userId}),
```
--------------------------------
### Plugin Usage Best Practices: Performance Considerations
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Advises against calling performance-intensive plugins repeatedly within loops. It suggests using batch processing or caching mechanisms for better efficiency.
```javascript
// 避免在循环中频繁调用耗时插件
items = data.items,
processedItems = [],
items.each(
// ❌ 避免:在循环中调用HTTP请求
// result = restTools.get("http://api.com/process/" + row.id),
// ✅ 推荐:批量处理或缓存结果
processedItems.push({
id: row.id,
processed: true,
timestamp: dateTools.now()
})
)
```
--------------------------------
### Find plugins.xml in Windows
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Locates all 'plugins.xml' files within project resources on Windows systems using the 'dir' and 'findstr' commands. It performs a recursive search.
```cmd
# Find all project plugins configurations
dir /s /b *plugins.xml | findstr resources
```
--------------------------------
### 条件判断优化
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
演示了如何通过将简单条件放在前面来优化条件判断的执行效率。
```logic
// ✅ 简单条件在前
(data.name != null && data.name != "") && data.age > 18 : (
// 处理逻辑
), null,
```
--------------------------------
### Logic语言参数访问
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
演示了如何在Logic脚本中通过 `data.fieldName` 的方式访问传入的参数。
```logic
// 获取传入的参数
userId = data.userId,
userName = data.userName,
userAge = data.age,
```
--------------------------------
### 异步调用Logic
Source: https://github.com/junior125306/logic-support/blob/master/docs/advanced-features.md
演示了如何使用`logic.runAsync()`进行异步调用,并使用`.thenAccept()`和`.exceptionally()`处理结果和异常。适用于需要并行处理或避免阻塞的操作。
```logic
// 异步调用Logic
future = logic.runAsync("processDataAsync", {
data: largeDataSet
}),
// 回调处理函数
handleAsyncResult = (result) => {
log.info("异步处理完成: " + result.status)
},
handleAsyncError = (result) => {
log.info("异步处理失败: " + result)
},
future.thenAccept(handleAsyncResult).exceptionally(handleAsyncError)
```
--------------------------------
### Plugin Development Best Practices: Method Design
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Recommends best practices for designing plugin methods, favoring static methods with simple parameters and specific return types. It advises against complex object parameters due to potential conversion issues.
```java
// ✅ 推荐:静态方法,简单参数
public static String formatName(String firstName, String lastName) {
return firstName + " " + lastName;
}
// ✅ 推荐:返回具体类型
public static boolean isValidEmail(String email) {
return email != null && email.contains("@");
}
// ❌ 避免:复杂对象参数(Logic转换困难)
public static void complexMethod(ComplexObject obj) {
// 避免这种设计
}
```
--------------------------------
### Configure Data Sources in XML
Source: https://github.com/junior125306/logic-support/blob/master/docs/advanced-features.md
Demonstrates how to configure different data sources within the 'logic.xml' file. Each configuration entry maps an alias to a specific logic path and specifies the target data source, enabling multi-data source operations.
```xml
```
--------------------------------
### Dynamic Data Source Switching
Source: https://github.com/junior125306/logic-support/blob/master/docs/database-operations.md
Explains how to manage and switch between different data sources at runtime. This is useful for scenarios like read-write splitting or accessing different databases for specific operations.
```javascript
// 在Logic注册时指定数据源
//
// 运行时动态切换数据源
dynamicDataSource.withDataSource("readonly-db", (data) => {
// 在只读数据库中执行查询
users = sql.querySQL("heavyQuery", "
SELECT * FROM t_user u
LEFT JOIN t_department d ON u.f_dept_id = d.id
WHERE u.f_create_time >= '{data.startDate}'
ORDER BY u.f_create_time DESC
")
}, {
startDate: data.startDate
}),
```
--------------------------------
### 常见模式 - 条件处理模式
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
演示了在Logic中如何处理多个条件分支,根据不同条件执行不同的逻辑。
```logic
// 多条件判断
status = data.status,
role = data.role,
status == "active" && role == "admin" : (
// 管理员处理
result = processAsAdmin()
), status == "active" : (
// 普通用户处理
result = processAsUser()
), (
// 异常处理
throw "用户状态异常"
)
```
--------------------------------
### Plugin Usage Best Practices: Logging
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Recommends using logging statements to track important plugin calls and their outcomes. This helps in monitoring and debugging application flow.
```javascript
// 记录重要插件调用
log.info("开始调用外部API: " + apiUrl),
response = restTools.get(apiUrl),
log.info("API调用完成,响应长度: " + response.length)
```
--------------------------------
### File Saving with FileSaveTools
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Illustrates how to save uploaded file content to the file system using the FileSaveTools plugin. It shows saving the file and then recording its metadata.
```javascript
// 保存上传的文件
fileData = data.fileContent,
fileName = data.fileName,
savedPath = FileSaveTools.saveFile(fileData),
log.info("文件保存路径: " + savedPath),
// 保存并记录文件信息
fileRecord = {
f_original_name: fileName,
f_save_path: savedPath,
f_file_size: fileData.length,
f_upload_time: dateTools.format(dateTools.now(), "yyyy-MM-dd HH:mm:ss"),
f_uploader: securityUtils.getCurrentUserId()
}
```
--------------------------------
### 日志级别使用
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
展示了Logic中不同日志级别(info, error, debug, warn)的使用场景。
```logic
// 关键业务操作
log.info("用户登录: {user.name}"),
// 错误信息
log.error("数据保存失败: {e}"),
// 调试信息
log.debug("处理参数: {data}"),
// 警告信息
log.warn("用户权限不足: {user.id}"),
```
--------------------------------
### 常见模式 - 批量处理模式
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
展示了Logic中处理批量数据的一般模式,包括错误收集。
```logic
items = data.items,
results = [],
errors = [],
items.each(
try {
result = entity.partialSave("t_table", row),
results.push(result)
} catch (Exception e) {
errors.push({item: row, error: e})
}
),
return {
success: errors.length == 0,
results: results,
errors: errors
}
```
--------------------------------
### 标准代码结构
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
展示了Logic代码的标准结构,包括参数验证、参数获取、业务逻辑验证、核心业务处理和返回结果。
```logic
// 1. 参数验证
validate {
userId: {
required: true,
message: "用户ID不能为空"
}
},
// 2. 参数获取
userId = data.userId,
currentTime = dateTools.getNow2(),
// 3. 业务逻辑验证
userId != null && userId != "" : null, (
throw "用户ID不能为空"
),
// 4. 核心业务处理
user = entity.getById("t_user", userId),
user != null : null, (
throw "用户不存在"
),
// 5. 返回结果
return {
success: true,
data: user
}
```
--------------------------------
### SHA1 Hashing with sha1Tools
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Demonstrates how to generate SHA1 hash values for strings and file content using the sha1Tools plugin. This is useful for data integrity checks.
```javascript
// 生成哈希值
inputData = data.username + data.email,
hashValue = sha1Tools.hash(inputData),
log.info("哈希值: " + hashValue),
// 文件完整性校验
fileContent = data.fileData,
fileHash = sha1Tools.hash(fileContent)
```
--------------------------------
### Logic语言条件表达式
Source: https://github.com/junior125306/logic-support/blob/master/docs/getting-started.md
展示了Logic语言中条件表达式的正确写法,强调了必须包含true和false两个分支,即使false分支为空也需写为null。
```logic
// ✅ 正确的条件表达式
age > 18 : (
status = "成年人"
), (
status = "未成年人"
),
// ✅ 空的false分支也要写null
isVip : (
discount = 0.8
), null,
```
--------------------------------
### 范围循环
Source: https://github.com/junior125306/logic-support/blob/master/docs/syntax-reference.md
展示了如何对一个数字范围进行循环。
```logic
(1, 10).each(
log.info("数字: {row}")
),
```
--------------------------------
### commonTools - 通用工具类方法
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
提供了commonTools插件中各种通用功能的用法示例,包括UUID生成、MD5加密、随机数生成、数字和字符串判断、精确数学运算等。
```logic
// UUID生成(标准带分隔符)
uniqueId = commonTools.getUUID(),
// UUID生成(简化版不带分隔符)
simpleUUID = commonTools.getUUID(true),
// MD5加密
password = commonTools.md5(data.password),
// MD5加密(带盐值)
securePassword = commonTools.md5(data.password, "salt123"),
// 随机数生成
randomNum = commonTools.getRandomNumber(1, 100),
// 数字判断
isNum = commonTools.isNumeric(data.input),
// 字符串操作
isContained = commonTools.isContains(data.text, "search"),
parts = commonTools.split(data.text, ","),
// 精确数学运算
sum = commonTools.add(data.num1, data.num2),
difference = commonTools.sub(data.num1, data.num2),
product = commonTools.mul(data.num1, data.num2),
quotient = commonTools.div(data.num1, data.num2),
// 示例用法
orderId = commonTools.getUUID(),
log.info("生成订单ID: {orderId}"),
```
--------------------------------
### 数据库优化 - 参数化查询
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
演示了在Logic中如何使用参数化查询来提高数据库操作的安全性与效率。
```logic
// ✅ 使用参数化查询
users = sql.querySQL("query", "SELECT * FROM t_user WHERE id = {data.id}"),
```
--------------------------------
### 数据验证 - 权限检查
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
演示了在Logic中如何进行权限检查,确保只有授权用户才能执行特定操作。
```logic
// 权限检查
currentUser.role == "admin" : null, (throw "权限不足"),
```
--------------------------------
### Find systemv4 directory in Linux/Mac
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Locates the 'systemv4' directory by searching parent directories on Linux and macOS. This is useful when the exact path is unknown.
```bash
# Find systemv4 in parent directories
find .. -name "systemv4" -type d 2>/dev/null
```
--------------------------------
### 远程调用Logic
Source: https://github.com/junior125306/logic-support/blob/master/docs/advanced-features.md
展示了如何使用`logic.remoteRun()`调用远程服务的Logic。这对于微服务架构或分布式系统集成非常重要。
```logic
// 调用远程服务的Logic
remoteResult = logic.remoteRun("userService", "getUserProfile", {
userId: data.userId
}),
```
--------------------------------
### Find systemv4 directory in Windows
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Locates the 'systemv4' directory by searching parent directories on Windows. This is useful when the exact path is unknown.
```cmd
# Find systemv4 in parent directories
dir /s /b /ad ..\systemv4
```
--------------------------------
### 执行更新SQL
Source: https://github.com/junior125306/logic-support/blob/master/docs/database-operations.md
使用`sql.execute`执行SQL更新或删除语句。支持批量更新操作和条件删除。
```logic
sql.execute("updateUserStatus", "
UPDATE t_user
SET f_status = {data.newStatus},
f_update_time = '{dateTools.getNow2()}',
f_updater = {securityUtils.getCurrentUserId()}
WHERE f_dept_id = {data.deptId}
AND f_status = {data.oldStatus}
")
sql.execute("deleteInactiveUsers", "
DELETE FROM t_user
WHERE f_status = 0
AND f_delete_time < '{data.beforeDate}'
")
```
--------------------------------
### 异常处理
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
展示了Logic中`try-catch`块的使用,用于捕获和处理潜在的异常,并进行日志记录。
```logic
try {
user = entity.getById("t_user", data.userId),
result = entity.partialSave("t_user", updateData)
} catch (Exception e) {
log.error("操作失败: " + e),
throw "系统错误,请稍后重试"
}
```
--------------------------------
### 插件注册XML配置示例
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
展示了Logic插件在XML配置文件中注册的格式,包括如何为插件指定别名(alias)和对应的Java类全限定名(class)。
```xml
```
--------------------------------
### 常见模式 - 标准CRUD模式
Source: https://github.com/junior125306/logic-support/blob/master/docs/best-practices.md
提供了一个标准的CRUD(创建、读取、更新、删除)操作模式在Logic中的实现。
```logic
// 标准CRUD模式
validate {id: {required: true}},
id = data.id,
record = entity.getById("t_table", id),
record != null : null, (throw "记录不存在"),
result = entity.partialSave("t_table", updateData),
return {success: true, data: result}
```
--------------------------------
### Logic 插件调用示例
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
展示了在Logic脚本中调用已注册插件的语法和基本示例,包括获取当前时间和生成UUID。
```logic
// Logic中调用插件的语法
result = pluginName.methodName(param1, param2),
// 示例:获取当前时间
currentTime = dateTools.getNow(),
// 示例:获取一个用"-"分隔的UUID
UUID = commonTools.getUUID(data.name),
```
--------------------------------
### JavaScript Plugin Debugging Techniques
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Provides essential JavaScript snippets for debugging Logic plugins. It covers logging variable types and values, handling potential method errors, and validating input parameter types.
```javascript
// 1. Log plugin return value type and content
result = dateTools.now();
log.info("dateTools.now() return type: " + typeof(result));
log.info("dateTools.now() return value: " + result);
// 2. Test if plugin method exists
try {
testResult = unknownPlugin.unknownMethod();
log.info("Method call successful")
} catch (Exception e) {
log.error("Method does not exist or call failed: " + e)
}
// 3. Parameter type validation
log.info("Input parameter type: " + typeof(data.input));
result = customTools.processData(data.input);
```
--------------------------------
### 基本 Logic 结构
Source: https://github.com/junior125306/logic-support/blob/master/docs/syntax-reference.md
展示了一个标准的 Logic 代码结构,包括参数验证、参数获取、业务逻辑和结果返回。
```logic
// 1. 参数验证
validate {
userId: {
required: true,
message: "用户ID不能为空"
}
},
// 2. 参数获取
userId = data.userId,
// 3. 业务逻辑
user = entity.getById("t_user", userId),
user != null : null, (
throw "用户不存在"
),
// 4. 返回结果
return {
success: true,
data: user
}
```
--------------------------------
### Plugin Usage Best Practices: Error Handling
Source: https://github.com/junior125306/logic-support/blob/master/docs/plugin-system.md
Recommends wrapping plugin calls within try-catch blocks to gracefully handle potential exceptions during external API calls or plugin operations. It suggests logging errors and throwing custom messages.
```javascript
// 包装插件调用在try-catch中
try {
result = restTools.get("http://external-api.com/data"),
processedData = jsonTools.fromJson(result)
} catch (Exception e) {
log.error("插件调用失败: " + e),
throw "外部服务调用失败"
}
```
--------------------------------
### 基本条件表达式
Source: https://github.com/junior125306/logic-support/blob/master/docs/syntax-reference.md
展示了 Logic 语言中条件表达式的基本格式,包括真假分支和空分支的处理。
```logic
age > 18 : (
status = "成年人"
), (
status = "未成年人"
),
// 空分支
isVip : (
discount = 0.8
), null,
```
--------------------------------
### Readability Improvement Best Practices in Logic
Source: https://github.com/junior125306/logic-support/blob/master/docs/syntax-reference.md
Offers tips for enhancing code readability in Logic, emphasizing the use of meaningful variable names and adding comments to explain complex logic or business rules, making the code easier to understand and maintain.
```Logic
// 使用有意义的变量名
currentUser = data.user,
isUserActive = currentUser.status == 1,
hasPermission = currentUser.role == "admin",
// 添加注释说明复杂逻辑
// 检查用户权限:必须是激活的管理员用户
isUserActive && hasPermission : (
access = "granted"
), (
access = "denied"
),
```