### Access Test Clients in Go Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Provides Go code examples for retrieving pre-configured test clients for different OAuth flows, such as authorization code, PKCE, and client credentials. ```go // Get confidential client for authorization code flow confidentialClient := testClients[0] // Get public client for PKCE flow publicClient := testClients[1] // Get client credentials client credentialsClient := testClients[2] ``` -------------------------------- ### Setup OAuth Test Environment Function Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Creates a complete OAuth test environment, including a configured OAuth service, primary and cache stores, pre-loaded test data, and returns a cleanup function. It supports MongoDB and Badger stores with automatic fallback. ```go func setupOAuthTestEnvironment(t *testing.T) (*Service, store.Store, store.Store, func()) { // Creates complete OAuth test environment with: // - Configured OAuth service with all features enabled // - Primary store (MongoDB preferred, Badger fallback) // - Cache store (LRU cache) // - Pre-loaded test clients and users // - Cleanup function for proper teardown } ``` -------------------------------- ### Install Attachment Package Source: https://github.com/yaoapp/yao/blob/main/neo/attachment/README.md Installs the Go attachment package using the go get command. This is the standard way to add external libraries to a Go project. ```bash go get github.com/yaoapp/yao/neo/attachment ``` -------------------------------- ### Public Endpoint Python Example Source: https://github.com/yaoapp/yao/blob/main/openapi/hello/README.md Illustrates how to make a GET request to the public endpoint using the Python requests library. ```python import requests # Public endpoint response = requests.get('/v1/helloworld/public') print(response.json()) ``` -------------------------------- ### Run All OAuth Tests Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Executes all Go tests for the OAuth service with verbose output and a 60-second timeout. ```bash cd $YAO_SOURCE_ROOT go test -v ./openapi/oauth -timeout 60s ``` -------------------------------- ### Access Test Users in Go Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Provides Go code examples for retrieving pre-configured test users with various roles and features, including admin, regular, 2FA-enabled, and API-scoped users. ```go // Get admin user for administrative testing adminUser := testUsers[0] // Get regular user for standard flow testing regularUser := testUsers[1] // Get user with specific features secureUser := testUsers[6] // 2FA enabled apiUser := testUsers[7] // API scopes ``` -------------------------------- ### Complete Workflow Example Source: https://github.com/yaoapp/yao/blob/main/widgets/table/README.md Demonstrates a typical workflow involving table operations: getting settings, searching records, creating, updating, finding, deleting, and exporting data. Each step uses the Process function with specific table operations. ```typescript // Get table settings const settings = Process("yao.table.Setting", "pet"); // Search for records const results = Process( "yao.table.Search", "pet", { wheres: [{ column: "status", value: "checked" }], }, 1, 10 ); // Create a new record const id = Process("yao.table.Create", "pet", { name: "New Pet", type: "cat", status: "checked", doctor_id: 1, }); // Update the record Process("yao.table.Update", "pet", id, { name: "Updated Pet Name", }); // Find the record const record = Process("yao.table.Find", "pet", id); // Delete the record Process("yao.table.Delete", "pet", id); // Export data to Excel const filePath = Process("yao.table.Export", "pet", null, 100); ``` -------------------------------- ### Public Endpoint cURL Example Source: https://github.com/yaoapp/yao/blob/main/openapi/hello/README.md Demonstrates how to test basic server connectivity using the public endpoint via a cURL command. ```bash curl -X GET "/v1/helloworld/public" ``` -------------------------------- ### Integration Testing OAuth Flow Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Provides an example of integration testing for a complete OAuth flow. It sets up the test environment and then utilizes specific pre-configured test clients and users (e.g., confidential client, admin user) to simulate real-world interactions and verify end-to-end functionality. ```go func TestOAuthFlow(t *testing.T) { service, _, _, cleanup := setupOAuthTestEnvironment(t) defer cleanup() // Use testClients[0] for confidential client testing // Use testUsers[0] for admin user testing // Complete OAuth flows with real data } ``` -------------------------------- ### Bash Example: Bearer Token Authentication Source: https://github.com/yaoapp/yao/blob/main/openapi/README.md Demonstrates how to authenticate API requests using a Bearer token, typically obtained via an OAuth 2.0 flow. This example uses curl to make a GET request to a DSL list endpoint. ```bash curl -X GET "/v1/dsl/list/model" \ -H "Authorization: Bearer {access_token}" ``` -------------------------------- ### Yao Workflow Example (TypeScript) Source: https://github.com/yaoapp/yao/blob/main/utils/README.md Demonstrates a comprehensive workflow using various utility functions provided by the Yao application. This example showcases generating UUIDs, getting timestamps, creating file paths, printing colored output, parsing URLs, handling errors, generating JWT tokens, and using flow control for conditional processing. ```typescript // Generate a UUID const id = Process("utils.str.UUID"); // Get current timestamp const timestamp = Process("utils.now.Timestamp"); // Create a path const path = Process("utils.str.JoinPath", "data", id, "file.txt"); // Print colored info Process("utils.fmt.ColorPrintf", "blue", "Processing request with ID: %s", id); // Parse URL parameters const url = "https://example.com/api?token=123&id=" + id; const parsedUrl = Process("utils.url.ParseURL", url); // Handle errors conditionally if (!parsedUrl.query.token) { Process("utils.throw.Unauthorized", "Missing token"); } // Generate a JWT token const token = Process( "utils.jwt.Make", 1, { id: id, timestamp: timestamp }, { timeout: 3600, subject: "API Access", } ); // Use flow control for conditional processing Process( "utils.flow.Case", { when: [{ operator: "gt", value: 0, field: "status" }], process: "utils.flow.Return", args: [{ token: token.token, path: path }], }, { when: [{ operator: "eq", value: 0, field: "status" }], process: "utils.throw.BadRequest", args: ["Invalid status"], } ); // Get current date and time const now = Process("utils.now.DateTime"); // Print a success message Process("utils.fmt.ColorPrintf", "green", "Operation completed at %s", now); ``` -------------------------------- ### Quick Example: Open, Write, Save, Close Excel Source: https://github.com/yaoapp/yao/blob/main/excel/README.md A complete example demonstrating the basic workflow of opening an Excel file, performing operations, saving changes, and crucially, closing the file handle to prevent resource leaks. ```typescript // Open an Excel file const h = Process("excel.Open", "data.xlsx", true); // Perform operations const sheets = Process("excel.Sheets", h); Process("excel.write.Cell", h, sheets[0], "A1", "Hello World"); Process("excel.Save", h); // IMPORTANT: Always close the handle when done Process("excel.Close", h); ``` -------------------------------- ### Public Endpoint JavaScript Example Source: https://github.com/yaoapp/yao/blob/main/openapi/hello/README.md Demonstrates how to fetch data from the public endpoint using the browser's Fetch API in JavaScript. ```javascript // Public endpoint fetch("/v1/helloworld/public") .then((response) => response.json()) .then((data) => console.log(data)); ``` -------------------------------- ### Protected Endpoint cURL Example (Authentication Flow) Source: https://github.com/yaoapp/yao/blob/main/openapi/hello/README.md Illustrates the process of obtaining an OAuth token and then using it to access the protected endpoint with cURL. ```bash # First, obtain an access token curl -X POST "/v1/oauth/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials&client_id=your_client_id&client_secret=your_client_secret" # Then use the token to access the protected endpoint curl -X GET "/v1/helloworld/protected" \ -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..." ``` -------------------------------- ### YAML Configuration for Redis Store Source: https://github.com/yaoapp/yao/blob/main/neo/store/README.md Example YAML configuration for setting up the YAO Neo Store to use Redis as a backend. ```yaml neo: store: connector: "redis" prefix: "neo:" ttl: 3600 ``` -------------------------------- ### Source Environment Configuration Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Sources the local environment configuration script. This is a prerequisite for setting up the test environment, ensuring necessary variables and paths are available. ```bash # Source the environment configuration source $YAO_SOURCE_ROOT/env.local.sh ``` -------------------------------- ### Example Workflow: Updating and Reloading a DSL Source: https://github.com/yaoapp/yao/blob/main/openapi/dsl/README.md Illustrates the process of updating an existing DSL resource and then reloading it to apply the changes. ```Bash # 1. Update the DSL: curl -X PUT "/v1/dsl/update/model" \ -H "Authorization: Bearer {token}" \ -H "Content-Type: application/json" \ -d '{ "id": "product", "source": "{ \"name\": \"product\", \"label\": \"Product Model\", \"table\": { \"name\": \"products\" }, \"columns\": [{ \"name\": \"id\", \"type\": \"ID\" }, { \"name\": \"name\", \"type\": \"string\" }] }"' # 2. Reload to apply changes: curl -X POST "/v1/dsl/reload/model" \ -H "Authorization: Bearer {token}" \ -H "Content-Type: application/json" \ -d '{ "id": "product", "store": "file" }' ``` -------------------------------- ### YAML Configuration for Database Store Source: https://github.com/yaoapp/yao/blob/main/neo/store/README.md Example YAML configuration for setting up the YAO Neo Store to use a database backend (e.g., MySQL). ```yaml # neo.yml neo: store: connector: "mysql" # or "postgresql", "sqlite", "default" prefix: "neo_" # Table prefix max_size: 100 # Maximum chat history size ttl: 7200 # 2 hours TTL for conversations user_field: "user_id" # User identification field ``` -------------------------------- ### Example Workflow: Creating a New Model Source: https://github.com/yaoapp/yao/blob/main/openapi/dsl/README.md Demonstrates a typical workflow for creating a new DSL model, involving validation of the source code followed by the creation request. ```Bash # 1. Validate the source first: curl -X POST "/v1/dsl/validate/model" \ -H "Authorization: Bearer {token}" \ -H "Content-Type: application/json" \ -d '{ "source": "{ \"name\": \"product\", \"table\": { \"name\": \"products\" }, \"columns\": [{ \"name\": \"id\", \"type\": \"ID\" }] }"' # 2. Create the model: curl -X POST "/v1/dsl/create/model" \ -H "Authorization: Bearer {token}" \ -H "Content-Type: application/json" \ -d '{ "id": "product", "source": "{ \"name\": \"product\", \"table\": { \"name\": \"products\" }, \"columns\": [{ \"name\": \"id\", \"type\": \"ID\" }] }", "store": "file" }' # 3. Verify it was created: curl -X GET "/v1/dsl/inspect/model/product" \ -H "Authorization: Bearer {token}" ``` -------------------------------- ### YAML Configuration for MongoDB Store Source: https://github.com/yaoapp/yao/blob/main/neo/store/README.md Example YAML configuration for setting up the YAO Neo Store to use MongoDB as a backend. ```yaml neo: store: connector: "mongodb" prefix: "neo_" ttl: 7200 ``` -------------------------------- ### Run OAuth Tests with Coverage Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Executes all Go tests for the OAuth service with verbose output, enabling code coverage reporting and a 60-second timeout. ```bash cd $YAO_SOURCE_ROOT go test -v ./openapi/oauth -cover -timeout 60s ``` -------------------------------- ### Authentication Testing cURL Example Source: https://github.com/yaoapp/yao/blob/main/openapi/hello/README.md Provides a bash script to test the OAuth authentication flow by obtaining a token and then accessing the protected endpoint. ```bash # Test authentication flow TOKEN=$(curl -s -X POST "/v1/oauth/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET" \ | jq -r '.access_token') curl -X GET "/v1/helloworld/protected" \ -H "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Protected Endpoint Python Example Source: https://github.com/yaoapp/yao/blob/main/openapi/hello/README.md Demonstrates how to access the protected endpoint in Python using the requests library, including setting the Authorization header with a bearer token. ```python # Protected endpoint headers = {'Authorization': f'Bearer {access_token}'} response = requests.get('/v1/helloworld/protected', headers=headers) print(response.json()) ``` -------------------------------- ### MongoDB Environment Variables Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Defines environment variables required for connecting to a MongoDB instance during full testing. Falls back to Badger if not provided. ```bash # MongoDB connection (optional, will fallback to Badger) export MONGO_TEST_HOST=localhost export MONGO_TEST_PORT=27017 export MONGO_TEST_USER=test export MONGO_TEST_PASS=test ``` -------------------------------- ### Run Specific OAuth Test Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Executes a specific Go test case for the OAuth service, targeting the 'TestNewService' function with verbose output and a 30-second timeout. ```bash cd $YAO_SOURCE_ROOT go test -v ./openapi/oauth -run TestNewService -timeout 30s ``` -------------------------------- ### Protected Endpoint JavaScript Example Source: https://github.com/yaoapp/yao/blob/main/openapi/hello/README.md Shows how to access the protected endpoint in JavaScript using the Fetch API, including passing the OAuth bearer token in the Authorization header. ```javascript // Protected endpoint const token = localStorage.getItem("access_token"); fetch("/v1/helloworld/protected", { headers: { Authorization: `Bearer ${token}`, }, }) .then((response) => response.json()) .then((data) => console.log(data)); ``` -------------------------------- ### Health Check cURL Example Source: https://github.com/yaoapp/yao/blob/main/openapi/hello/README.md Shows a simple cURL command to perform a health check on the service, redirecting output to null for silent operation. ```bash curl -f "/v1/helloworld/public" > /dev/null 2>&1 && echo "Service is healthy" || echo "Service is down" ``` -------------------------------- ### Assistant Management API Source: https://github.com/yaoapp/yao/blob/main/neo/README.md Provides endpoints for listing, retrieving, creating, updating, and deleting assistants. Includes functionality to get assistant tags and execute assistant APIs. ```APIDOC GET /assistants Description: Get a paginated list of available assistants. Parameters: - page (optional): Page number (default: 1) - pagesize (optional): Items per page (default: 20) - tags (optional): Comma-separated list of tags - keywords (optional): Search keywords - connector (optional): Connector name filter - select (optional): Comma-separated fields to select - built_in (optional): Filter built-in assistants ('true'/'false'/'1'/'0') - mentionable (optional): Filter mentionable assistants ('true'/'false'/'1'/'0') - automated (optional): Filter automated assistants ('true'/'false'/'1'/'0') - assistant_id (optional): Specific assistant ID - locale (optional): Locale code (default: 'en-us') Example: curl -X GET 'http://localhost:5099/api/__yao/neo/assistants?page=1&pagesize=20&tags=tag1,tag2&token=xxx' GET /assistants/tags Description: Get all available assistant tags. Parameters: - locale (optional): Locale code (default: 'en-us') Example: curl -X GET 'http://localhost:5099/api/__yao/neo/assistants/tags?token=xxx' GET /assistants/:id Description: Get detailed information about a specific assistant. Parameters: - locale (optional): Locale code (default: 'en-us') Example: curl -X GET 'http://localhost:5099/api/__yao/neo/assistants/assistant_123?token=xxx' POST /assistants/:id/call Description: Call a specific assistant's API functionality. Body: { "name": "Test", "payload": { "name": "yao", "age": 18 } } Example: curl -X POST 'http://localhost:5099/api/__yao/neo/assistants/assistant_123/call' \ -H 'Content-Type: application/json' \ -d '{"name": "Test", "payload": {"name": "yao", "age": 18}}' POST /assistants Description: Create a new assistant or update an existing one. Body: { "name": "My Assistant", "type": "chat", "tags": ["tag1", "tag2"], "mentionable": true, "avatar": "path/to/avatar.png" } Example: curl -X POST 'http://localhost:5099/api/__yao/neo/assistants' \ -H 'Content-Type: application/json' \ -d '{"name": "My Assistant", "type": "chat", "tags": ["tag1"], "token": "xxx"}' DELETE /assistants/:id Description: Delete a specific assistant. Example: curl -X DELETE 'http://localhost:5099/api/__yao/neo/assistants/assistant_123?token=xxx' ``` -------------------------------- ### Assistant Management Operations Source: https://github.com/yaoapp/yao/blob/main/neo/store/README.md Provides Go code examples for managing assistants. Includes creating assistants with various properties, retrieving assistants with filtering, and fetching a specific assistant by ID. ```go // Create an assistant assistant := map[string]interface{}{ "name": "Code Helper", "type": "assistant", "connector": "gpt-4", "description": "A helpful coding assistant", "tags": []string{"coding", "development"}, "sort": 100, "options": map[string]interface{}{ "temperature": 0.7, "max_tokens": 2000, }, "prompts": []string{ "You are a helpful coding assistant.", }, "mentionable": true, "automated": true, } assistantID, err := store.SaveAssistant(assistant) // Get assistants with filtering filter := AssistantFilter{ Tags: []string{"coding"}, Keywords: "helper", Page: 1, PageSize: 10, } assistants, err := store.GetAssistants(filter) // Get specific assistant assistant, err := store.GetAssistant("assistant123") ``` -------------------------------- ### Go Code for Manual Store Initialization Source: https://github.com/yaoapp/yao/blob/main/neo/store/README.md Demonstrates manual initialization of different YAO Neo Store backends (Database, Redis, MongoDB) using their respective constructor functions. ```go import "github.com/yaoapp/yao/neo/store" // Database backend setting := store.Setting{ Connector: "mysql", Prefix: "neo_", MaxSize: 100, TTL: 3600, } store, err := store.NewXun(setting) // Redis backend redisStore := store.NewRedis() // MongoDB backendmongoStore := store.NewMongo() ``` -------------------------------- ### Go Function for Automatic Store Initialization Source: https://github.com/yaoapp/yao/blob/main/neo/store/README.md Illustrates the automatic initialization process of the YAO Neo Store, selecting the appropriate backend based on configuration. ```go // From yao/neo/load.go func initStore() error { var err error if Neo.StoreSetting.Connector == "default" || Neo.StoreSetting.Connector == "" { Neo.Store, err = store.NewXun(Neo.StoreSetting) return err } // Other connector types conn, err := connector.Select(Neo.StoreSetting.Connector) if err != nil { return err } if conn.Is(connector.DATABASE) { Neo.Store, err = store.NewXun(Neo.StoreSetting) return err } else if conn.Is(connector.REDIS) { Neo.Store = store.NewRedis() return nil } else if conn.Is(connector.MONGO) { Neo.Store = store.NewMongo() return nil } return fmt.Errorf("%s store connector %s not support", Neo.ID, Neo.StoreSetting.Connector) } ``` -------------------------------- ### Basic OAuth Test Structure Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Demonstrates the basic structure for an OAuth test function. It initializes the test environment using `setupOAuthTestEnvironment` and ensures proper cleanup using `defer cleanup()`. It highlights the usage of pre-configured test clients and users for testing standard OAuth flows. ```go func TestOAuthFeature(t *testing.T) { service, _, _, cleanup := setupOAuthTestEnvironment(t) defer cleanup() // Use pre-configured test clients and users // All standard OAuth flows are supported } ``` -------------------------------- ### Get value from map Source: https://github.com/yaoapp/yao/blob/main/utils/README.md Gets a value from a map (object) by its key. Returns the value associated with the specified key. ```typescript /** * Gets a value from a map by key * @param map - Input map * @param key - Key to retrieve * @returns any - Value associated with the key */ const name = Process("utils.map.Get", { id: 1, name: "John", age: 30 }, "name"); // Returns: "John" ``` -------------------------------- ### Get item by index from array Source: https://github.com/yaoapp/yao/blob/main/utils/README.md Gets an item from an array by its index. Requires the array and the index of the desired item. ```typescript /** * Gets an item from an array by index * @param array - Input array * @param index - Array index * @returns any - Item at the specified index */ const item = Process("utils.arr.Get", ["apple", "banana", "orange"], 1); // Returns: "banana" ``` -------------------------------- ### Get array indexes Source: https://github.com/yaoapp/yao/blob/main/utils/README.md Gets the indexes of an array. Returns an array of integers representing the indices of the input array. ```typescript /** * Gets the indexes of an array * @param array - Input array * @returns array - Array indexes */ const indexes = Process("utils.arr.Indexes", ["apple", "banana", "orange"]); // Returns: [0, 1, 2] ``` -------------------------------- ### Go Test Execution Source: https://github.com/yaoapp/yao/blob/main/neo/attachment/README.md Provides commands for running tests in the project. It includes instructions for running all tests and optionally setting environment variables for S3 credentials to test S3 storage backend integration. ```bash # Run all tests go test ./... # Run with S3 credentials (optional) export S3_ACCESS_KEY="your-key" export S3_SECRET_KEY="your-secret" export S3_BUCKET="your-bucket" export S3_API="https://your-s3-endpoint" go test ./... ``` -------------------------------- ### Run Go Tests with Options Source: https://github.com/yaoapp/yao/blob/main/neo/store/README.md Provides bash commands for executing Go tests. Includes options for verbose output, running specific tests, and generating code coverage reports. ```bash # Run all tests go test -v # Run specific test go test -run TestXunKnowledgeCRUD -v # Run with coverage go test -cover ``` -------------------------------- ### Write Column (TypeScript) Source: https://github.com/yaoapp/yao/blob/main/excel/README.md Writes an array of values to a column in a sheet, starting from a specified cell. Requires file handle, sheet name, starting cell reference, and an array of values. ```typescript /** * Writes values to a column starting at the specified cell * @param handle - Handle ID from excel.open * @param sheet - Sheet name * @param startCell - Starting cell reference (e.g. "A1") * @param values - Array of values to write * @returns null */ Process("excel.write.Column", h, "SheetName", "A1", ["Row1", "Row2", "Row3"]); ``` -------------------------------- ### Write Row (TypeScript) Source: https://github.com/yaoapp/yao/blob/main/excel/README.md Writes an array of values to a row in a sheet, starting from a specified cell. Requires file handle, sheet name, starting cell reference, and an array of values. ```typescript /** * Writes values to a row starting at the specified cell * @param handle - Handle ID from excel.open * @param sheet - Sheet name * @param startCell - Starting cell reference (e.g. "A1") * @param values - Array of values to write * @returns null */ Process("excel.write.Row", h, "SheetName", "A1", ["Cell1", "Cell2", "Cell3"]); ``` -------------------------------- ### Basic Attachment Upload and Read Source: https://github.com/yaoapp/yao/blob/main/neo/attachment/README.md Demonstrates the basic usage of the attachment package, including registering a default manager, creating a custom manager with specific options, uploading a file, and reading it back. It covers essential steps for file handling. ```go package main import ( "context" "fmt" "strings" "mime/multipart" "github.com/yaoapp/yao/neo/attachment" ) func main() { // Create a manager with default settings manager, err := attachment.RegisterDefault("uploads") if err != nil { panic(err) } // Or create a custom manager customManager, err := attachment.New(attachment.ManagerOption{ Driver: "local", MaxSize: "20M", ChunkSize: "2M", AllowedTypes: []string{"text/*", "image/*", ".pdf"}, Options: map[string]interface{}{ "path": "/var/uploads", }, }) if err != nil { panic(err) } // Upload a file content := "Hello, World!" fileHeader := &attachment.FileHeader{ FileHeader: &multipart.FileHeader{ Filename: "hello.txt", Size: int64(len(content)), Header: make(map[string][]string), }, } fileHeader.Header.Set("Content-Type", "text/plain") option := attachment.UploadOption{ UserID: "user123", ChatID: "chat456", OriginalFilename: "my_document.txt", // Preserve original filename } file, err := manager.Upload(context.Background(), fileHeader, strings.NewReader(content), option) if err != nil { panic(err) } // Check upload status if file.Status == "uploaded" { fmt.Printf("File uploaded successfully: %s\n", file.ID) } // Read the file back data, err := manager.Read(context.Background(), file.ID) if err != nil { panic(err) } println(string(data)) // Output: Hello, World! } ``` -------------------------------- ### Write Multiple Rows (TypeScript) Source: https://github.com/yaoapp/yao/blob/main/excel/README.md Writes a two-dimensional array of values to a sheet, starting from a specified cell. This is useful for writing blocks of data. Requires file handle, sheet name, starting cell reference, and the data array. ```typescript /** * Writes a two-dimensional array of values starting at the specified cell * @param handle - Handle ID from excel.open * @param sheet - Sheet name * @param startCell - Starting cell reference (e.g. "A1") * @param values - Two-dimensional array of values to write * @returns null */ Process("excel.write.All", h, "SheetName", "A1", [ ["Row1Cell1", "Row1Cell2", "Row1Cell3"], ["Row2Cell1", "Row2Cell2", "Row2Cell3"], ]); ``` -------------------------------- ### Get all keys from map Source: https://github.com/yaoapp/yao/blob/main/utils/README.md Retrieves all keys from a map (object) and returns them as an array. ```typescript /** * Gets all keys from a map * @param map - Input map * @returns array - Array of keys */ const keys = Process("utils.map.Keys", { id: 1, name: "John", age: 30 }); // Returns: ["id", "name", "age"] ``` -------------------------------- ### Initialize Xun Store for Testing Source: https://github.com/yaoapp/yao/blob/main/neo/store/README.md Demonstrates how to initialize the Xun store with a specific prefix for isolated unit tests. This ensures that test data does not interfere with other operations. ```go store, err := NewXun(Setting{ Connector: "default", Prefix: "__unit_test_conversation_", TTL: 3600, }) ``` -------------------------------- ### Get Environment Variable (utils.env.Get) Source: https://github.com/yaoapp/yao/blob/main/utils/README.md Retrieves the value of a specified environment variable. This is essential for configuring applications dynamically. ```typescript /** * Gets the value of an environment variable * @param name - Environment variable name * @returns string - Environment variable value */ const dbHost = Process("utils.env.Get", "DB_HOST"); ``` -------------------------------- ### Get current date Source: https://github.com/yaoapp/yao/blob/main/utils/README.md Retrieves the current date formatted as 'YYYY-MM-DD'. This function provides the current calendar date. ```typescript const date = Process("utils.now.Date"); // Returns: "2023-07-01" ``` -------------------------------- ### Get current time Source: https://github.com/yaoapp/yao/blob/main/utils/README.md Retrieves the current time formatted as 'HH:MM:SS'. This function provides the current clock time. ```typescript const time = Process("utils.now.Time"); // Returns: "12:34:56" ``` -------------------------------- ### Test Public API Endpoint in Go Source: https://github.com/yaoapp/yao/blob/main/openapi/hello/README.md Demonstrates making an HTTP GET request to a public API endpoint using Go's net/http package. It fetches and prints the response body from '/v1/helloworld/public'. Includes basic error handling and resource cleanup. ```Go package main import ( "fmt" "io" "net/http" ) func testPublicEndpoint() { resp, err := http.Get("/v1/helloworld/public") if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(string(body)) } ``` -------------------------------- ### Get XGen Configuration - TypeScript Source: https://github.com/yaoapp/yao/blob/main/widgets/table/README.md Fetches the XGen configuration for a table, optionally accepting additional data. Uses the Process API. ```typescript /** * Gets the XGen configuration for a table * @param tableID - ID of the table * @param data - Optional additional data * @returns object - XGen configuration */ const xgen = Process("yao.table.Xgen", "pet", { /* optional data */ }); ``` -------------------------------- ### Server-to-Server Integration Workflow Source: https://github.com/yaoapp/yao/blob/main/openapi/README.md Outlines the client credentials flow for server-to-server integrations. It shows how to obtain a client credentials token and then use it to manage DSL resources via API calls. ```bash # 1. Obtain client credentials token: curl -X POST "/v1/oauth/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials&client_id=server_client&client_secret=server_secret&scope=dsl:manage" # 2. Manage DSL resources (Create a new model): curl -X POST "/v1/dsl/create/model" \ -H "Authorization: Bearer {access_token}" \ -H "Content-Type: application/json" \ -d '{ "id": "product", "source": "{ \"name\": \"product\", \"table\": { \"name\": \"products\" }, \"columns\": [...] }" ``` -------------------------------- ### Get Table Settings - TypeScript Source: https://github.com/yaoapp/yao/blob/main/widgets/table/README.md Retrieves the settings for a specified table using the Process API. Requires the table ID as a string. ```typescript /** * Gets the settings for a table * @param tableID - ID of the table * @returns object - Table settings */ const settings = Process("yao.table.Setting", "pet"); ``` -------------------------------- ### FileHeader Utility Methods (Go) Source: https://github.com/yaoapp/yao/blob/main/neo/attachment/README.md Explains and demonstrates the utility methods available on the `FileHeader` type in Go, such as retrieving UID, fingerprint, range, sync status, and chunk information for managing file uploads. ```go // Get unique identifier for chunked uploads uid := fileHeader.UID() // Get content fingerprint for deduplication fingerprint := fileHeader.Fingerprint() // Get byte range for chunked uploads rangeHeader := fileHeader.Range() // Check if synchronization is enabled isSync := fileHeader.Sync() // Check if this is a chunked upload isChunk := fileHeader.IsChunk() // Check if upload is complete (for chunked uploads) isComplete := fileHeader.Complete() // Get detailed chunk information start, end, total, err := fileHeader.GetChunkInfo() // Get total file size (for chunked uploads) totalSize := fileHeader.GetTotalSize() // Get current chunk size chunkSize := fileHeader.GetChunkSize() ``` -------------------------------- ### Get Multiple Environment Variables (utils.env.GetMany) Source: https://github.com/yaoapp/yao/blob/main/utils/README.md Retrieves the values of multiple environment variables by name. Returns a map of variable names to their values. ```typescript /** * Gets multiple environment variables * @param ...names - Environment variable names * @returns object - Map of environment variables */ const config = Process("utils.env.GetMany", "DB_HOST", "DB_PORT", "DB_USER"); // Returns: { "DB_HOST": "localhost", "DB_PORT": "5432", "DB_USER": "postgres" } ``` -------------------------------- ### Parameterized Testing for Multiple Stores Source: https://github.com/yaoapp/yao/blob/main/openapi/oauth/TESTING_GUIDE.md Illustrates parameterized testing to evaluate the OAuth functionality across different store backends. It iterates through various store configurations, running sub-tests for each to ensure compatibility and robustness. ```go func TestMultipleStores(t *testing.T) { storeConfigs := getStoreConfigs() for _, config := range storeConfigs { t.Run(config.Name, func(t *testing.T) { // Test with different store backends }) } } ``` -------------------------------- ### Registering Global Attachment Managers Source: https://github.com/yaoapp/yao/blob/main/neo/attachment/README.md Demonstrates registering default and custom attachment managers for global access, supporting different drivers like 'local' and 's3'. ```go // Register default manager with sensible defaults attachment.RegisterDefault("main") // Register custom managers attachment.Register("local", "local", attachment.ManagerOption{ Driver: "local", Options: map[string]interface{}{ "path": "/var/uploads", }, }) attachment.Register("s3", "s3", attachment.ManagerOption{ Driver: "s3", Options: map[string]interface{}{ "bucket": "my-bucket", "key": "access-key", "secret": "secret-key", }, }) // Use global managers localManager := attachment.Managers["local"] s3Manager := attachment.Managers["s3"] defaultManager := attachment.Managers["main"] ``` -------------------------------- ### Get Multiple Table Records - TypeScript Source: https://github.com/yaoapp/yao/blob/main/widgets/table/README.md Retrieves multiple records from a table with optional query parameters and relationships. Uses the Process API. ```typescript /** * Gets multiple records from a table * @param tableID - ID of the table * @param params - Query parameters * @returns array - Array of records */ const records = Process("yao.table.Get", "pet", { limit: 10, withs: { user: {} }, }); ```