docs/docs/en/plugin-development/server/data-source-manager.md
NocoBase provides DataSourceManager for managing multiple data sources. Each DataSource has its own Database, ResourceManager, and ACL instances, allowing you to flexibly manage and extend different data sources.
Each DataSource instance contains the following:
dataSource.collectionManager: Used to manage collections and fields.dataSource.resourceManager: Handles resource-related operations (such as CRUD, etc.).dataSource.acl: Access control (ACL) for resource operations.For convenient access, NocoBase provides aliases for main data source members:
app.db is equivalent to dataSourceManager.get('main').collectionManager.dbapp.acl is equivalent to dataSourceManager.get('main').aclapp.resourceManager is equivalent to dataSourceManager.get('main').resourceManagerReturns the specified DataSource instance.
const dataSource = dataSourceManager.get('main');
Register middleware for all data sources, which will affect operations on all data sources.
dataSourceManager.use(async (ctx, next) => {
console.log('This middleware applies to all data sources');
await next();
});
Executes before data source loading. Typically used for static class registration, such as model classes and field type registration:
dataSourceManager.beforeAddDataSource((dataSource: DataSource) => {
const collectionManager = dataSource.collectionManager;
if (collectionManager instanceof SequelizeCollectionManager) {
collectionManager.registerFieldTypes({
belongsToArray: BelongsToArrayField, // Register custom field type
});
}
});
Executes after data source loading. Typically used for registering operations, setting access control, etc.
dataSourceManager.afterAddDataSource((dataSource) => {
dataSource.resourceManager.registerActionHandler('downloadXlsxTemplate', downloadXlsxTemplate);
dataSource.resourceManager.registerActionHandler('importXlsx', importXlsx);
dataSource.acl.allow('*', 'downloadXlsxTemplate', 'loggedIn'); // Logged-in users can access
});
For complete data source extension, please refer to the data source extension chapter.
app object