### Install Directus Project with npm Source: https://ezdoc.cn/docs/directus/self-hosted/quickstart This command initializes a new Directus project using npm, prompting the user for project details and database configuration. It's the first step in setting up a new Directus instance. ```bash npm init directus-project example-project ``` -------------------------------- ### Start Directus Server Source: https://ezdoc.cn/docs/directus/self-hosted/quickstart After successful installation, this command is used to start the Directus server from within the project directory. It launches the application, making it accessible via a web browser. ```bash npx directus start ``` -------------------------------- ### Start Directus Server Source: https://ezdoc.cn/docs/directus/self-hosted/manual This command starts the Directus server using the "start" script defined in "package.json". This makes the Directus API and admin panel accessible. ```bash npm run start ``` -------------------------------- ### Create Directus Admin User Source: https://ezdoc.cn/docs/directus/self-hosted/quickstart This step prompts the user to create the initial administrator account for the Directus instance, requiring an email and password for login. ```bash Create your first admin user: ? Email: admin@example.com ? Password: ******** ``` -------------------------------- ### Start Directus Documentation Development Server Source: https://ezdoc.cn/docs/directus/contributing/running-locally These commands set up and start the development server for the Directus public website documentation. This process requires cloning the separate "directus/docs" repository first, then installing its dependencies and starting its dev server. ```bash pnpm install pnpm dev ``` -------------------------------- ### Configure Directus Start Script in package.json Source: https://ezdoc.cn/docs/directus/self-hosted/manual This JSON snippet shows how to add a "start" script to your "package.json" file, aliasing it to "directus start". This simplifies deployment to cloud platforms like AWS, Google Cloud Platform, or DigitalOcean. ```json { "scripts": { "start": "directus start" } } ``` -------------------------------- ### Select Directus Database Client Source: https://ezdoc.cn/docs/directus/self-hosted/quickstart During the Directus project initialization, this prompt allows the user to select the desired database client, such as SQLite, using arrow keys. ```bash ? Choose your database client SQLite ``` -------------------------------- ### Confirm Directus Database File Path Source: https://ezdoc.cn/docs/directus/self-hosted/quickstart After selecting the database client, Directus suggests a default file path for the database. Users can press Enter to accept the default or specify a custom path. ```bash ? Database File Path: /example-project/data.db ``` -------------------------------- ### Directus Database Configuration Options Source: https://ezdoc.cn/docs/directus/self-hosted/quickstart Details the additional database configuration parameters that may be prompted when linking Directus to different SQL database types, beyond SQLite. These options allow for specifying connection details like host, port, database name, user credentials, and SSL settings. ```APIDOC Database Host: IP address of the database. Port: Port number where the database is running. Database Name: Name of the existing database. Database User: Name of an existing user in the database. Database Password: Password for accessing the database. Enable SSL: Choose 'Y' for yes or 'N' for no. Root: Provide a root name. ``` -------------------------------- ### Create Directus Cloud Community Project Source: https://ezdoc.cn/docs/directus/cloud/projects Step-by-step guide to creating a new free Directus Cloud Community project. This process is straightforward and suitable for non-production activities, allowing quick setup for testing or personal use. ```APIDOC Steps to Create a Community Project: 1. Open the team menu in the dashboard header and select the desired team. 2. Click "项目" (Projects). 3. Click "创建项目" (Create Project). 4. Set the Project Name. 5. Select the Community tier. 6. Scroll to the bottom of the screen and select a starting template. 7. Click "创建项目" (Create Project). ``` -------------------------------- ### Get Directus Server Installation Information Source: https://ezdoc.cn/docs/directus/reference/system/server Retrieves detailed information about the current Directus server installation. Public information is available to all users, while logged-in and admin users receive additional details like rate limits, Directus version, Node.js version, and OS specifics. ```APIDOC Endpoint: /server/info Method: GET Description: Information about the current Directus installation. Permissions: Public information for all. Logged-in users get rateLimit info. Admin users get directus.version, node.version, os.type, etc. Returns: project: object (Public information, used for Admin App public pages. See Settings object for details.) rateLimit: false | object (For logged-in users) points: number (Points allowed per duration if rate limiter is enabled) duration: number (Duration in seconds for point calculation) directus.version: string (Current Directus version, for admin users) node.version: string (Current Node.js version, for admin users) node.uptime: integer (Current process uptime, for admin users) os.type: string (Operating system type, for admin users) os.version: string (Operating system version, for admin users) os.uptime: string (Operating system uptime, for admin users) os.totalmem: string (Total available memory, for admin users) ``` ```REST GET /server/info ``` ```GraphQL POST /graphql/system type Query { server_info: server_info } ``` -------------------------------- ### Install Directus Core Package Source: https://ezdoc.cn/docs/directus/self-hosted/manual This command installs the Directus core package as a dependency in your project. It's a crucial step after initializing the project and before configuring the environment. ```bash npm install directus ``` -------------------------------- ### Install Directus Package Extension via npm Source: https://ezdoc.cn/docs/directus/extensions/creating-extensions This bash command sequence outlines the process for installing a Directus package extension from the npm registry. It requires navigating into the Directus project folder before executing `npm install` with the full package name of the desired extension. ```bash cd npm install ``` -------------------------------- ### Install Dependencies and Build Directus Project Source: https://ezdoc.cn/docs/directus/contributing/running-locally These commands install all project dependencies using pnpm and then build all packages within the Directus monorepo. This step is crucial to prepare the entire project for local development and ensure all components are compiled. ```bash pnpm install pnpm -r build ``` -------------------------------- ### Accessing Directus Internal Systems in Custom Panels Source: https://ezdoc.cn/docs/directus/extensions/panels This JavaScript example demonstrates how to access Directus's internal API and store systems within a custom panel's Vue `setup()` function. It utilizes `useApi()` and `useStores()` from the `@directus/extensions-sdk` to obtain instances of the API client and various stores, enabling interaction with Directus functionalities like collections. ```JavaScript import { useApi, useStores } from '@directus/extensions-sdk' export default { setup() { const api = useApi() const { useCollectionsStore } = useStores() const collectionsStore = useCollectionsStore() // ... }, } ``` -------------------------------- ### Bootstrap Directus Project Source: https://ezdoc.cn/docs/directus/self-hosted/manual This command runs the Directus bootstrap process, which typically sets up the database schema and initial configuration. Ensure your ".env" file with database information is set up before running this. ```bash npx directus bootstrap ``` -------------------------------- ### Start Multiple Directus Component Development Servers Source: https://ezdoc.cn/docs/directus/contributing/running-locally These commands demonstrate how to start development servers for multiple specific Directus components (e.g., API and App) in separate terminal instances. This approach provides more control and is ideal for parallel development of different parts of the application. ```bash pnpm --filter directus dev ``` ```bash pnpm --filter @directus/app dev ``` -------------------------------- ### Directus: Basic Custom API Endpoint Entry Point in JavaScript Source: https://ezdoc.cn/docs/directus/extensions/endpoints This JavaScript code illustrates the fundamental entry point for a Directus custom API endpoint. It exports a default function that registers a simple GET route at the root ('/'). This route serves as a basic example, responding with a 'Hello, World!' message. ```js export default (router) => { router.get('/', (req, res) => res.send('Hello, World!')) } ``` -------------------------------- ### Install Directus JS SDK Source: https://ezdoc.cn/docs/directus/reference/sdk This command installs the Directus JavaScript SDK using npm, a package manager for Node.js. It's the essential first step to integrate the SDK into your project, enabling interaction with the Directus API. ```bash npm install @directus/sdk ``` -------------------------------- ### Initialize Node.js Project for Directus Source: https://ezdoc.cn/docs/directus/self-hosted/manual This command initializes a new Node.js project in the current directory, creating a default "package.json" file. It's the first step in setting up a Directus project. ```bash npm init -y ``` -------------------------------- ### Access Directus Internal Systems (API, Stores) in Custom Module Source: https://ezdoc.cn/docs/directus/extensions/modules This JavaScript code demonstrates how to access Directus internal systems like the API and stores within a custom module using the `@directus/extensions-sdk`. It shows the usage of `useApi()` and `useStores()` composables within the `setup()` function to get instances of the API client and collection store. ```JavaScript import { useApi, useStores } from '@directus/extensions-sdk' export default { setup() { const api = useApi() const { useCollectionsStore } = useStores() const collectionsStore = useCollectionsStore() // ... }, } ``` -------------------------------- ### Start All Directus Development Servers Source: https://ezdoc.cn/docs/directus/contributing/running-locally This command starts the development server for all Directus packages simultaneously. It allows you to run the entire application locally for comprehensive development and testing. Be aware that race conditions might occur when running all packages. ```bash pnpm -r dev ``` -------------------------------- ### Example GraphQL Query to List Webhooks Source: https://ezdoc.cn/docs/directus/reference/system/webhooks An example GraphQL query demonstrating how to retrieve the URL and method of all webhooks. This query illustrates a basic usage pattern for fetching specific fields from multiple webhook entries. ```GraphQL query { webhooks { url method } } ``` -------------------------------- ### Run Directus End-to-End Tests Locally Source: https://ezdoc.cn/docs/directus/contributing/running-locally These commands prepare and execute the end-to-end tests for Directus locally. The process involves building the codebase, cleaning up previous Docker containers, starting necessary Docker services, and then running the tests. Docker must be installed and actively running for this to work. ```bash pnpm -r build docker compose -f tests/docker-compose.yml down -v docker compose -f tests/docker-compose.yml up -d --wait pnpm test:e2e ``` -------------------------------- ### Directus Filter Rule Usage Examples Source: https://ezdoc.cn/docs/directus/reference/filter-rules Illustrates common filter rule applications with examples for string containment, current user matching, and date comparisons. These examples demonstrate how to apply operators like `_contains`, `_eq`, and `_lte`. ```json { "title": { "_contains": "Directus" } } { "owner": { "_eq": "$CURRENT_USER" } } { "datetime": { "_lte": "$NOW" } } ``` -------------------------------- ### Start Specific Directus Component Development Server Source: https://ezdoc.cn/docs/directus/contributing/running-locally This command starts the development server for a specific Directus component, such as the API. This is useful for focused development, debugging, or to avoid race conditions that can occur when running all packages at once. ```bash pnpm --filter directus dev ``` -------------------------------- ### Directus Custom Operation App Entry Point JavaScript Example Source: https://ezdoc.cn/docs/directus/extensions/operations This JavaScript code block provides an example of the configuration object for a custom operation's App entry point in Directus. It defines properties like `id`, `name`, `icon`, `description`, `overview` for display, and `options` for user input within the Directus App interface. ```javascript export default { id: 'custom', name: 'Custom', icon: 'box', description: 'This is my custom operation!', overview: ({ text }) => [ { label: 'Text', text, }, ], options: [ { field: 'text', name: 'Text', type: 'string', meta: { width: 'full', interface: 'input', }, }, ], } ``` -------------------------------- ### Create Directus Cloud Standard Project Source: https://ezdoc.cn/docs/directus/cloud/projects Step-by-step guide to creating a new production-ready Directus Cloud Standard project. This process involves selecting configuration options and proceeding to checkout for payment, enabling a scalable and robust Directus instance. ```APIDOC Steps to Create a Standard Project: 1. Open the team menu in the dashboard header and select the desired team. 2. Click "项目" (Projects). 3. Click the team under which you want to create the project. 4. Click "创建项目" (Create Project). 5. Set the Project Name as needed. 6. Select the Standard tier. 7. Set configuration options as needed. 8. Click "继续结帐" (Continue to Checkout). You will be taken to the checkout page. 9. Enter payment information and click "订阅" (Subscribe). ``` -------------------------------- ### Directus Database Schema Application and Migration Execution Source: https://ezdoc.cn/docs/directus/extensions/migrations Outlines the command-line steps to properly set up a Directus database. This includes installing the database, applying a schema snapshot from a YAML file, and then running the latest custom migrations, ensuring schema consistency before migration execution. ```bash npx directus database install # notice that schema is applied before running migrations npx directus schema apply ./path/to/snapshot.yaml npx directus database migrate:latest ``` -------------------------------- ### Directus config.yaml Configuration File Example Source: https://ezdoc.cn/docs/directus/self-hosted/config-options This YAML snippet demonstrates configuring Directus using a config.yaml file. It uses YAML's key-value pair syntax to define configuration parameters, similar to environment variables. ```yaml HOST: 0.0.0.0 PORT: 8055 DB_CLIENT: pg DB_HOST: localhost DB_PORT: 5432 # # etc ``` -------------------------------- ### Directus Environment Variable Type Conversion Input Examples Source: https://ezdoc.cn/docs/directus/self-hosted/config-options These examples illustrate how Directus automatically converts environment variable string values into appropriate data types (string, number, boolean, array) based on their content. This simplifies configuration by reducing the need for explicit type parsing. ```plaintext PUBLIC_URL="https://example.com" DB_HOST="3306" CORS_ENABLED="false" STORAGE_LOCATIONS="s3,local,example" ``` -------------------------------- ### Accessing Directus Internal Systems (API, Stores) Source: https://ezdoc.cn/docs/directus/extensions/layouts This JavaScript snippet demonstrates how to access Directus internal systems like the API and stores using `useApi()` and `useStores()` composables from `@directus/extensions-sdk` within the `setup()` function of a layout. ```javascript import { useApi, useStores } from '@directus/extensions-sdk' export default { setup() { const api = useApi() const { useCollectionsStore } = useStores() const collectionsStore = useCollectionsStore() // ... }, } ``` -------------------------------- ### Example Directus Webhook Object JSON Source: https://ezdoc.cn/docs/directus/reference/system/webhooks An example JSON representation of a Directus Webhook object, illustrating typical values for its properties like ID, name, method, URL, status, data, actions, and collections. This example helps in understanding the expected data format when interacting with the Webhooks API. ```JSON { "data": { "id": 1, "name": "Build Website", "method": "POST", "url": "https://example.com/", "status": "active", "data": true, "actions": ["create", "update"], "collections": ["articles"] } } ``` -------------------------------- ### Example Directus Collection JSON Representation Source: https://ezdoc.cn/docs/directus/reference/system/collections A JSON example demonstrating the typical structure and values for a Directus Collection object. This snippet illustrates how a collection's core properties, metadata, and schema information are represented in a JSON format. ```JSON { "collection": "articles", "meta": { "collection": "articles", "icon": "article", "note": "Blog posts", "display_template": "{{ title }}", "hidden": false, "singleton": false, "translations": [ { "language": "en-US", "translation": "Articles" }, { "language": "nl-NL", "translation": "Artikelen" } ], "archive_field": "status", "archive_value": "archived", "unarchive_value": "draft", "archive_app_filter": true, "sort_field": "sort", "item_duplication_fields": null, "sort": 1 }, "schema": { "name": "pages", "comment": null } } ``` -------------------------------- ### Directus: Custom API Endpoint with Configuration Object in JavaScript Source: https://ezdoc.cn/docs/directus/extensions/endpoints This JavaScript example demonstrates defining a Directus custom API endpoint using a configuration object. It allows specifying a unique 'id' for the endpoint's root path and registering multiple GET routes. This approach provides more control over the endpoint's base URL and structure. ```js export default { id: 'greet', handler: (router) => { router.get('/', (req, res) => res.send('Hello, World!')) router.get('/intro', (req, res) => res.send('Nice to meet you.')) router.get('/goodbye', (req, res) => res.send('Goodbye!')) } } ``` -------------------------------- ### Example GraphQL Query to Retrieve Webhook by ID Source: https://ezdoc.cn/docs/directus/reference/system/webhooks An example GraphQL query demonstrating how to retrieve the URL, actions, and method of a specific webhook by its ID. This query showcases how to fetch selected fields for a single webhook entry. ```GraphQL query { webhooks_by_id(id: 15) { url actions method } } ``` -------------------------------- ### Directus .env Configuration File Example Source: https://ezdoc.cn/docs/directus/self-hosted/config-options This snippet shows the structure of a .env file for Directus configuration, where each line defines an environment variable in key=value format. It includes common settings like host, port, and database connection details. ```plaintext HOST="0.0.0.0" PORT=8055 DB_CLIENT="pg" DB_HOST="localhost" DB_PORT=5432 etc ``` -------------------------------- ### Directus Hook Extension Entry Point Example (JavaScript) Source: https://ezdoc.cn/docs/directus/extensions/hooks This JavaScript code demonstrates the basic structure for a Directus custom API hook extension. It exports a default function that receives `filter` and `action` functions to register event listeners. This example logs messages when items are created, showing both pre-event (filter) and post-event (action) execution. ```js export default ({ filter, action }) => { filter('items.create', () => { console.log('Creating Item!') }) action('items.create', () => { console.log('Item created!') }) } ``` -------------------------------- ### Directus config.json Configuration File Example Source: https://ezdoc.cn/docs/directus/self-hosted/config-options This JSON snippet illustrates how to configure Directus using a config.json file. It maps environment variable names as keys to their corresponding values within a standard JSON object structure. ```json { "HOST": "0.0.0.0", "PORT": 8055, "DB_CLIENT": "pg", "DB_HOST": "localhost", "DB_PORT": 5432 // etc } ``` -------------------------------- ### Clone Directus Repository Source: https://ezdoc.cn/docs/directus/contributing/running-locally This command clones the Directus repository from your GitHub fork to your local machine. Replace "YOUR-USERNAME" with your actual GitHub username to get your copy of the source code. ```bash git clone git@github.com:YOUR-USERNAME/directus.git ``` -------------------------------- ### Directus API: Basic Assign One-to-Many/Many-to-Many Items Source: https://ezdoc.cn/docs/directus/reference/introduction Example JSON payload for basic assignment of existing items in one-to-many or many-to-many relationships. Provide an array of primary keys. ```JSON { "children": [2, 7, 149] } ``` -------------------------------- ### Directus Custom Layout Vue Component Example Source: https://ezdoc.cn/docs/directus/extensions/layouts This Vue Single File Component (SFC) example shows a basic structure for a custom layout component in Directus. It defines required props like 'collection' and 'name' and renders them in a simple template, demonstrating how layout components receive data. ```vue ``` -------------------------------- ### Get GraphQL SDL for Directus Server Source: https://ezdoc.cn/docs/directus/reference/system/server Retrieves the GraphQL Schema Definition Language (SDL) for the current Directus project. The SDL is generated based on the permissions of the authenticated user. ```APIDOC Endpoint: /server/specs/graphql/ Method: GET Description: Retrieve the current project's GraphQL SDL. Permissions: Based on the authenticated user's permissions. Returns: GraphQL SDL file. Example SDL Structure: type about_us { id: Int introduction: String our_process: String sales_email: String general_email: String primary_color: String secondary_color: String logo: directus_files mark: directus_files } type articles { id: Int status: String # etc } ``` ```REST GET /server/specs/graphql/ GET /server/specs/graphql/system ``` ```GraphQL POST /graphql/system type Query { server_specs_graphql(scope: graphql_sdl_scope): String } query { server_specs_graphql(scope: system) } ``` -------------------------------- ### Directus Custom Layout Entry Point Configuration Source: https://ezdoc.cn/docs/directus/extensions/layouts This JavaScript snippet demonstrates the configuration object exported by a custom layout's entry point file. It defines the layout's ID, name, icon, component reference, slot components (options, sidebar, actions), and a setup function for reactive state. ```javascript import { ref } from 'vue' import LayoutComponent from './layout.vue' export default { id: 'custom', name: 'Custom', icon: 'box', component: LayoutComponent, slots: { options: () => null, sidebar: () => null, actions: () => null, }, setup() { const name = ref('Custom Layout') return { name } }, } ``` -------------------------------- ### Configure Directus Role Permissions Source: https://ezdoc.cn/docs/directus/configuration/users-roles-permissions Guide to setting up granular permissions for a Directus role, including collection and CRUD operations, and custom access levels. ```APIDOC PERMISSION_CONFIGURATION: GENERAL: - Changes are automatically saved. - Roles with 'admin_access' enabled have full platform access, and permission configuration is disabled. STEPS: 1. Navigate: Settings > Roles & Permissions > {Role Name} 2. Section: Scroll to 'Permissions' 3. Action: Click the icon for the desired collection (row) and operation (column). 4. Selection: Choose permission level: - "check All Access" - "block No Access" - "rule Custom" CUSTOM_ACCESS_FOR_CREATE_OPERATION: - Field Permissions: Controls which fields accept values during creation. Fields are toggled individually. - Field Validation: Defines rules for validating field values upon creation. - Field Presets: Controls default values for fields when an item is created. ``` -------------------------------- ### Directus API: Basic Create/Update/Assign One-to-Many/Many-to-Many Items Source: https://ezdoc.cn/docs/directus/reference/introduction Example JSON payload for basic create, update, or assign operations in one-to-many or many-to-many relationships. Mix primary keys and objects for new or updated items. ```JSON { "children": [ 2, // assign existing item 2 to be a child of the current item { "name": "A new nested item" }, { "id": 149, "name": "Assign and update existing item 149" } ] } ``` -------------------------------- ### Set CONFIG_PATH Environment Variable for Directus Source: https://ezdoc.cn/docs/directus/self-hosted/config-options This bash command demonstrates how to set the CONFIG_PATH environment variable before starting Directus, allowing it to load configuration from a specified file path instead of the default .env. ```bash CONFIG_PATH="/path/to/config.js" npx directus start ``` -------------------------------- ### Directus API: Detailed Create/Update/Delete One-to-Many/Many-to-Many Items Source: https://ezdoc.cn/docs/directus/reference/introduction Example JSON payload for detailed control over changes in one-to-many or many-to-many relationships. Use 'create', 'update', and 'delete' arrays for precise operations. ```JSON { "children": { "create": [{ "name": "A new nested item" }], "update": [{ "id": 149, "name": "A new nested item" }], "delete": [7] } } ``` -------------------------------- ### Directus Schema Diff Request Example Source: https://ezdoc.cn/docs/directus/reference/system/schema Demonstrates a `multipart/form-data` request to the `/schema/diff` endpoint, including a sample `schema.yaml` payload. This request is used to retrieve schema differences from a Directus instance. ```yaml POST /schema/diff Content-Type: multipart/form-data; charset=utf-8; boundary=__X_BOUNDARY__ Content-Length: 3442422 --__X_BOUNDARY__ Content-Disposition: form-data; name="file"; filename="schema.yaml" Content-Type: text/yaml version: 1 directus: 9.22.4 vendor: sqlite collections: - collection: articles meta: accountability: all archive_app_filter: true archive_field: null archive_value: null collapse: open collection: articles color: null display_template: null group: null hidden: false icon: null item_duplication_fields: null note: null singleton: false sort: null sort_field: null translations: null unarchive_value: null schema: name: articles fields: - collection: articles field: id type: integer meta: collection: articles conditions: null display: null display_options: null field: id group: null hidden: true interface: input note: null options: null readonly: true required: false sort: null special: null translations: null validation: null validation_message: null width: full schema: name: id table: articles data_type: integer default_value: null max_length: null numeric_precision: null numeric_scale: null is_nullable: false is_unique: false is_primary_key: true is_generated: false generation_expression: null has_auto_increment: true foreign_key_table: null foreign_key_column: null - collection: articles field: title type: string meta: collection: articles conditions: null display: null display_options: null field: title group: null hidden: false interface: input note: null options: null readonly: false required: false sort: null special: null translations: null validation: null validation_message: null width: full schema: name: title table: articles data_type: varchar default_value: null max_length: 255 numeric_precision: null numeric_scale: null is_nullable: true is_unique: false is_primary_key: false is_generated: false generation_expression: null has_auto_increment: false foreign_key_table: null foreign_key_column: null relations: [] ``` -------------------------------- ### Directus Environment Variable Type Conversion Output Examples Source: https://ezdoc.cn/docs/directus/self-hosted/config-options This JSON snippet shows the resulting data types after Directus automatically converts the input environment variable strings. It demonstrates how strings become numbers, booleans, or arrays, simplifying their use in the application. ```json // "https://example.com" // 3306 // false // ["s3", "local", "example"] ``` -------------------------------- ### Directus Configuration Syntax Prefixes Source: https://ezdoc.cn/docs/directus/self-hosted/config-options Directus allows explicit type casting for environment variables using syntax prefixes. This documentation details available prefixes like string, number, regex, array, and json, along with examples of their usage and the resulting output types. ```APIDOC Syntax Prefixes for Directus Environment Variables: - string: Example: "string:value" Output: "\"value\"" - number: Example: "number:3306" Output: "3306" - regex: Example: "regex:\\.example\\.com$" Output: "/\\.example\\.com$/" - array: Example 1: "array:https://example.com,https://example2.com" Output 1: "[\"https://example.com\", \"https://example2.com\"]" Example 2: "array:string:https://example.com,regex:\\.example3\\.com$" Output 2: "[\"https://example.com\", \"https://example2.com\", /\\.example3\\.com$/]" - json: Example: "json:{\"items\": [\"example1\", \"example2\"]}" Output: "{\"items\": [\"example1\", \"example2\"]}" ``` -------------------------------- ### Directus API Global Query Parameters - Fields Examples Source: https://ezdoc.cn/docs/directus/reference/query This section illustrates various ways to select fields in Directus API queries using the "fields" parameter. It covers dot notation for nested relationships and wildcard usage for different depths. It also provides a best practice recommendation to request only specific fields for production use to optimize query speed and reduce output size. ```APIDOC ?fields=* ``` ```APIDOC ?fields=*.* ``` ```APIDOC ?fields=*,images.* ``` ```APIDOC ?fields=first_name,last_name ``` ```APIDOC ?fields=*.*,images.thumbnails.* ``` -------------------------------- ### Create Single Dashboard Source: https://ezdoc.cn/docs/directus/reference/system/dashboards This snippet demonstrates how to create a single dashboard. It includes examples for both REST API (POST /dashboards) and GraphQL, showing the request body structure and the corresponding mutation. ```APIDOC REST API: POST /dashboards ``` ```json { "name": "My Dashboard", "icon": "dashboard" } ``` ```APIDOC GraphQL: POST /graphql/system type Mutation { create_dashboards_item(data: create_directus_dashboards_input!): directus_dashboards } ``` ```graphql mutation { create_dashboards_item(data: { name: "My Dashboard", icon: "dashboards" }) { id name } } ``` -------------------------------- ### Directus Custom Operation API Entry Point JavaScript Example Source: https://ezdoc.cn/docs/directus/extensions/operations This JavaScript code block illustrates the configuration object for a custom operation's API entry point in Directus. It specifies the operation's `id` and the `handler` function responsible for executing the operation's core logic when triggered by a flow. ```javascript export default { id: 'custom', handler: ({ text }) => { console.log(text) }, } ``` -------------------------------- ### Directus Schema Diff Output Example Source: https://ezdoc.cn/docs/directus/reference/system/schema This JSON snippet illustrates the structure of a Directus schema difference report. It details newly added collections (e.g., 'articles') and their respective fields ('id', 'title'), including their metadata and schema definitions. This output is typically generated when comparing two different states of a Directus project's data model. ```json { "hash": "2b3c71570228b864e16098147e5497f61b245a42", "diff": { "collections": [ { "collection": "articles", "diff": [ { "kind": "N", "rhs": { "collection": "articles", "meta": { "accountability": "all", "archive_app_filter": true, "archive_field": null, "archive_value": null, "collapse": "open", "collection": "articles", "color": null, "display_template": null, "group": null, "hidden": false, "icon": null, "item_duplication_fields": null, "note": null, "singleton": false, "sort": null, "sort_field": null, "translations": null, "unarchive_value": null }, "schema": { "name": "articles" } } } ] } ], "fields": [ { "collection": "articles", "field": "id", "diff": [ { "kind": "N", "rhs": { "collection": "articles", "field": "id", "type": "integer", "meta": { "collection": "articles", "conditions": null, "display": null, "display_options": null, "field": "id", "group": null, "hidden": true, "interface": "input", "note": null, "options": null, "readonly": true, "required": false, "sort": null, "special": null, "translations": null, "validation": null, "validation_message": null, "width": "full" }, "schema": { "name": "id", "table": "articles", "data_type": "integer", "default_value": null, "max_length": null, "numeric_precision": null, "numeric_scale": null, "is_nullable": false, "is_unique": false, "is_primary_key": true, "is_generated": false, "generation_expression": null, "has_auto_increment": true, "foreign_key_table": null, "foreign_key_column": null } } } ] }, { "collection": "articles", "field": "title", "diff": [ { "kind": "N", "rhs": { "collection": "articles", "field": "title", "type": "string", "meta": { "collection": "articles", "conditions": null, "display": null, "display_options": null, "field": "title", "group": null, "hidden": false, "interface": "input", "note": null, "options": null, "readonly": false, "required": false, "sort": null, "special": null, "translations": null, "validation": null, "validation_message": null, "width": "full" }, "schema": { "name": "title", "table": "articles", "data_type": "varchar", "default_value": null, "max_length": 255, "numeric_precision": null, "numeric_scale": null, "is_nullable": true, "is_unique": false, "is_primary_key": false, "is_generated": false, "generation_expression": null, "has_auto_increment": false, "foreign_key_table": null, "foreign_key_column": null } } } ] } ], "relations": [] } } ``` -------------------------------- ### Directus: Fetching Recipes with Custom API Endpoint in JavaScript Source: https://ezdoc.cn/docs/directus/extensions/endpoints This JavaScript example demonstrates a Directus custom API endpoint designed to fetch 'recipes' data. It utilizes the `ItemsService` to query and retrieve items from the 'recipes' collection, sorting them by name. The endpoint handles potential errors by catching exceptions and returning a `ServiceUnavailableException`. ```js export default (router, { services, exceptions }) => { const { ItemsService } = services const { ServiceUnavailableException } = exceptions router.get('/', (req, res, next) => { const recipeService = new ItemsService('recipes', { schema: req.schema, accountability: req.accountability }) recipeService .readByQuery({ sort: ['name'], fields: ['*'] }) .then(results => res.json(results)) .catch((error) => { return next(new ServiceUnavailableException(error.message)) }) }) } ``` -------------------------------- ### Initialize Directus Database Source: https://ezdoc.cn/docs/directus/contributing/running-locally This command bootstraps the Directus database, creating all necessary tables and running migrations. It must be executed from the "api" directory context. Ensure you have a SQL database running or are using SQLite, which will create a file-based database. ```bash pnpm --dir api cli bootstrap ``` -------------------------------- ### Scaffold Directus Extension Project with CLI Source: https://ezdoc.cn/docs/directus/extensions/creating-extensions This command initializes a new Directus extension project using the `create-directus-extension` utility. It interactively prompts for the extension's name, type, and preferred programming language, then sets up the recommended file structure for development. ```bash npm init directus-extension ``` -------------------------------- ### Initialize Directus JS SDK Instance Source: https://ezdoc.cn/docs/directus/reference/sdk This code snippet demonstrates how to import the Directus class and create a new instance, pointing it to your Directus API endpoint. This instance serves as the primary entry point for all subsequent interactions with your Directus project. ```js import { Directus } from '@directus/sdk' const directus = new Directus('http://directus.example.com') ``` -------------------------------- ### Build Directus Extension using npm Script Source: https://ezdoc.cn/docs/directus/extensions/creating-extensions This command compiles and bundles the Directus extension for deployment. It executes a predefined script in `package.json` that calls the `directus-extension` CLI from the `@directus/extensions-sdk` to process source files. ```bash npm run build ``` -------------------------------- ### Directus Relationship Filtering Examples Source: https://ezdoc.cn/docs/directus/reference/filter-rules Demonstrates how to filter data based on related fields, including one-to-many and many-to-many relationships. Examples show filtering by a related author's name and filtering through a junction table for M2M relationships. ```json { "author": { "name": { "_eq": "Rijk van Zanten" } } } { "authors": { "authors_id": { "name": { "_eq": "Rijk van Zanten" } } } } ``` -------------------------------- ### Directus Custom Panel Entry Point Configuration Options Source: https://ezdoc.cn/docs/directus/extensions/panels This API documentation details the available configuration options for a Directus custom panel's entry point object. It covers properties such as the unique identifier, display name, associated icon, a short description, the component reference, user-configurable options, and minimum dimensions for placement on a dashboard. ```APIDOC id: string — Unique key for this panel. Best to scope proprietary panels with an author prefix. name: string — Human-readable name for this panel. icon: string — Name of an icon from the material icon set, or an extended list of Directus custom icons. description: string — Short description (<80 characters) for this panel displayed in the app. component: reference — Reference to the panel component. options: object | Vue Component — Options for the panel, can be an options object or a dedicated Vue component. minWidth: number — Minimum width of the panel on the dashboard (in grid units). minHeight: number — Minimum height of the panel on the dashboard (in grid units). ``` -------------------------------- ### Directus JS SDK Constructor for Custom Configuration Source: https://ezdoc.cn/docs/directus/reference/sdk This snippet illustrates the constructor signature for the Directus SDK, enabling custom configuration. It shows how to import the Directus class and instantiate it with a URL and an optional init object for advanced settings. ```js import { Directus } from '@directus/sdk' const directus = new Directus(url, init) ``` -------------------------------- ### Directus API: Basic Remove One-to-Many/Many-to-Many Items Source: https://ezdoc.cn/docs/directus/reference/introduction Example JSON payload for basic removal of items from one-to-many or many-to-many relationships. Omit items from the array to remove them. ```JSON { "children": [2, 149] } ``` -------------------------------- ### Directus API: Delete Many-to-One Related Item Source: https://ezdoc.cn/docs/directus/reference/introduction Example JSON payload to delete a related item in a many-to-one relationship by setting its field to null. This invalidates the foreign key. ```JSON { "featured_article": null } ``` -------------------------------- ### Delete Single or Multiple Items Source: https://ezdoc.cn/docs/directus/reference/sdk Deletes one or more items from a collection. Examples include deleting a single item by ID or multiple items using an array of IDs. ```js // One await articles.deleteOne(15) // Multiple await articles.deleteMany([15, 42]) ``` -------------------------------- ### Directus Layouts: Overview and Purpose Source: https://ezdoc.cn/docs/directus/app/layouts This section defines what layouts are in Directus, explaining how they provide a more human-friendly and intuitive display for interacting with data compared to raw SQL table representations. It emphasizes their role in adapting to diverse data models. ```APIDOC Layouts: Purpose: Custom displays for viewing and interacting with items in a collection. Benefit: Provides a more human-friendly and intuitive display for data models (e.g., map locations, calendar events) than raw SQL tables. Analogy: While data is stored in collections (SQL tables), layouts offer a more intuitive view than an Excel-style data sheet. ``` -------------------------------- ### Get OpenAPI Specification for Directus Server Source: https://ezdoc.cn/docs/directus/reference/system/server Retrieves the OpenAPI Specification (OAS) for the current Directus project. The returned OAS is tailored based on the read permissions of the authenticated user. ```APIDOC Endpoint: /server/specs/oas Method: GET Description: Retrieve the current project's OpenAPI specification. Permissions: Based on the authenticated user's read permissions. Returns: An object conforming to the OpenAPI Specification (OAS). ``` ```REST GET /server/specs/oas ``` ```GraphQL POST /graphql/system type Query { server_specs_oas: String } query { server_specs_oas } ``` -------------------------------- ### Directus JS SDK Constructor Parameters API Reference Source: https://ezdoc.cn/docs/directus/reference/sdk This section provides detailed API documentation for the parameters of the Directus SDK constructor. It specifies the url parameter, including its type, a description of its purpose (pointing to the Directus instance), and its default value. ```APIDOC Parameters: url: Type: String Description: String pointing to your Directus instance. E.g., https://example.directus.io Default: N/A ``` -------------------------------- ### Directus Schema API Endpoints Overview Source: https://ezdoc.cn/docs/directus/reference/system/schema An overview of the primary REST API endpoints available for managing the Directus instance schema, including retrieving snapshots, comparing schemas, and applying differences. ```APIDOC Directus Schema API Endpoints: 1. /schema/snapshot: Retrieve the current snapshot of the instance's schema. 2. /schema/diff: Compare a snapshot with another instance's schema (e.g., new instance or instance in a different environment) and retrieve a 'diff' containing all differences. 3. /schema/apply: Update another instance's schema based on a previously obtained diff. ``` -------------------------------- ### Directus Extension Build Script in package.json Source: https://ezdoc.cn/docs/directus/extensions/creating-extensions This JSON snippet illustrates the `scripts` section within a `package.json` file, defining the `build` command. This script directly invokes the `directus-extension` CLI, which is part of the `@directus/extensions-sdk`, to manage the extension's compilation process. ```json { "scripts": { "build": "directus-extension build" } } ``` -------------------------------- ### Directus API: Update Many-to-One Related Item Source: https://ezdoc.cn/docs/directus/reference/introduction Example JSON payload to update an existing related item in a many-to-one relationship. Provide the item's ID along with the fields to update. ```JSON { "featured_article": { "id": 15, "title": "This is an updated title for my article!" } } ``` -------------------------------- ### Upload a File from Browser Source: https://ezdoc.cn/docs/directus/reference/sdk Illustrates how to upload a file from a web browser using `multipart/form-data`. Includes both JavaScript for handling the upload and HTML for the form structure. ```js /* index.js */ import { Directus } from 'https://unpkg.com/@directus/sdk@latest/dist/sdk.esm.min.js' const directus = new Directus('https://example.directus.app', { auth: { staticToken: 'STATIC_TOKEN', // If you want to use a static token, see below for how to use email and password. }, }) // await directus.auth.login({ email, password }) If you want to use email and password, remove the staticToken above. const form = document.querySelector('#upload-file') if (form && form instanceof HTMLFormElement) { form.addEventListener('submit', async (event) => { event.preventDefault() const form = new FormData(event.target) await directus.files.createOne(form) }) } ``` ```html
```