### Start Application - NocoBase API Source: https://docs.nocobase.com/api/server/application Starts the application to accept incoming requests. It can optionally check if the application is installed before starting. This method returns a Promise that resolves when the application has successfully started. ```typescript interface StartOptions { checkInstall?: boolean; } // Example usage: app.start({ checkInstall: true }); ``` -------------------------------- ### createMockServer() Source: https://docs.nocobase.com/api/test/server Creates, installs, and starts a MockServer instance, suitable for comprehensive server-side testing. ```APIDOC ## createMockServer() ### Description Create a `MockServer` instance, perform forced installation, and start it. ### Method `createMockServer(options?: ApplicationOptions & { version?: string; beforeInstall?: BeforeInstallFn; skipInstall?: boolean; skipStart?: boolean; }): Promise` ### Parameters #### Query Parameters - **options** (ApplicationOptions) - Optional - Refer to Application for details on options. - **options.version** (string) - Optional - Application version. - **options.beforeInstall** (BeforeInstallFn) - Optional - Function to execute before installation. - **options.skipInstall** (boolean) - Optional - Whether to skip forced installation. - **options.skipStart** (boolean) - Optional - Whether to skip application startup. ### Response #### Success Response (200) - **Promise** - A promise that resolves to a started MockServer instance. ``` -------------------------------- ### Install Application - NocoBase API Source: https://docs.nocobase.com/api/server/application Installs the application, which includes initialization, synchronization of data table configurations, plugin installation, and a restart if the application is already running. It supports a force option to reinstall if already installed. ```typescript interface InstallOptions { force?: boolean; } // Example usage: app.install({ force: true }); ``` -------------------------------- ### MockServer Class Methods for Testing Source: https://docs.nocobase.com/api/test/server Illustrates common methods available on the `MockServer` class for server-side testing. These include loading and installing the application, cleaning the database, performing a quick start, destroying the application, and creating an agent for making API requests. ```typescript // Load and install the application await app.loadAndInstall(); // Clear the database await app.cleanDb(); // Execute 'nocobase start --quickstart' await app.quickstart(); // Destroy the application await app.destroy(); // Initiate API requests in test cases const agent = app.agent(); // Example of using the agent with login agent.login({ username: 'testuser', password: 'password' }); agent.loginUsingId(1); // Example of using the resource method const userResource = agent.resource('users'); ``` -------------------------------- ### Initial NocoBase Installation Source: https://docs.nocobase.com/api/cli Performs an initial installation of NocoBase, setting up the database and necessary configurations. Options include specifying the language, root user email, password, and nickname. ```bash yarn nocobase install -l zh-CN -e admin@nocobase.com -p admin123 ``` -------------------------------- ### CacheManager Initialization Example (TypeScript) Source: https://docs.nocobase.com/api/cache/cache-manager Illustrates how to initialize CacheManager with custom options, overriding or extending default configurations. This example shows setting 'redis' as the default store and providing specific Redis configurations. ```typescript const cacheManager = new CacheManager({ stores: { defaultStore: 'redis', redis: { // redisStore is already provided in the default options, so only need to provide redisStore configuration. url: 'redis://localhost:6379', }, }, }); ``` -------------------------------- ### List Resources API Endpoint Source: https://docs.nocobase.com/api/actions This example demonstrates retrieving a list of resources using the `list` action via a GET request to `/api/:list`. It supports various query parameters for filtering, field selection, sorting, and pagination. The `list` method is part of the @nocobase/actions package. ```shell curl -X GET http://localhost:13000/api/users:list ``` -------------------------------- ### Get Specific Resource API Endpoint Source: https://docs.nocobase.com/api/actions This example shows how to retrieve a specific resource using the `get` action. It employs a GET request to `/api/:get` and can filter by the primary key (`filterByTk`) or other filter criteria. The `get` method is part of the @nocobase/actions package. ```shell curl -X GET http://localhost:13000/api/users:get?filterByTk=1 ``` -------------------------------- ### Start NocoBase in Production Mode Source: https://docs.nocobase.com/api/cli Starts the NocoBase application in production mode. This command requires the application to be built first using `yarn nocobase build`. ```bash yarn nocobase start ``` -------------------------------- ### Start NocoBase in Development Mode Source: https://docs.nocobase.com/api/cli Starts the NocoBase application in development mode, enabling real-time code compilation. The command also provides options to start only the client or server side. ```bash yarn nocobase dev yarn nocobase dev --server yarn nocobase dev --client ``` -------------------------------- ### Start Metric Reader Method (TypeScript) Source: https://docs.nocobase.com/api/telemetry/metric Shows the signature for the start method. This method is used to initiate the MetricReader, beginning the process of collecting metrics. ```typescript start(): void ``` -------------------------------- ### Execute Custom NocoBase CLI Command Source: https://docs.nocobase.com/api/cli Shows how to execute a custom command that has been added to the NocoBase CLI. This example assumes a 'hello' command has been registered. ```bash yarn nocobase hello ``` -------------------------------- ### Check Installation Status - NocoBase API Source: https://docs.nocobase.com/api/server/application Checks whether the NocoBase application has been installed. This method returns a Promise resolving to a boolean indicating the installation status. ```typescript // Example usage: const installed = await app.isInstalled(); console.log('Is installed:', installed); ``` -------------------------------- ### Force Reinstall NocoBase Source: https://docs.nocobase.com/api/cli Reinstalls NocoBase by first deleting all existing NocoBase data tables. This is useful for a clean slate installation or when encountering issues with the current setup. It requires specifying installation options like language and root user credentials. ```bash yarn nocobase install -f -l zh-CN -e admin@nocobase.com -p admin123 ``` -------------------------------- ### Basic Server-Side Test Setup with MockServer Source: https://docs.nocobase.com/api/test/server Demonstrates the basic structure for setting up a server-side test environment using `createMockServer`. It initializes the mock server with specified plugins, sets up the database and agent, and ensures proper cleanup after tests. ```typescript describe('actions', () => { let app: MockServer; let db: Database; let agent: any; beforeAll(async () => { app = await createMockServer({ plugins: ['acl', 'users', 'data-source-manager'], }); db = app.db; agent = app.agent(); }); afterAll(async () => { await app.destroy(); }); }); ``` -------------------------------- ### Example: Add Associated Objects (TypeScript) Source: https://docs.nocobase.com/api/database/relation-repository/belongs-to-many-repository This example demonstrates how to use the `add` method to associate tags with a post. It shows two ways to use the method: passing only target keys, and passing target keys along with intermediate table field values. ```typescript const t1 = await Tag.repository.create({ values: { name: 't1' } }); const t2 = await Tag.repository.create({ values: { name: 't2' } }); const p1 = await Post.repository.create({ values: { title: 'p1' } }); const PostTagRepository = new BelongsToManyRepository(Post, 'tags', p1.id); // Pass in the targetKey PostTagRepository.add([t1.id, t2.id]); // Pass in intermediate table fields PostTagRepository.add([ [t1.id, { tagged_at: '123' }], [t2.id, { tagged_at: '456' }], ]); ``` -------------------------------- ### PluginManager - Install Enabled Plugins Source: https://docs.nocobase.com/api/server/plugin-manager Installs all enabled plugins that have not yet been installed. This asynchronous method ensures that all necessary plugin components are set up. ```typescript /** * Installs all enabled plugins that are not yet installed. */ install(): Promise; ``` -------------------------------- ### Making General HTTP Requests with APIClient Source: https://docs.nocobase.com/api/sdk Illustrates how to use the `request` method of the APIClient for general HTTP requests. This example shows a basic request with just a URL, leveraging standard axios configurations. ```typescript const res = await apiClient.request({ url: '' }); ``` -------------------------------- ### Creating a Cache Instance (TypeScript) Source: https://docs.nocobase.com/api/cache/cache-manager Demonstrates how to create a new cache instance using `createCache`. This example shows specifying a name, store type, and optional prefix for the cache, along with custom store configurations. ```typescript await cacheManager.createCache({ name: 'default', // Unique identifier for the cache store: 'memory', // Unique identifier for the store prefix: 'mycache', // Automatically adds the 'mycache:' prefix to cache keys, optional // Other store configurations, custom configurations that will be merged with global store configurations max: 2000, }); ``` -------------------------------- ### Telemetry Module Source: https://docs.nocobase.com/api/telemetry/telemetry Documentation for the Telemetry class methods, including constructor, init, start, shutdown, and addInstrumentation. ```APIDOC ## Telemetry Class ### Description The `Telemetry` class is the telemetry module of NocoBase, encapsulating OpenTelemetry support for registering metrics and traces within the OpenTelemetry ecosystem. ### Class Methods #### `constructor(options?: TelemetryOptions)` **Description**: Constructor to create a `Telemetry` instance. **Parameters**: * `options` (TelemetryOptions) - Optional. Configuration for telemetry, including service name, version, trace, and metric options. **TelemetryOptions Interface**: ```typescript export interface TelemetryOptions { serviceName?: string; version?: string; trace?: TraceOptions; metric?: MetricOptions; } ``` **TelemetryOptions Details**: * `serviceName` (string) - Optional. Refer to Semantic Conventions. Defaults to `nocobase`. * `version` (string) - Optional. Refer to Semantic Conventions. Defaults to the current NocoBase version. * `trace` (TraceOptions) - Optional. Configuration for tracing. * `metric` (MetricOptions) - Optional. Configuration for metrics. #### `init(): void` **Description**: Registers instrumentation and initializes `Trace` and `Metric`. #### `start(): void` **Description**: Starts the processing of `Trace` and `Metric` related data, such as exporting to Prometheus. #### `shutdown(): Promise` **Description**: Stops the processing of `Trace` and `Metric` related data. #### `addInstrumentation(...instrumentation: InstrumentationOption[])` **Description**: Adds instrumentation libraries. **Parameters**: * `...instrumentation` (InstrumentationOption[]) - One or more instrumentation options to add. ``` -------------------------------- ### CacheManager Default Options (TypeScript) Source: https://docs.nocobase.com/api/cache/cache-manager Demonstrates the default configuration for CacheManager, including memory and Redis store setups. It shows how to define default store types and their global configurations. ```typescript import { redisStore, RedisStore } from 'cache-manager-redis-yet'; const defaultOptions: CacheManagerOptions = { defaultStore: 'memory', stores: { memory: { store: 'memory', // global config max: 2000, }, redis: { store: redisStore, close: async (redis: RedisStore) => { await redis.client.quit(); }, }, }, }; ``` -------------------------------- ### Upgrade NocoBase Installation Source: https://docs.nocobase.com/api/cli Upgrades an existing NocoBase installation to the latest version. This command should be run after updating the NocoBase packages. ```bash yarn nocobase upgrade ``` -------------------------------- ### First or Create Resource API Endpoint Source: https://docs.nocobase.com/api/actions This example shows how to retrieve a resource if it exists, or create it if it doesn't, using the `firstOrCreate` action. It uses a POST request to `/api/:firstOrCreate` with `filterKeys` to identify existing resources and a JSON payload for creation. The `firstOrCreate` method is part of the @nocobase/actions package. ```shell curl "http://localhost:13000/api/users:firstOrCreate?filterKeys[]=username" \ -X POST \ -H "Content-Type: application/json" \ -d '{"username": "admin", "nickname": "Admin"}' ``` -------------------------------- ### Create Resource API Endpoint Source: https://docs.nocobase.com/api/actions This example shows how to create a resource using the `create` action. It utilizes a POST request to the `/api/:create` endpoint with a JSON payload containing the resource fields. The `create` method is part of the @nocobase/actions package. ```shell curl "http://localhost:13000/api/users:create" \ -X POST \ -H "Content-Type: application/json" \ -d '{"username": "admin"}' ``` -------------------------------- ### JavaScript Code Block Example Source: https://docs.nocobase.com/api/field/markdown-vditor Demonstrates a simple JavaScript function for logging a greeting to the console. This snippet is intended to show basic JavaScript syntax within a Markdown code block. ```javascript function greet() { console.log('Hello, Markdown!'); } greet(); ``` -------------------------------- ### List Resources Source: https://docs.nocobase.com/api/actions Retrieves a list of resources, with options for filtering, field selection, sorting, and pagination. Accessible via GET /api/:list. ```APIDOC ## GET /api/:list ### Description Retrieves a list of resources. ### Method GET ### Endpoint /api/:list ### Parameters #### Query Parameters - **filter** (Filter) - Optional - Filtering parameters, see Filter Operators - **fields** (string[]) - Optional - Fields to retrieve - **except** (string[]) - Optional - Fields to exclude - **appends** (string[]) - Optional - Related fields to append - **sort** (string[]) - Optional - Sorting parameters - **paginate** (boolean) - Optional - Whether to use pagination (default: true) - **page** (number) - Optional - Current page number (default: 1) - **pageSize** (number) - Optional - Number of items per page (default: 20) ### Request Example ```bash curl -X GET http://localhost:13000/api/users:list?sort[]=username&pageSize=10 ``` ### Response #### Success Response (200) - **data** (object[]) - An array of resources - **meta** (object) - Pagination metadata (if paginate is true) #### Response Example ```json { "data": [ { "id": 1, "username": "admin" } ], "meta": { "currentPage": 1, "pageSize": 20, "totalCount": 50 } } ``` ``` -------------------------------- ### Registering a New Cache Store (TypeScript) Source: https://docs.nocobase.com/api/cache/cache-manager Shows how to dynamically register a new caching method with CacheManager using the `registerStore` method. This example registers the Redis store with its specific configurations. ```typescript import { redisStore } from 'cache-manager-redis-yet'; cacheManager.registerStore({ // Unique identifier for the store name: 'redis', // Factory method for creating the store store: redisStore, // Callback method for closing the store connection close: async (redis: RedisStore) => { await redis.client.quit(); }, // Global configurations url: 'xxx', }); ``` -------------------------------- ### Upgrade Application - NocoBase API Source: https://docs.nocobase.com/api/server/application Upgrades the application by running migration scripts for each installed plugin and then restarting the application. This ensures that the application and its plugins are running the latest compatible versions. ```typescript // Example usage: app.upgrade(); ``` -------------------------------- ### Clear Database and Reinstall NocoBase Source: https://docs.nocobase.com/api/cli Clears the entire database and then performs a NocoBase reinstallation. This is a more drastic measure than force installation, as it removes all database content, not just NocoBase tables. Options for language and root user credentials are required. ```bash yarn nocobase install -c -l zh-CN -e admin@nocobase.com -p admin123 ``` -------------------------------- ### Logger Transports Console Example (TypeScript) Source: https://docs.nocobase.com/api/logger Demonstrates how to import and use the predefined 'console' transport from the '@nocobase/logger' package. This allows configuring the console output for logs. Dependencies include '@nocobase/logger'. ```typescript import { Transports } from '@nocobase/logger'; const transport = Transports.console({ //... options for console transport }); ``` -------------------------------- ### Trace Class Methods - TypeScript Source: https://docs.nocobase.com/api/telemetry/trace Illustrates the core methods of the Trace class in TypeScript, including constructor, initialization, processor registration, tracer retrieval, starting, and shutting down tracing. ```typescript class Trace { constructor(options?: TraceOptions) init(): void registerProcessor(name: string, processor: GetSpanProcessor) getTracer(name?: string, version?: string) start(): void shutdown(): Promise } ``` -------------------------------- ### Restart Application - NocoBase API Source: https://docs.nocobase.com/api/server/application Restarts the application by performing a reload and then starting it again. This is useful for applying configuration changes or recovering from certain states. It accepts optional StartOptions. ```typescript interface StartOptions { checkInstall?: boolean; } // Example usage: app.restart({ checkInstall: false }); ``` -------------------------------- ### Move Resource API Endpoint Source: https://docs.nocobase.com/api/actions This example shows how to reorder resources using the `move` action, typically for drag-and-drop functionality. It uses a POST request to `/api/:move` with `sourceId` and `targetId` parameters to define the move operation. The `move` method is part of the @nocobase/actions package. ```shell curl -X POST "http://localhost:13000/api/users:move?sourceId=1&targetId=2" ``` -------------------------------- ### Get Path Segments Source: https://docs.nocobase.com/api/handlebars-helpers/path The `segments` helper function allows retrieving specific joined segments of a file path by providing a range of array indices. It takes the filepath string and two index strings ('start' and 'end') as arguments, returning a joined string of the selected segments. ```handlebars {{segments "a/b/c/d" "2" "3"}} ``` ```handlebars {{segments "a/b/c/d" "1" "3"}} ``` ```handlebars {{segments "a/b/c/d" "1" "2"}} ``` -------------------------------- ### Get Resource Source: https://docs.nocobase.com/api/actions Retrieves a specific resource by its primary key or other filter criteria. Accessible via GET /api/:get. ```APIDOC ## GET /api/:get ### Description Retrieves a specific resource. ### Method GET ### Endpoint /api/:get ### Parameters #### Query Parameters - **filterByTk** (number | string) - Optional - Filter by primary key value - **filter** (Filter) - Optional - Filtering parameters, see Filter Operators - **fields** (string[]) - Optional - Fields to retrieve - **except** (string[]) - Optional - Fields to exclude - **appends** (string[]) - Optional - Related fields to append ### Request Example ```bash curl -X GET http://localhost:13000/api/users:get?filterByTk=1 ``` ### Response #### Success Response (200) - **resource** (object) - The requested resource details #### Response Example ```json { "resource": { "id": 1, "username": "admin" } } ``` ``` -------------------------------- ### mockServer() Source: https://docs.nocobase.com/api/test/server Creates a MockServer instance for setting up server-side testing environments. ```APIDOC ## mockServer() ### Description Create a `MockServer` instance. ### Method `mockServer(options?: ApplicationOptions): MockServer` ### Parameters #### Query Parameters - **options** (ApplicationOptions) - Optional - Refer to Application for details on options. ### Response #### Success Response (200) - **MockServer** - An instance of MockServer. ``` -------------------------------- ### Cache Management - Basic Methods Source: https://docs.nocobase.com/api/cache/cache Provides basic cache management operations by leveraging the node-cache-manager library. These methods include getting, setting, deleting, and resetting cache entries, as well as wrapping functions with caching logic. ```APIDOC ## Cache Management - Basic Methods ### Description These methods provide basic cache management operations, similar to those found in node-cache-manager. ### Methods - `get(key: string)`: Retrieves a value from the cache. - `set(key: string, value: any, ttl?: number)`: Sets a value in the cache with an optional Time-To-Live (TTL). - `del(key: string)`: Deletes a value from the cache. - `reset()`: Clears all entries from the cache. - `wrap(key: string, fn: () => T | Promise, ttl?: number)`: Wraps a function call with caching. If the key exists, it returns the cached value; otherwise, it executes the function, caches the result, and returns it. - `mset(keyValuePairs: Array<{ key: string; value: any; ttl?: number }>)`: Sets multiple key-value pairs in the cache. - `mget(keys: string[])`: Retrieves multiple values from the cache based on an array of keys. - `mdel(keys: string[])`: Deletes multiple values from the cache based on an array of keys. - `keys()`: Retrieves all keys currently in the cache. - `ttl(key: string)`: Returns the Time-To-Live (TTL) for a given cache key. ``` -------------------------------- ### Display NocoBase CLI Help Source: https://docs.nocobase.com/api/cli Shows the general help message for the NocoBase CLI, listing available commands and global options. This is useful for understanding the overall structure and available functionalities. ```bash yarn nocobase -h ``` -------------------------------- ### Get Repository Instance in NocoBase Source: https://docs.nocobase.com/api/data-source-manager/i-collection-manager Retrieve an instance of a `Repository` by its name and optionally by its source ID using the `getRepository` function. This is used to get specific data access layers for interacting with data sources. ```typescript getRepository(name: string, sourceId?: string | number): IRepository ``` -------------------------------- ### Initialize and Configure AuthManager Source: https://docs.nocobase.com/api/auth/auth-manager Demonstrates the basic usage of AuthManager, including initialization with an authentication key, setting up a data storer, registering a 'basic' authentication type with its corresponding class and title, and applying the authentication middleware to the application's resource manager. ```typescript const authManager = new AuthManager({ // Key to retrieve the current authenticator identifier from the request header authKey: 'X-Authenticator', }); // Set methods for storing and retrieving authenticators in AuthManager authManager.setStorer({ get: async (name: string) => { return db.getRepository('authenticators').find({ filter: { name } }); }, }); // Register an authentication type authManager.registerTypes('basic', { auth: BasicAuth, title: 'Password', }); // Use authentication middleware app.resourceManager.use(authManager.middleware()); ``` -------------------------------- ### Basic Repository Create Operation Source: https://docs.nocobase.com/api/database/repository Demonstrates how to create new data objects using the `create` method of the Repository. It covers both single record creation and bulk creation of multiple records. ```javascript await userRepository.create({ name: 'Mark', age: 18, }); // INSERT INTO users (name, age) VALUES ('Mark', 18) // Bulk creation await userRepository.create([ { name: 'Mark', age: 18, }, { name: 'Alex', age: 20, }, ]); ``` -------------------------------- ### Custom Repository Constructor and Usage in TypeScript Source: https://docs.nocobase.com/api/database/repository Illustrates how to define a custom repository by extending the base `Repository` class and adding custom methods. It demonstrates registering this custom repository and using it to perform database operations. ```typescript import { Repository } from '@nocobase/database'; class MyRepository extends Repository { async myQuery(sql) { return this.database.sequelize.query(sql); } } db.registerRepositories({ books: MyRepository, }); db.collection({ name: 'books', // here link to the registered repository repository: 'books', }); await db.sync(); const books = db.getRepository('books') as MyRepository; await books.myQuery('SELECT * FROM books;'); ``` -------------------------------- ### Get Vitest Configuration using defineConfig Source: https://docs.nocobase.com/api/test/client Retrieves the Vitest configuration object provided by NocoBase. This function is essential for setting up client-side tests with Vitest. ```typescript import { defineConfig } from '@nocobase/test/vitest.mjs'; const config = defineConfig(); ``` -------------------------------- ### Accessing and Using NocoBase Resources with APIClient Source: https://docs.nocobase.com/api/sdk Shows how to obtain a resource object using `apiClient.resource()` and then perform operations like creating or listing resources. This provides a more structured way to interact with NocoBase resources. ```typescript const resource = apiClient.resource('users'); await resource.create({ values: { username: 'admin', }, }); const res = await resource.list({ page: 2, pageSize: 20, }); ``` -------------------------------- ### Get items after index in array Source: https://docs.nocobase.com/api/handlebars-helpers/array The `after` helper returns all items in an array after a specified index. It takes the array and the number of items to exclude as parameters. ```handlebars {{after array 1}} ``` -------------------------------- ### Define hasOne Association in NocoBase Source: https://docs.nocobase.com/api/database/field Establishes a one-to-one relationship where the foreign key is stored in the associated collection. An example is a 'user' having a 'profile'. ```typescript db.collection({ name: 'users', fields: [ { type: 'hasOne', name: 'profile', target: 'profiles', // Can be omitted }, ], }); ``` -------------------------------- ### Initialize Metric Provider (TypeScript) Source: https://docs.nocobase.com/api/telemetry/metric Shows the signature for the init method of the Metric class. This method is responsible for initializing the MetricProvider, setting up the necessary components for metric collection. ```typescript init(): void ``` -------------------------------- ### Define a Resource with ActionOptions in TypeScript Source: https://docs.nocobase.com/api/resourcer/resource-manager Demonstrates defining a resource where the 'list' action is configured using ActionOptions. This allows customization of request parameters like fields, filters, and pagination without overriding the core handler. ```typescript app.resourceManager.define({ name: 'users', actions: { list: { fields: [], filter: {}, // ... }, }, }); ``` -------------------------------- ### ResourceManager.registerActionHandlers() Source: https://docs.nocobase.com/api/resourcer/resource-manager Registers action methods globally or for specific resources. This allows you to define custom handlers for actions like 'list', 'create', 'get', etc. ```APIDOC ## POST /resourceManager/registerActionHandlers ### Description Registers action methods globally or for specific resources. You can define custom handlers for default actions or new actions. ### Method POST ### Endpoint `/resourceManager/registerActionHandlers` ### Parameters #### Request Body - **name** (ActionName) - Required - The name of the action. Can be a general action name (e.g., 'list') or resource-specific (e.g., 'users:list'). - **handler** (HandlerType) - Required - The middleware handler function for the action. ### Request Example ```json { "name": "users:updateProfile", "handler": "async (ctx, next) => { /* ... */ await next(); }" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the action handler was registered successfully. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### PluginManager - Get All Plugin Names Source: https://docs.nocobase.com/api/server/plugin-manager Returns an iterable iterator of all registered plugin names within the NocoBase application. This is useful for iterating through available plugin identifiers. ```typescript /** * Gets all plugin names. * @returns An iterable iterator of plugin names. */ getAliases(): IterableIterator; ``` -------------------------------- ### Connect to MySQL or PostgreSQL Database Source: https://docs.nocobase.com/api/database Establishes a connection to a MySQL or PostgreSQL database using the Database constructor. Requires specifying connection details such as dialect, host, port, database name, username, and password. ```javascript const { Database } = require('@nocobase/database'); // MySQL database configuration parameters const database = new Database({ dialect: 'mysql', host: 'localhost', port: 3306, database: 'nocobase', username: 'root', password: 'password' }) // MySQL \ PostgreSQL database configuration parameters const database = new Database({ dialect: /* 'postgres' or 'mysql' */, database: 'database', username: 'username', password: 'password', host: 'localhost', port: 'port' }) ``` -------------------------------- ### APIClient Constructor Options Source: https://docs.nocobase.com/api/sdk Defines the options available for constructing an APIClient instance. This includes standard axios configurations and custom options for authentication and storage classes. ```typescript interface ExtendedOptions { authClass?: any; storageClass?: any; } export type APIClientOptions = | AxiosInstance | (AxiosRequestConfig & ExtendedOptions); ``` -------------------------------- ### Get Basename Source: https://docs.nocobase.com/api/handlebars-helpers/path The `basename` helper function extracts the filename (including extension) from a given filepath. It takes a string filepath and returns the basename as a string. ```handlebars {{basename "docs/toc.md"}} ``` -------------------------------- ### Get Defined Data Table from Nocobase Source: https://docs.nocobase.com/api/database The `getCollection` method retrieves a previously defined data table by its name. This allows for further inspection or manipulation of the collection's structure. ```typescript const collection = db.getCollection('books'); ``` -------------------------------- ### PluginManager Instance Methods Source: https://docs.nocobase.com/api/server/plugin-manager Documentation for the various methods available to manage plugins. ```APIDOC ## Instance Methods ### `addPreset()` Adds a system built-in plugin. Built-in plugins are enabled by default and do not appear in the client plugin manager list. #### Signature * `addPreset(plugin: string | typeof Plugin, options: any = {})` #### Details Parameter| Type| Description ---|---|--- `plugin`| `string` | `typeof Plugin`| Plugin name or instance `options`| `any`| Plugin options ``` ```APIDOC ### `getPlugins()` Gets all plugin instances of the current application. #### Signature * `getPlugins(): Map>` ``` ```APIDOC ### `getAliases()` Gets all plugin names. #### Signature * `getAliases(): IterableIterator` ``` ```APIDOC ### `get()` Gets a specific plugin. #### Signature * `get(name: string | typeof Plugin): Plugin` ``` ```APIDOC ### `has()` Checks if a plugin exists. #### Signature * `has(name: string | typeof Plugin): boolean` ``` ```APIDOC ### `create()` Creates a plugin and generates the plugin directory. #### Signature * `create(pluginName: string, options?: { forceRecreate?: boolean }): Promise` #### Details Parameter| Type| Description| Default ---|---|---|--- `pluginName`| `string`| Plugin name| - `options.forceRecreate`| `boolean`| Whether to remove the existing plugin directory and recreate it| `false` ``` ```APIDOC ### `add()` Adds or upgrades a plugin. #### Signature * `add(plugin?: any, options: any = {}, insert = false, isUpgrade = false): Promise` #### Details Parameter| Type| Description| Default ---|---|---|--- `plugin`| `string` | `typeof Plugin`| Plugin name or instance| - `options`| `any`| Plugin configuration| - `insert`| `boolean`| Whether to add plugin table records| `false` `isUpgrade`| `boolean`| Whether it's a plugin upgrade| `false` ``` ```APIDOC ### `load()` Loads all enabled plugins. #### Signature * `load(): Promise` ``` ```APIDOC ### `install()` Installs all enabled plugins that are not yet installed. #### Signature * `install(): Promise` ``` ```APIDOC ### `enable()` Enables one or more plugins that are not enabled. #### Signature * `enable(name: string | string[]): Promise` ``` ```APIDOC ### `disable()` Disables one or more enabled plugins. #### Signature * `disable(name: string | string[]): Promise` ``` ```APIDOC ### `remove()` Removes one or more plugins. #### Signature * `remove(name: string | string[], options?: { removeDir?: boolean; force?: boolean })` #### Details Parameter| Type| Description| Default ---|---|---|--- `name`| `string` | `string[]`| Plugin name(s)| - `options.removeDir`| `boolean`| Whether to remove the plugin directory| `false` `options.force`| `boolean`| Whether to delete database records directly, skipping `beforeRemove` / `afterRemove` hooks| `false` ``` -------------------------------- ### Get items before index in array Source: https://docs.nocobase.com/api/handlebars-helpers/array The `before` helper returns all items in an array before a specified count. It's the opposite of the `after` helper and takes the array and the number of items to exclude. ```handlebars {{before array 2}} ``` -------------------------------- ### First or Create Resource Source: https://docs.nocobase.com/api/actions Retrieves a resource if it exists, otherwise creates a new one. Accessible via POST /api/:firstOrCreate. ```APIDOC ## POST /api/:firstOrCreate ### Description Retrieves or creates a resource. ### Method POST ### Endpoint /api/:firstOrCreate ### Parameters #### Query Parameters - **filterKeys** (string[]) - Required - Fields in the request body used to find existing resources #### Request Body - **[key: string]** (any) - Required - Key-value pairs representing resource fields ### Request Example ```bash curl "http://localhost:13000/api/users:firstOrCreate?filterKeys[]=username" \ -X POST \ -H "Content-Type: application/json" \ -d '{"username": "admin", "nickname": "Admin"}' ``` ### Response #### Success Response (200) - **resource** (object) - The found or created resource details #### Response Example ```json { "resource": { "id": 1, "username": "admin", "nickname": "Admin" } } ``` ``` -------------------------------- ### Get Stem of Filepath Source: https://docs.nocobase.com/api/handlebars-helpers/path The `stem` helper function retrieves the 'stem' of a filepath, which is the filename without its extension. It accepts a string filepath and returns the stem as a string. ```handlebars {{stem "docs/toc.md"}} ``` -------------------------------- ### Instantiate Collection Manually in Typescript Source: https://docs.nocobase.com/api/database/collection Shows how to manually create a Collection instance using its constructor in TypeScript. This method allows for more granular control when defining a collection and its associated fields, providing an existing database instance. ```typescript const posts = new Collection( { name: 'posts', fields: [ { type: 'string', name: 'title', }, { type: 'double', name: 'price', }, ], }, { // An existing database instance database: db, }, ); ``` -------------------------------- ### Get Directory Name Source: https://docs.nocobase.com/api/handlebars-helpers/path The `dirname` helper function retrieves the directory name from a given filepath. It accepts a string filepath and returns the directory path as a string. ```handlebars {{dirname "docs/toc.md"}} ``` -------------------------------- ### Basic Repository Query Source: https://docs.nocobase.com/api/database/repository Illustrates how to perform a basic query to select all records from a repository that match a given filter. This is done using the `find` method with a `filter` parameter. ```javascript // SELECT * FROM users WHERE id = 1 userRepository.find({ filter: { id: 1, }, }); ``` -------------------------------- ### Basic Plugin Class Definition Source: https://docs.nocobase.com/api/server/plugin Defines a basic NocoBase server plugin by extending the base Plugin class. This is the starting point for any custom plugin development. ```typescript import { Plugin } from '@nocobase/server'; export class PluginDemoServer extends Plugin {} export default PluginDemoServer; ``` -------------------------------- ### Check if String Starts With Prefix (Handlebars) Source: https://docs.nocobase.com/api/handlebars-helpers/string Tests whether a string begins with a specified prefix. This helper can be used in block statements. It takes the prefix and the string to test as parameters. ```handlebars {{#startsWith "Goodbye" "Hello, world!"}} Whoops {{else}} Bro, do you even hello world? {{/startsWith}} ``` -------------------------------- ### Define belongsToMany Association in NocoBase Source: https://docs.nocobase.com/api/database/field Establishes a many-to-many relationship using an intermediate table to store foreign keys. An example is a 'post' having multiple 'tags' and vice-versa. ```typescript db.collection({ name: 'posts', fields: [ { type: 'belongsToMany', name: 'tags', target: 'tags', // Can be omitted if name is the same through: 'postsTags', // Intermediate table will be generated automatically if not specified foreignKey: 'postId', // Foreign key in the intermediate table referring to the table itself sourceKey: 'id', // Primary key of the table itself otherKey: 'tagId', // Foreign key in the intermediate table referring to the association table }, ], }); db.collection({ name: 'tags', fields: [ { type: 'belongsToMany', name: 'posts', through: 'postsTags', // Refer to the same intermediate table in the same set of relation }, ], }); ``` -------------------------------- ### Basic APIClient Usage in NocoBase Plugin Source: https://docs.nocobase.com/api/sdk Demonstrates how to extend the Plugin class and use the APIClient within a NocoBase plugin to make HTTP requests. It shows the basic structure for initializing and using the apiClient.request method. ```typescript class PluginSampleAPIClient extends Plugin { async load() { const res = await this.app.apiClient.request({ // ... }); } } ``` -------------------------------- ### PluginManager - Get All Plugin Instances Source: https://docs.nocobase.com/api/server/plugin-manager Retrieves all currently active plugin instances within the NocoBase application. This method returns a Map where keys are Plugin classes and values are their corresponding instances. ```typescript /** * Gets all plugin instances of the current application. * @returns A Map of plugin classes to their instances. */ getPlugins(): Map>; ``` -------------------------------- ### Get item at specific index from array Source: https://docs.nocobase.com/api/handlebars-helpers/array The `itemAt` helper retrieves and returns the item located at a specific index within an array. It requires the array and the desired index as parameters. ```handlebars {{itemAt array 1}} ``` -------------------------------- ### Get first item or items from array Source: https://docs.nocobase.com/api/handlebars-helpers/array The `first` helper returns the first item or a specified number of first items from an array. It takes the array and an optional count `n`. ```handlebars {{first "['a', 'b', 'c', 'd', 'e']" 2}} ``` -------------------------------- ### Performing NocoBase Resource Operations via APIClient Source: https://docs.nocobase.com/api/sdk Demonstrates using the `request` method with `ResourceActionOptions` to perform specific NocoBase resource operations like listing users. It highlights how to specify the resource, action, and parameters. ```typescript const res = await apiClient.request({ resource: 'users', action: 'list', params: { pageSize: 10, }, }); ``` -------------------------------- ### Get Nested Value from Object Source: https://docs.nocobase.com/api/handlebars-helpers/object Retrieves a value from an object using a dot-notation path. Can be used as a standard helper or a block helper for conditional rendering based on value existence. ```handlebars {{get context 'a.b.c'}} ``` ```handlebars {{#get context 'a.b.c'}} Value exists: {{this}} {{else}} Value not found {{/get}} ``` -------------------------------- ### Get a Field from Collection in Typescript Source: https://docs.nocobase.com/api/database/collection Illustrates how to retrieve a specific field object from a defined collection using its name. This is useful for inspecting or manipulating field configurations after the collection has been set up. ```typescript const posts = db.collection({ name: 'posts', fields: [ { type: 'string', name: 'title', }, ], }); const field = posts.getField('title'); ``` -------------------------------- ### Plugin Class Overview Source: https://docs.nocobase.com/api/server/plugin Documentation for the NocoBase server-side Plugin class, including its purpose, basic usage, instance properties, lifecycle methods, and other utility methods. ```APIDOC ## Plugin Class `Plugin` is the plugin class for the NocoBase server, providing configuration properties and lifecycle methods related to server-side plugins. ### Basic Usage ```typescript import { Plugin } from '@nocobase/server'; export class PluginDemoServer extends Plugin {} export default PluginDemoServer; ``` ## Instance Properties ### `options` Configuration options for the plugin. ### `name` `string` - The name of the plugin. ### `enabled` `boolean` - Whether the plugin is enabled. ### `installed` `boolean` - Whether the plugin is installed. ### `log` System log instance, with the default `module` set to the plugin name. Refer to Logger. ### `app` The `Application` instance of the current application. Refer to Application. ### `pm` The `PluginManager` instance of the current application. Refer to PluginManager. ### `db` The `DataBase` instance of the current application. Refer to DataBase. ## Lifecycle Methods ### `afterAdd()` Executed after the plugin is added, i.e., after `pm.add()`. ### `beforeLoad()` Executed during `pm.load()`. Used to register events, initialize classes, or perform other preprocessing logic before plugin loading. At this stage, the core API can be accessed, but not other plugin APIs. ### `load()` Loads the plugin and its related configurations. Executed during `pm.load()`, after all `beforeLoad()` methods of plugins have finished execution. At this stage, other plugin APIs can be accessed. ### `install()` Installation logic of the plugin, executed during application installation, upgrade, or when the plugin is first enabled. Typically used to perform tasks such as inserting preset data into tables. ### `beforeEnable()` Executed before the plugin is enabled. ### `afterEnable()` Executed after the plugin is enabled. ### `beforeDisable()` Executed before the plugin is disabled. ### `afterDisable()` Executed after the plugin is disabled. ### `beforeRemove()` Executed before the plugin is removed. ### `afterRemove()` Executed after the plugin is removed. ## Other Methods ### `t()` Internationalization method. ### `createLogger()` Creates a logger. Refer to Logger. ### `toJSON()` A method for internal use. Outputs plugin-related configuration information. ### `sendSyncMessage()` Publish synchronization messages. The synchronization messages sent by this method will only be received by the same plugin on other nodes, and will not be related to other plugins. #### Signature ```typescript sendSyncMessage(message: any): void | Promise ``` #### Arguments * `message`: Sync message data. #### Example ```typescript this.sendSyncMessage({ key: 'value' }); ``` ### `handleSyncMessage()` In a distributed environment, handle synchronization events published by the current plugin from other nodes. When the plugin uses memory state, it is necessary to override the event handling logic to ensure synchronization with the state of other nodes. #### Signature ```typescript handleSyncMessage(message: any): void | Promise ``` #### Arguments * `message`: Sync message data from other nodes. #### Example ```typescript handleSyncMessage(message: SyncMessage) { console.log('handleSyncMessage', message); // this.reloadData(); } ``` ``` -------------------------------- ### Get All Collections in NocoBase Source: https://docs.nocobase.com/api/data-source-manager/i-collection-manager The `getCollections` function retrieves all currently defined `Collection` instances within NocoBase. It returns an array of `ICollection` objects, providing a comprehensive view of your data structures. ```typescript getCollections(): Array ``` -------------------------------- ### NocoBase Application Load Method Signature Source: https://docs.nocobase.com/api/server/application Details the signature for the `load()` method of the NocoBase Application module, which is responsible for initializing the application. It returns a Promise that resolves when the loading process is complete. ```typescript load(options?: LoadOptions): Promise ``` -------------------------------- ### Telemetry Module Methods (TypeScript) Source: https://docs.nocobase.com/api/telemetry/telemetry Provides methods for managing the Telemetry module. This includes initializing, starting, and shutting down telemetry processing, as well as adding custom instrumentation libraries. ```typescript constructor(options?: TelemetryOptions) init(): void start(): void shutdown(): Promise addInstrumentation(...instrumentation: InstrumentationOption[]) ``` -------------------------------- ### Repository Instance Methods: find() Source: https://docs.nocobase.com/api/database/repository Details the `find()` method for retrieving datasets with filtering, sorting, and other options. ```APIDOC ## Instance Methods ### `find()` Find datasets from the database with the specified filtering conditions and sorting, etc. **Signature** * `async find(options?: FindOptions): Promise` **Type** ```typescript type Filter = FilterWithOperator | FilterWithValue | FilterAnd | FilterOr; type Appends = string[]; type Except = string[]; type Fields = string[]; type Sort = string[] | string; interface SequelizeFindOptions { limit?: number; offset?: number; } interface FilterByTk { filterByTk?: TargetKey; } interface CommonFindOptions extends Transactionable { filter?: Filter; fields?: Fields; appends?: Appends; except?: Except; sort?: Sort; } type FindOptions = SequelizeFindOptions & CommonFindOptions & FilterByTk; ``` **Detailed Information** #### `filter: Filter` Query conditions for filtering data results. In the query parameters that passed in, `key` is the name of the field, `value` is the corresponding value. Operators can be used in conjunction with other filtering conditions. ```typescript // Find records with name "foo" and age above 18 repository.find({ filter: { name: 'foo', age: { $gt: 18, }, }, }); ``` Refer to Operators for more information. #### `filterByTk: TargetKey` Query data by `TargetKey`, this is shortcut for the `filter` parameter. The field of `TargetKey` can be configured in `Collection`, the default is `primaryKey`. ```typescript // By default, find records with id 1 repository.find({ filterByTk: 1, }); ``` #### `fields: string[]` Query columns. It is used to control which data fields to output. With this parameter, only the specified fields will be returned. #### `except: string[]` Exclude columns. It is used to control which data fields to output. With this parameter, the specified fields will not be returned. #### `appends: string[]` Append columns. It is used to load associated data. With this parameter, the specified associated fields will be returned together. ``` -------------------------------- ### Context Management with {{with}} Helper Source: https://docs.nocobase.com/api/handlebars-helpers/core The {{with}} helper allows you to set a specific context for a block of content. This simplifies accessing nested properties within that block, making your templates cleaner and more readable by reducing repetitive path navigation. ```handlebars {{#with person}}

Name: {{name}}

Age: {{age}}

{{/with}} ```